Some small SpringMVC mapping model view on

A .SpringMVC Overview

  • Excellent Web-based framework MVC design concept for the presentation layer provides SpringMVC, is one of the most mainstream of the current MVC framework.
  • SpringMVC through a set of MVC annotations, POJO let become controller processes the request, without implementing any interface.
  • Support RESTFUL style URL.
  • Pluggable components using a loosely coupled architecture, flexibility and scalability.

II. Use of mapping request @RequestMapping

1. mapping request @RequestMapping

  • SpringMVC use annotations to specify @RequestMapping can come out of those URL request for the controller.
  • And methods defined in the class definition of the controller can be labeled.
    • The class definition: provide initial request mapping information. Relative to the root directory of WEB applications.
      - Methods Department: provides further breakdown mapping information. With respect to the class definition at the URL. If the class definition unlabeled @RequestMapping, the URL method mark relative to the root of the WEB application.
  • After DispatcherServlet intercepted request, the request processing method corresponding to the mapping information determined by the controller @RequestMapping provided.

2. Mapping request parameters, the request header request method, or

  • In addition to mapping @RequestMapping URL request using request, the request method may be used to request parameters and request header mapping request.
  • @RequestMapping of value, method, params and request headers indicate URL, request method, request parameters and request header mapping conditions, is the relationship between them and the joint use can make more accurate mapping of the request.
  • params and headers support simple expression.
    • param1: indicates a request must contain the request parameter named param1.
    • ! Param1: indicates that the request does not contain a request parameter named param1.
    • ! param1 = value1: indicates a request containing request parameter named param1, but its value can not be VALUE1.
      - { "param1 = value", "param2"}: request must include two named param1 and param2 request parameters, and parma1 value of the parameter must be value1.

      3. @RequestMapping map request matcher

    • Ant-style address resource supports three matching symbols.
      • ?: A matching character file name.
      • *: Matches any character in a file name.
      • **: Match multilayer path.
    • @RequestMapping also supports Ant-style URL.
      • /user/*/createUser:匹配/user/aaa/createUser、/user/bbb/createUser等url。
      • /user/**/createUser:匹配/user/createUser、/user/aaa/createUser、/user/aaa/bbb/createUser等URL。
      • /user/createUser??: 匹配/user/createUseraa、/user/createUserbb等URL。

4. @PathVariable URL mapping placeholder binding

  • URL with a placeholder Spring 3.0 is the new feature that is important to Rest target process in SpringMVC.
  • Placeholder parameters in the URL can be bound to the controller by the processing method of ginseng into @PathVeriable: URL in {xxx} placeholder can be bound to the operation by the method of @PathVeriable ( "xxx") into the reference in.

III. Mapping Request Parameter

1. Request signature processing method

  • By analyzing the parameters corresponding springMVC signature processing method, the HTTP request to the information processing method of binding.
  • SpringMVC controller processing method signature restrictions are very loose, almost on the method signature in any way you like.
  • It may be necessary when the reference method and the method of labeling the corresponding primary key (@ PathVariable, @ RequestParam, @ RequestHeader, etc.), information SpringMVC HTTP request frame will bind to the appropriate method of the ginseng, and return type of the method according to subsequent processing accordingly.

    2. @RequestParam binding request parameter values.

  • At the parameters used in the processing method @RequestParam request parameters can be passed to the requesting method.
    • value: parameter name.
    • required: if necessary, the default is true, indicating that the request must include a parameter corresponding to the parameter, if present, will throw an exception.

3. @RequestHeader binding request header attribute value

  • Request header contains several attributes, whereby the server can obtain information of the client, the attribute value can be bound to the request header into a coherent processing method by @RequestHeader.

    4. Use @CookieValue value binding request parameters of Cookie

  • @CookieValue allow treatment to the Senate bind a cookie value.

5. POJO object binding request parameter values

  • SpringMVC will automatically match the request parameters by name and POJO attribute names, automatically fill properties for the object, supports cascading property.

6. Use as the reference Servlet API

  • 使用HttpServletRequest、HttpServletResponse、HttpSession、java.lang.Principal、Locale、InputStream、OutputStream、Reader、Writer

Fourth, the data processing model

1.SpringMVC provide output data model approach

  • ModelAndView: processing method return type is ModelAndView, a method to add the body of the object from the data model.
  • Map and Model: When the parameter is org.springframework.ui.Model, org.springframework.ui.ModelMap or a java.util.Map, processing method returns, the Map data is automatically added to the model.
  • @SessionAttributes: a property in the model to the HttpSession staging, this property may be shared among multiple requests for.
  • @ModelAttribute: After labeling the annotations into the reference method, the reference object will be placed in the data model.

2.ModelAndView

  • The return value if the controller is ModelAndView processing method, which contains both the view information, also contains the model data.
  • Adding model data.
    • ModelAndView addObject(String attributeName,Object attributeValue)
    • ModelAndView addAllObject(Map<String,?> modeMap)
  • Setting the View
    • void setView(View view);
    • void setViewName(String viewName)

3.Map and Model

  • SpringMVC internal interface using a data storage model org.springframework.ui.Model.
  • Specific steps:
    • SpringMVC creates an implicit model object model data as a storage container before calling the method.
    • If the method of the type Model or reference to Map, SpringMVC implicit reference to the model will be passed to these parameters into. Vivo, developers can access all this data model into the parameters by the object, the model may be added to the new attribute data.

4.SessionAttributes

  • If you want to touch a common attribute data model between a plurality of requests. You may be denoted by a controller based on @ SessionAttributes, SpringMVC in the model corresponding to the HttpSession temporary attribute.
  • In addition to the need to specify @SessionAttributes session attributes into the attribute name, the object type can also be specified by the mode attribute of the model that belong to the session needs to be set.
    • @SessionAttributes (types = User.class) would implicitly model for all types of User.class added to the session attributes.
    • @SessionAttributes (value = { "user1" , "user2"},) will be the name of the model is implicitly added to the session attributes and user1 user2.
      - @ SessionAttributes (value { "user1 "}, types = {User.class}) can be specified simultaneously.

5.ModelAttributes

  • Use @ModelAttributes comment on the method definition: SpringMVC before calling the target processing method will first call-by-labeling method @ModelAttributes at the method level.
  • In the method of using the reference @ModelAttributes Note:
    • Can be obtained from a subject implied implicit model data acquisition target, and then bound to the object request parameters, then pass into the reference.
    • The method of adding objects to the model parameters.

6. exception thrown by the @SessionAttributes

  • If the class is defined at standard processing @SessionAttributes ( "xxx"), attempting to obtain the attribute from the session, and assign it to the parameter, and then use the parameters to fill the request message object. If no corresponding attribute in the session, an exception will be thrown HttpSessionRequiredException.
  • If you avoid, you can add a name for the model attribute property name in the class by manually getter method of the property to the name of the implicit model.

V. Views and View resolvers

How to resolve the #### 1.SpringMVC view

2. The view and the view resolver ####

  • After the completion of the request processing method executed, returns a final ModelAndView object. Corresponding to the other return String, View or ModelMap type of processing that, also in the interior SPRINGMVC they are assembled into a ModelAndView object, which contains the logical names and model view of the object.
  • With SpringMVC view resolver to get the final view of the object, the final view may be JSP, it may be manifestations of Excel, JFreechart and other views.
  • For the ultimate view of what the object actually uses the model data for rendering. The processor does not care, focus on a variety of processors focusing on the job raw model data, enabling repeat decoupling MVC.

3. view

  • The role of the view that the rendering model data, the model will appear in the customer data in some form.
  • To achieve specific view of the model and decoupling techniques, Spring defines a highly abstract View interface org.springframework.web.servlet package.
  • View object responsible for view resolver instantiated. Because the view is stateless, so they will not have thread-safety issues.

    4. Common view implementation class

Categories View type Explanation
URL View resolvers InternalResourceView The encapsulation of resources into a JSP or other view, the view is InternalResourceViewResolver default implementation class
URL View resolvers JstlView If the JSP file using the function JSTL internationalization tags, you need to use the view class
Document View AbstractExcelView Abstract class excel document view. This view is based on POI excel document structure
Document View AbstractPdfView An abstract class PDF document view, the view class structure based on IText PDF document.
Report View configurableJsperReportsView View reports using JasperReports technology
Report View JasperReportsCsvView View reports using JasperReports technology
Report View JasperReportsMultiFormatView View reports using JasperReports technology
Report View JasperReportsHtmlView View reports using JasperReports technology
Report View JasperReportsPdfView View reports using JasperReports technology
Report View JasperReportsXlsView View reports using JasperReports technology
JSON view MappingJacksonJsonView The model output in JSON by way of open source framework ObjectMapper Jackson

The view resolver

  • SpringMVC offers a different strategy to resolve the logical view names can be configured in early SpringWEB the context of one or more resolution policy, and specify the order between them. Each mapping strategy corresponding to a specific view resolver class.
  • Action ViewResolver relatively simple: the parsing logic attempts to view a particular object.
  • All ViewResolver view resolver must implement the interface.

6. The common view resolver class

Categories View type Explanation
解析为Bean的名字 BeanNameViewResolver 将逻辑视图名解析为一个Bean,Bean的id等于逻辑视图名。
解析为URL文件 InternalResourceViewResolve 将视图对象解析为一个URL文件,一般使用该解析器将视图名映射成为一个保存在WEB-INF目录下面的程序文件。
解析为URL文件 JasperReportsViewResolver JasperReports是一个基于java的开源报表工具,该解析器将视图名解析为报表文件对应的URL
模板文件视图 FreeMarkerResolver 解析基于FreeMarker模板技术的模板文件
模板文件视图 VelocityViewResolver 解析基于Velocity模板技术的模板文件
模板文件视图 VelocityLayoutViewResolver 解析基于Velocity模板技术的模板文件
  • 可以选择使用一种视图解析器或混用多种视图解析器
  • 每个视图解析器都实现了Ordered接口并开发出一个order属性,可以通过order属性指定解析器的优先顺序,order越小优先级越高。
  • SpringMVC会按照视图解析器顺序的优先顺序对逻辑视图进行解析,知道解析成功并返回视图对象,否则将抛出ServletException异常。

7.InternalResourceViewResolver

  • JSP是最常见的视图技术,可以使用InternalResourceViewResolver作为视图解析器。
  • 若项目中使用了JSTL,则SpringMVC会自动把视图由InternalResourceView转为JstlView。
  • 若使用JSTL的fmt标签需要在SpringMVC的配置文件中配置国际化资源文件。
  • 若希望直接响应通过SpringMVC渲染的页面,可以使用mvc:view-controller标签实现。

8.Excel视图

  • 若希望使用Excel展示数据文件,仅需要扩展SpringMVC提供的AbstractExcelView或AbstractJExcelView即可。实现buildExcelDocument()方法,在方法中使用模型数据对象构建Excel文档就可以了。
  • AbstractExcelView基于POI API,而AbstractJExcelView是基于JExcelAPI的。
  • 视图对象需要配置IOC容器中的一个Bean,使用BeanNameViewResolver作为视图解析器即可。
  • 若希望直接再浏览器中直接下载Excel文档,则可以设置响应头Content-Disposition的值为attachment;filename=xxx.xls。

9.关于重定向

  • 一般情况下,控制器方法返回字符串类型的值会被当成逻辑视图名处理。
  • 如果返回的字符串中带forward:或redirect:前缀时,SpringMVC会对他们进行特殊处理:将forward:和redirect:当成指示符,其后的字符串作为URL来处理。
    • redirect:success.jsp:会完成一个到success.jsp的重定向操作。
    • forward:success.jsp:会完成一个到success.jsp的转发操作。

Guess you like

Origin www.cnblogs.com/jack1995/p/10955710.html