Spring MVC

1. A brief introduction to the SpringMVC process

  (1) The user sends a request to the front-end controller DispatcherServlet

  (2) DispatcherServlet receives the request and calls the HandlerMapping handler mapper

  (3) The processor mapper finds a specific processor according to the request url, generates a processor object and a processor interceptor (if any) and returns it to DispatcherServlet.

  (4) DispatcherServlet calls the handler through the HandlerAdapter handler adapter

  (5) Execute the processor (Controller, also called the back-end controller).

  (6) Controller execution completes and returns to ModelAndView

  (7) HandlerAdapter returns the controller execution result ModelAndView to DispatcherServlet

  (8) DispatcherServlet passes ModelAndView to ViewReslover view resolver

  (9) ViewReslover returns to the specific View after parsing

  (10) DispatcherServlet renders the view to the View (that is, fills the model data into the view).

  (11) DispatcherServlet responds to the user

2. Brief description of components

  (1)   DispatcherServlet: front-end controller

    When the user request arrives at the front controller, it is equivalent to C in the mvc mode. The dispatcherServlet is the center of the entire process control. It calls other components to process the user's request. The existence of the dispatcherServlet reduces the coupling between the components.

  (2)   HandlerMapping: Handler Mapper

    HandlerMapping is responsible for finding Handlers, that is, processors, according to user requests. Springmvc provides different mappers to implement different mapping methods, such as: configuration file methods, implementation interface methods, annotation methods, etc.

  (3)  Handler: processor

    Handler is the back-end controller following the DispatcherServlet front-end controller. Under the control of DispatcherServlet, Handler processes specific user requests.

Since Handler involves specific user business requests, programmers are generally required to develop Handlers according to business requirements.

  (4)  HandlAdapter: processor adapter

    The processor is executed through the HandlerAdapter, which is the application of the adapter mode. More types of processors can be executed by extending the adapter.

  (5)   View Resolver: View resolver

 

    The View Resolver is responsible for generating the View view from the processing result . The View Resolver first resolves the logical view name into the physical view name, that is, the specific page address, then generates the View view object, and finally renders the View and displays the processing result to the user through the page.

  (6)   View: View

 

    The springmvc framework provides support for many types of View views, including: jstlView, freemarkerView, pdfView, etc. Our most commonly used view is jsp. In general, model data needs to be displayed to users through page tags or page template technology, and specific pages need to be developed by programmers according to business needs.

  Among the various components of springmvc, the processor mapper, the processor adapter, and the view resolver are called the three major components of springmvc. The components that need to be opened by the user are handler, view

3. Simple parameter binding

  (1)当请求的参数名称和处理器形参名称一致时会将请求参数与形参进行绑定,参数类型推荐使用包装数据类型,因为基础数据类型不可以为null

      整形:Integer、int
      字符串:String
      单精度:Float、float
      双精度:Double、double
      布尔型:Boolean、boolean
      说明:对于布尔类型的参数,请求的参数值为true或false

  (2)使用@RequestParam常用于处理简单类型的绑定

      value:参数名字,即入参的请求参数名字,如value=“item_id,表示请求的参数区中的名字为item_id的参数的值将传入;
     required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报;
     TTP Status 400 - Required Integer parameter 'XXXX' is not present
     defaultValue:默认值,表示如果请求中没有同名参数时的默认值 

public String editItem(@RequestParam(value="item_id",required=true) String id) {
}

      形参名称为id,但是这里使用value="item_id"限定请求的参数名为item_id,所以页面传递参数的名必须为item_id。
     注意:如果请求参数中没有item_id将跑出异常:
     HTTP Status 500 - Required Integer parameter 'item_id' is not present
     这里通过required=true限定item_id参数为必需传递,如果不传递则报400错误,可以使用defaultvalue设置默认值,即使required=true也可以不传item_id参数值

  (3)使用pojo接收表单数据

     如果提交的参数很多,或者提交的表单中的内容很多的时候可以使用pojo接收数据。要求pojo对象中的属性名和表单中input的name属性一致。请求的参数名称和pojo的属性名称一致,会自动将请求参数赋值给pojo的属性,注意:提交的表单中不要有日期类型的数据,否则会报400错误。如果想提交日期类型的数据需要用到后面的自定义参数绑定的内容。

  (4)自定义参数绑定

    由于日期数据有很多种格式,所以springmvc没办法把字符串转换成日期类型。所以需要自定义参数绑定。前端控制器接收到请求后,找到注解形式的处理器适配器,对RequestMapping标记的方法进行适配,并对方法中的形参进行参数绑定。在springmvc这可以在处理器适配器上自定义Converter进行参数绑定。如果使用<mvc:annotation-driven/>可以在此标签上进行扩展。

publicclass DateConverter implements Converter<String, Date> {

    @Override
    public Date convert(String source) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            returnsimpleDateFormat.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        returnnull;
    }
}

<!-- 加载注解驱动 -->

      <mvc:annotation-drivenconversion-service="conversionService"/>

      <!-- 转换器配置 -->

      <beanid="conversionService"

           class="org.springframework.format.support.FormattingConversionServiceFactoryBean">

           <propertyname="converters">

                 <set>

                      <beanclass="cn.itcast.springmvc.convert.DateConverter"/>

                 </set>

           </property>

      </bean>

4. 高级参数绑定

  4.1 数组

    Controller方法中可以用String[]接收,或者pojo的String[]属性接收。两种方式任选其一即可

  4.2 List对象

    List中存放对象,并将定义的List放在包装类中,使用包装pojo对象接收

5. RequestMapping

  通过RequestMapping注解可以定义不同的处理器映射规则,@RequestMapping(value="/item")或@RequestMapping("/item)

value的值是数组,可以将多个url映射到同一个方法

  5.1 限定方法 

    @RequestMapping(method = RequestMethod.GET)或者@RequestMapping(method = RequestMethod.POST)或@RequestMapping(method={RequestMethod.GET,RequestMethod.POST})

6. Controller 返回值

  6.1 返回ModelAndView

    controller方法中定义ModelAndView对象并返回,对象中可添加model数据、指定view

  6.2 返回字符串

    (1)controller方法返回字符串可以指定逻辑视图名,通过视图解析器解析为物理视图地址

    (2)Contrller方法返回结果重定向到一个url地址,如下商品修改提交后重定向到商品查询方法,参数无法带到商品查询方法中,redirect方式相当于“response.sendRedirect()”,重定向后浏览器的地址栏变为转发后的地址,因为重定向即执行了一个新的request和response。由于新发起一个request原来的参数在重定向时就不能传递到下一个url,如果要传参数可以/item/queryItem.action后边加参数,如下:/item/queryItem?...&…..

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

7. 异常处理器

  springmvc在处理请求过程中出现异常信息交由异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑。

系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。 系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理。

  为了区别不同的异常通常根据异常类型自定义异常类,这里我们创建一个自定义系统异常,如果controller、service、dao抛出此类异常说明是系统预期处理的异常信息

1. 自定义异常类
public
class CustomException extends Exception { /** serialVersionUID*/ private static final long serialVersionUID = -5212079010855161498L; public CustomException(String message){ super(message); this.message = message; } //异常信息 private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
2. 自定义异常处理器

public class CustomExceptionResolver implements HandlerExceptionResolver {

 @Override

    public ModelAndView resolveException(HttpServletRequest request,

           HttpServletResponse response, Object handler, Exception ex) {

        ex.printStackTrace();

       CustomException customException = null;

       //如果抛出的是系统自定义异常则直接转换

       if(ex instanceof CustomException){

           customException = (CustomException)ex;

       }else{

           //如果抛出的不是系统自定义异常则重新构造一个系统错误异常。

           customException = new CustomException("系统错误,请与系统管理 员联系!");

       }

       ModelAndView modelAndView = new ModelAndView();

       modelAndView.addObject("message", customException.getMessage());

       modelAndView.setViewName("error");

       return modelAndView;

    }

}

8. 文件上传

  在tomcat上配置图片虚拟目录,在tomcat下conf/server.xml中添加:<Context docBase="F:\develop\upload\temp" path="/pic" reloadable="false"/>,访问http://localhost:8080/pic即可访问F:\develop\upload\temp下的图片。CommonsMultipartResolver解析器依赖commons-fileupload和commons-io

  8.1 配置解析器

<!-- 文件上传 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置上传文件的最大尺寸为5MB -->
        <property name="maxUploadSize">
            <value>5242880</value>
        </property>
    </bean>

 

Tip: <Context>元素,用于将本地文件系统中的一个目录,映射成一个可供Web浏览器访问的虚拟根目录 
path属性,用于指定Web应用的虚拟路径 
docBase属性,用于指定该虚拟路径,所映射到的本地文件系统目录,可以使用绝对路径,或者相对于<Tomcat安装目录>/webapps的相对路径

 

 

9. Json数据交互

  9.1 @requestBody   

    @RequestBody注解用于读取http请求的内容(字符串)通过springmvc提供的HttpMessageConverter接口将读到的内容转换为json、xml等格式的数据并绑定到controller方法的参数上。List.action?id=1&name=zhangsan&age=12

  9.2 @ResponseBody

    该注解用于将Controller的方法返回的对象,通过HttpMessageConverter接口转换为指定格式的数据如:json,xml等,通过Response响应给客户端

10. RESTful

  @RequestMapping(value="/ viewItems/{id}"):{×××}占位符,请求的URL可以是“/viewItems/1”或“/viewItems/2”,通过在方法中使用@PathVariable获取{×××}中的×××变量。@PathVariable用于将请求URL中的模板变量映射到功能处理方法的参数上

11. 静态资源访问 

  如果在DispatcherServlet中设置url-pattern为 /,则必须对静态资源进行访问处理。spring mvc 的<mvc:resources mapping="" location="">实现对静态资源进行映射访问。如下是对js文件访问配置:<mvc:resources location="/js/" mapping="/js/**"/>

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325300878&siteId=291194637