zoukankan      html  css  js  c++  java
  • springmvc记录(三种处理器映射器、两种处理器适配器、注解开发、参数绑定、处理json、多视图支持)

    录:

    1、mvc和springmvc介绍
    2、Springmvc执行流程
    3、springmvc入门程序
    4、三种处理器映射器
    5、2种处理器适配器
    6、命令控制器
    7、中文乱码解决
    8、时间类型转换
    9、注解开发
    10、转发和重定向
    11、RequestBody/ ResponseBody处理Json数据
    12、参数绑定
    13、springmvc多视图支持

    1、mvc和springmvc介绍    <--返回目录

    1.1、JAVAEE体系结构

    1.2、mvc设计模式

      model 1

       model 2

     1.3、Springmvc是什么

      Springmvc是一个web层mvc框架,类似struts2。Springmvc是spring的一部分

    2、Springmvc执行流程    <--返回目录

      具体流程步骤如下:

    1、首先用户发送请求——>DispatcherServlet,前端控制器收到请求后自己不进行处理,而是委托给其他的解析器进行处理,作为统一访问点,进行全局的流程控制;
    2、DispatcherServlet——>HandlerMapping,HandlerMapping将会把请求映射为HandlerExecutionChain对象(包含一个Handler处理器(页面控制器)对象、
    多个HandlerInterceptor拦截器)对象,通过这种策略模式,很容易添加新的映射策略;
    3、DispatcherServlet——>HandlerAdapter,HandlerAdapter将会把处理器包装为适配器,从而支持多种类型的处理器,即适配器设计模式的应用,
    从而很容易支持很多类型的处理器;
    4、HandlerAdapter——>处理器功能处理方法的调用,HandlerAdapter将会根据适配的结果调用真正的处理器的功能处理方法,完成功能处理;
    并返回一个ModelAndView对象(包含模型数据、逻辑视图名);
    5、ModelAndView的逻辑视图名——> ViewResolver, ViewResolver将把逻辑视图名解析为具体的View,通过这种策略模式,很容易更换其他视图技术; 6、View——>渲染,View会根据传进来的Model模型数据进行渲染,此处的Model实际是一个Map数据结构,因此很容易支持其他视图技术; 7、返回控制权给DispatcherServlet,由DispatcherServlet返回响应给用户,到此一个流程结束。

    3、springmvc入门程序    <--返回目录

    3.1、新建一个 Dynamic Web Project

    3.2、项目结构

    3.3、导入jar

     3.4、代码

       web.xm配置

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
      <display-name>helloworld</display-name>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      
        <!-- post请求编码过滤器 -->
        <filter>
            <filter-name>characterEncoding</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>characterEncoding</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
      
        <!-- 前端控制器DispatcherServlet -->
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!-- 默认加载方式
               默认加载必须规范:
               * 文件命名:servlet-name-servlet.xml====springmvc-servlet.xml
               * 路径规范:必须在WEB-INF目录下面  -->
            <init-param>
               <param-name>contextConfigLocation</param-name>
               <param-value>classpath:springmvc.xml</param-value>   
            </init-param>
        </servlet>
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>*.do</url-pattern>
        </servlet-mapping>
        
    </web-app>

      另外,前端控制器添加 <load-on-startup>2</load-on-startup>使得前端控制器在服务器启动就初始化。

      此处需要特别强调的是 <url-pattern>/</url-pattern>也可以使用/,但不能使用/*。如果使用/*,那么请求时可以通过DispatcherServlet转发到相应的Action或者Controller中的,但是返回的内容,如返回的jsp还会再次被拦截,这样导致404错误,即访问不到jsp。所以如果以后发现总是有404错误的时候,别忘了check一下 <url-pattern>/</url-pattern>的配置是否是/*.

      springmvc.xml 配置三大组件:处理器映射器、处理器适配器、视图解析器

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-3.2.xsd 
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
            
        <!-- 配置处理器映射器,springmvc默认的处理器映射器
             BeanNameUrlHandlerMapping:根据bean(自定义Controler)的name属性的url去寻找hanler(Controller)
         -->
        <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
            
        <!-- 配置处理器适配器执行Controlelr ,springmvc默认的
             SimpleControllerHandlerAdapter:执行Controller
        -->
        <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
        
        <!-- 配置自定义Controler -->
        <bean id="myController" name="/hello.do" class="com.oy.controller.MyController"></bean>
        
        <!-- 配置sprigmvc视图解析器:解析逻辑试图 
              后台返回逻辑试图:index
             视图解析器解析出真正物理视图:前缀+逻辑试图+后缀====/WEB-INF/jsps/index.jsp
        -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsps/"></property>
            <property name="suffix" value=".jsp"></property>        
        </bean>
    </beans>

      hello.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>主页</title>
    </head>
    <body>
    <h2>hello页面</h2><br/>
    ${msg}
    </body>
    </html>
    View Code

      MyController

    package com.oy.controller;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.Controller;
    
    public class MyController implements Controller {
    
        @Override
        public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {
            //接受请求,接受参数,验证参数
            //封装参数,调用业务方法
            //返回视图
            ModelAndView mv = new ModelAndView();
            //设置页面回显数据
            mv.addObject("msg", "欢迎学习springmvc!");
            
            //指定跳转的视图
            //返回物理视图
            //mv.setViewName("/WEB-INF/jsps/hello.jsp");
            //返回逻辑视图
            mv.setViewName("hello");
            return mv;
        }
        
    }

    3.5、测试

      根据web.xml 欢迎页配置

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

      当访问:http://localhost:8080/helloworld/时,访问项目根路径下的index.jsp

       当访问 http://localhost:8080/helloworld/hello.do,通过配置的BeanNameUrlHandlerMapping,根据bean(自定义Controler)的name属性的url去寻找hanler

    4、三种处理器映射器    <--返回目录

      BeanNameUrlHandlerMapping

       SimpleUrlHandlerMaping:功能寻找Controller。根据浏览器url匹配简单url的key,key又Controller的id找到Controller。

      ControllerClassNameHandlerMapping:功能寻找Controller。根据类名(MyController)类名.do来访问,类名首字母小写。

       映射器之间能不能共存?
      3个处理器映射器可以共存。

    5、2种处理器适配器    <--返回目录

      SimpleControllerHandlerAdapter:功能执行controller,调用controller里面方法,返回modelAndView。

       HttpRequestHandlerAdapter

       2个处理器适配器能共存?
      可以共存

    6、命令控制器    <--返回目录

      Springmvc通过命令设计模式接受页面参数。

      自定义命令控制器

       自定义javabean

       封装页面参数

       跳转到add页面:由于add页面在WEB-INF下面不能直接访问,需要通过Controller来访问。

       在springmvc.xml配置bean

    7、中文乱码解决    <--返回目录

    解决Url带中文参数乱码问题(get请求)
        1)配置tomcat的server.xml文件,发布项目的时候可以配置
            <!-- 处理中文乱码 URIEncoding="UTF-8"
            <Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
            -->
        2)开发阶段,配置eclipse下的servers/Tomcat v7.0 Server at localhost-config/server.xml
            事实上,在eclipse下修改的会同步到使用的tomcat服务器。

      get请求乱码解决

      post请求乱码解决

      在web.xml配置

    <!-- post请求编码过滤器 -->
    <filter>
        <filter-name>characterEncoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    8、时间类型转换    <--返回目录

    public class CommandController extends AbstractCommandController{
        
        //指定参数绑定到那个javaBean
        public CommandController(){
            this.setCommandClass(User.class);
        }
    
        @Override
        protected ModelAndView handle(HttpServletRequest request,
                HttpServletResponse response, Object command, BindException errors)
                throws Exception {
            //把命令对象强转成User对象
            User user = (User) command;
            ModelAndView mv = new ModelAndView();
            
            mv.addObject("user", user);
            
            mv.setViewName("index");
            
            return mv;
        }
        
        @Override
        protected void initBinder(HttpServletRequest request,
                ServletRequestDataBinder binder) throws Exception {
            
            String str = request.getParameter("birthday");
            if(str.contains("/")){
                binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy/MM/dd"), true));
            }else{
                binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));    
            }
            
        }
    
    }

    9、注解开发    <--返回目录

    9.1、搭建项目

      jdk1.7+tomcat8.5。

      搭建项目出现:org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class

    20:22:19,028 DEBUG PathMatchingResourcePatternResolver:351 - Resolved location pattern [classpath*:com/oy/**/*.class] to resources [file [D:oy_workspaceeclipse_javaee_win64_workspace.metadata.pluginsorg.eclipse.wst.server.core	mp0wtpwebappshelloworldWEB-INFclassescomoycontrollerUserController.class]]
    20:22:19,043 ERROR DispatcherServlet:466 - Context initialization failed
    org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [D:oy_workspaceeclipse_javaee_win64_workspace.metadata.pluginsorg.eclipse.wst.server.core	mp0wtpwebappshelloworldWEB-INFclassescomoycontrollerUserController.class]; nested exception is java.lang.IllegalArgumentException
        at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:281)
        at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:242)
        at org.springframework.context.annotation.ComponentScanBeanDefinitionParser.parse(ComponentScanBeanDefinitionParser.java:84)
        at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:73)
        

      

      由于之前使用的jdk1.8+tomcat9,现在改为jdk1.7+tomcat8.5。

      eclipse添加一个tomcat server

       将项目添加进tomca提示Project facet Java version 1.8 is not supported.

      首先改变项目jdk

      然后修改项目Java Compiler 和 project facet, 选中项目右键-->Properties-->Java Compiler 或 Project Facets

    9.2、项目结构和jar包

    9.3、代码

      web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
      <display-name>helloworld</display-name>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      
        <!-- post请求编码过滤器 -->
        <filter>
            <filter-name>characterEncoding</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>characterEncoding</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        
        <!-- 前端控制器DispatcherServlet -->
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!-- 默认加载方式
               默认加载必须规范:
               * 文件命名:servlet-name-servlet.xml====springmvc-servlet.xml
               * 路径规范:必须在WEB-INF目录下面  -->
            <init-param>
               <param-name>contextConfigLocation</param-name>
               <param-value>classpath:springmvc.xml</param-value>   
            </init-param>
            <load-on-startup>2</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>*.do</url-pattern>
        </servlet-mapping>
        
    </web-app>

      springmvc.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-3.2.xsd 
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
            
        <context:component-scan base-package="com.oy"></context:component-scan>
            
        <!-- 配置注解处理器映射器 
            功能:寻找执行类Controller -->
        <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
            
        <!-- 配置注解处理器适配器 
            功能:调用controller方法,执行controller -->
        <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>
    
        <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
        <!-- 配置sprigmvc视图解析器:解析逻辑试图 
              后台返回逻辑试图:index
             视图解析器解析出真正物理视图:前缀+逻辑试图+后缀====/WEB-INF/jsps/index.jsp
        -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsps/"></property>
            <property name="suffix" value=".jsp"></property>        
        </bean>
    </beans>

      log4j.properties

    ### direct log messages to stdout ###
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target=System.out
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
    
    ### direct messages to file mylog.log ###
    log4j.appender.file=org.apache.log4j.FileAppender
    log4j.appender.file.File=c:/mylog.log
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
    
    ### set log levels - for more verbose logging change 'info' to 'debug' ###
    
    log4j.rootLogger=debug, stdout
    View Code

      UserController

    package com.oy.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    @Controller
    @RequestMapping("/user")
    public class UserController {
    
        @RequestMapping(value="/hello.do",method={RequestMethod.GET,RequestMethod.POST})
        public String hello(){
            return "hello";
        }
    }

      

    9.4、测试

      http://localhost:8080/helloworld/user/hello.do

    10、转发和重定向    <--返回目录

    10.1、重定向Redirect

    Contrller方法返回结果重定向到一个url地址,如果方式:
    return "redirect:/user/userlist.do";
    注意:
    •    redirect:add.do 与 redirect:/user/add.do" 同一个类
          在同一个类里面进行跳转。上面2个都可以实现跳转。但是有区别:
          第一个是同一个根路径下面跳转。第二个是在项目路径下进行跳转。
    •    不同的类进行跳转
    不同的类进行跳转只能使用:redirect:/user/add.do进行跳转。即是从项目路径下来查询。
    redirect方式相当于“response.sendRedirect()”,转发后浏览器的地址栏变为转发后的地址,因为转发即执行了一个新的request和response。
    由于新发起一个request原来的参数在转发时就不能传递到下一个url,如果要传参数可以/user/userlist.do后边加参数,如下:
    /user/userlist.action?groupid=2&...

    10.2、转发Forward

    controller方法执行后继续执行另一个controller方法。
    return "forward:/user/userlist.action";
    forward方式相当于“request.getRequestDispatcher().forward(request,response)”,转发后浏览器地址栏还是原来的地址。转发并没有执行新的request和response,而是和转发前的请求共用一个request和response。所以转发前请求的参数在转发后仍然可以读取到。

    11、RequestBody/ ResponseBody处理Json数据    <--返回目录

      @RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容转换为json、xml等格式的数据并绑定到controller方法的参数上。

      添加处理json数据配置(测试时配置下面的json转换器仍然报415)

    <!-- 注解适配器 :添加json转换器-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
      <property name="messageConverters">
        <list>
          <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
        </list>
      </property>
    </bean>
    23:27:15,966 DEBUG DispatcherServlet:823 - DispatcherServlet with name 'springmvc' processing POST request for [/helloworld/json1.do]
    23:27:15,970 DEBUG RequestMappingHandlerMapping:209 - Looking up handler method for path /json1.do
    23:27:15,973 DEBUG RequestMappingHandlerMapping:216 - Returning handler method [public com.oy.controller.User com.oy.controller.MyJsonController.requestJson(org.springframework.ui.Model,com.oy.controller.User)]
    23:27:15,973 DEBUG DefaultListableBeanFactory:246 - Returning cached instance of singleton bean 'myJsonController'
    23:27:15,997 DEBUG AnnotationMethodHandlerExceptionResolver:132 - Resolving exception from handler [public com.oy.controller.User com.oy.controller.MyJsonController.requestJson(org.springframework.ui.Model,com.oy.controller.User)]: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=utf-8' not supported
    23:27:15,998 DEBUG ResponseStatusExceptionResolver:132 - Resolving exception from handler [public com.oy.controller.User com.oy.controller.MyJsonController.requestJson(org.springframework.ui.Model,com.oy.controller.User)]: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=utf-8' not supported
    23:27:15,999 DEBUG DefaultHandlerExceptionResolver:132 - Resolving exception from handler [public com.oy.controller.User com.oy.controller.MyJsonController.requestJson(org.springframework.ui.Model,com.oy.controller.User)]: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=utf-8' not supported
    23:27:15,999 DEBUG DispatcherServlet:999 - Null ModelAndView returned to DispatcherServlet with name 'springmvc': assuming HandlerAdapter completed request handling
    23:27:15,999 DEBUG DispatcherServlet:946 - Successfully completed request

      使用<mvc:annotation-driven/>就没有问题

    <!-- annotation-driven:默认创建了多个对象:RequestMappingHandlerMapping,RequestMappingHandlerAdapter
        也就提供对json格式支持
     -->
    <mvc:annotation-driven/>

      测试页面(发送ajax请求)

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.8.3.js"></script>
    <script type="text/javascript">
    //请求json,返回json
     function request_json(){
        //JSON.stringify() 方法是将一个JavaScript值(对象或者数组)转换为一个 JSON字符串
        var user = JSON.stringify({name:"张三",age:20});
        $.ajax({         
            type:'POST',
            url: '${pageContext.request.contextPath}/json1.do',
             contentType:'application/json;charset=utf-8',
             data:user,
            success : function(data){             
                alert(data.name+":"+data.age);
            } 
         }) 
     }
    </script>
    </head>
    <body>
    <input type="button" onclick="request_json()" value="请求json,返回json">
    </body>
    </html>

      controller

    @Controller
    public class MyJsonController {
        
        @RequestMapping("/json1.do")
        @ResponseBody
        public User requestJson(Model model, @RequestBody User user){
            System.out.println("用户信息:" + user);
            return user;
        }
        
    }

    12、参数绑定    <--返回目录

    Springmvc参数封装:基于方法进行封装。

    接受参数类型:
        基本类型,int,String等等基本类型。
        Pojo类型
        包装类型

    Springmvc默认支持类型:
        HttpSession,HttpRequstServlet,Model等等。

      controller

    @Controller
    public class MyJsonController {
        
        /**
         * 接收基本数据类型参数
         * http://localhost:8080/helloworld/params1.do?i=11
         *  
         * @param i
         * @param model
         * @return
         */
        @RequestMapping("/params1.do")
        public String hello1(Integer i, Model model){
            System.out.println("i:" + i);
            model.addAttribute("msg", i);
            return "msg";
        }
        
        /**
         * 接收字符串类型参数
         * http://localhost:8080/helloworld/params2.do?str=张三
         *  
         * @param i
         * @param model
         * @return
         */
        @RequestMapping("/params2.do")
        public String hello2(String str, Model model){
            System.out.println("str:" + str);
            model.addAttribute("msg", str);
            return "msg";
        }
        
        /**
         * 接收pojo或包装类型参数
         *  
         * @param i
         * @param model
         * @return
         */
        @RequestMapping("/ext.do")
        public String ext(UserExt ext, Model model){
            model.addAttribute("msg", ext.getExtId() + "--" + ext.getUser().getName()
                    + "---" + ext.getUser().getAge());
            return "msg";
        }
        
    }

      包装类UserExt

    public class UserExt {
        private String extId;
        private User user;
        public String getExtId() {
            return extId;
        }
        public void setExtId(String extId) {
            this.extId = extId;
        }
        public User getUser() {
            return user;
        }
        public void setUser(User user) {
            this.user = user;
        }
    }

      测试页面jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    
    <form action="${pageContext.request.contextPath }/ext.do" method="post">
        extId:<input type="text" name="extId" id="extId">
        name:<input type="text" name="user.name" id="name">
        age:<input type="text" name="user.age" id="age">
    <input type="submit" value="提交">
    </form>
    
    </body>
    </html>

       

      springmvc接收数组类型的参数

    @Controller
    public class IndexController {
        @RequestMapping("/recieveArray.do")
        public String hello1(Integer[] ids, Model model){
            model.addAttribute("msg", Arrays.toString(ids));
            return "msg";
            
        }
    }
    <form action="${pageContext.request.contextPath }/recieveArray.do" method="post">
        id:<input type="checkbox" name="ids" value="1">
        id:<input type="checkbox" name="ids" value="2">
        id:<input type="checkbox" name="ids" value="3">
        <input type="submit" value="提交">
    </form>

      springmvc接收list和map类型的参数:方法里面不能直接传递list和map,需要把list和map封装到包装类。

    public class UserExt {
        private List<User> userList;
        private List<Integer> userIds;
        private Map<String, Object> map = new HashMap<>();
        public List<User> getUserList() {
            return userList;
        }
        public void setUserList(List<User> userList) {
            this.userList = userList;
        }
        public List<Integer> getUserIds() {
            return userIds;
        }
        public void setUserIds(List<Integer> userIds) {
            this.userIds = userIds;
        }
        
        public Map<String, Object> getMap() {
            return map;
        }
        public void setMap(Map<String, Object> map) {
            this.map = map;
        }
        @Override
        public String toString() {
            return "UserExt [userList=" + userList + ", userIds=" + userIds + ", map=" + map + "]";
        }
    }
    @Controller
    public class IndexController {
        @RequestMapping("/recieveList.do")
        public String hello1(UserExt ext, Model model){
            model.addAttribute("msg", ext.toString());
            return "msg";
            
        }
    }
    <form action="${pageContext.request.contextPath }/recieveList.do" method="post">
        name:<input type="text" name="userList[0].name" id="name0">
        age<input type="text" name="userList[0].age" id="age0"><br/>
        
        name:<input type="text" name="userList[1].name" id="name1">
        age:<input type="text" name="userList[1].age" id="age1"><br/>
        
        userIds:<input type="checkbox" name="userIds" value="1">
        userIds:<input type="checkbox" name="userIds" value="2"><br/>
        
        map:<input type="text" name="map['key1']">
        map:<input type="text" name="map['key2']">
        <input type="submit" value="提交">
    </form>

    13、springmvc多视图支持    <--返回目录

      导入 spring.oxm.jar

      web.xml 配置

    <!-- 前端控制器DispatcherServlet -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 默认加载方式
           默认加载必须规范:
           * 文件命名:servlet-name-servlet.xml====springmvc-servlet.xml
           * 路径规范:必须在WEB-INF目录下面  -->
        <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:springmvc.xml</param-value>   
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

      springmvc.xml 配置

    <!-- 多视图的支持 -->
       <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
           <property name="contentNegotiationManager">
               <bean class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"/>
           </property>
           <property name="mediaTypes">
               <map>
                   <entry key="json" value="application/json"/>
                   <entry key="xml" value="application/xml"/>
               </map>
           </property>
           <property name="defaultViews">
               <list>
                   <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
                   <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                       <constructor-arg>
                           <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
                               <property name="classesToBeBound">
                                   <list>
                                       <value>com.oy.controller.User</value>
                                   </list>
                               </property>
                           </bean>
                       </constructor-arg>
                   </bean>
               </list>
           </property>
       </bean>

      实体类上添加@XmlRootElement注解。

      controller

    @Controller
    @RequestMapping(value="/myController")//访问该类的方法时,前面多这样一个路径
    public class MyJsonController {
        
        @RequestMapping("/multiView")
        public User hello1(){
            User u = new User();
            u.setName("zs");
            u.setAge(10);
            return u;
        }
        
    }

      测试

    ---

  • 相关阅读:
    Android软件开发之SharedPreferences
    android软件开发之获取本地音乐属性
    项目开发日记
    MVC中C给V传值
    wtf忘了已经安装了Newtonsoft.json
    我的一些容易忘记的解决问题的方法
    ajax请求返回null
    验证码的一些细节
    项目做不下去
    关于HttpContex
  • 原文地址:https://www.cnblogs.com/xy-ouyang/p/14224456.html
Copyright © 2011-2022 走看看