Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of SpringMVC usage cases

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of SpringMVC use case analysis, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this SpringMVC use case analysis article. Let's take a look at it.

I. Overview of SpringMVC

The excellent Web framework based on MVC design concept provided by Spring for the presentation layer is one of the most mainstream MVC frameworks at present.

After Spring3.0, it surpasses Struts2 and becomes the best MVC framework.

Spring MVC uses a set of MVC annotations to make POJO the controller for processing requests without implementing any interfaces.

Support REST-style URL requests

The loosely coupled pluggable component structure is adopted, which is more scalable and flexible than other MVC frameworks.

2. SpringMVC easy to use 1) configure DispatcherServlet in web.xml: dispatcherServlet org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:springmvc.xml 1 dispatcherServlet / 2) join SpringMVC configuration file 3) write a processor to handle the request And use the @ Controller annotation to identify the processor @ Controllerpublic class HelloWorldController {/ * * 1. Use the @ RequestMapping annotation to map the requested URL 2. The returned value will be parsed to the actual physical view through the view parser. For the InternalResourceViewResolver view parser, it will be parsed as follows: get the actual physical view by means of prefix + returnVal + suffix, and then forward it = > / WEB-INF/views/success.jsp * / @ RequestMapping ("/ helloworld") public String hello () {System.out.println ("helloworld") Return "success";}} 4) write view JSP

Create a succes.jsp under the / WEB-INF/views/ directory

Insert title here successfully jumps page 5) get the project up and running access: localhost:8080/hellowoorld 3, use @ RequestMapping mapping request

Spring MVC uses the @ RequestMapping annotation to specify which URL requests can be processed for the controller

It can be marked at the class definition and method definition of the controller.

Class definition: provides preliminary request mapping information. Relative to the root directory of WEB application

Method: provide further subdivision mapping information. Relative to the URL at the class definition. If @ RequestMapping is not marked at the class definition, the URL marked at the method is relative to the root directory of the WEB application

After DispatcherServlet intercepts the request, it determines the corresponding processing method of the request through the mapping information provided by @ RequestMapping on the controller.

1) Standard request header 2) @ RequestMapping

Value, method, params and heads of @ RequestMapping represent the mapping conditions of request URL, request method, request parameters and request header, respectively. The relationship between them is the relationship between and. The combination of multiple conditions can make the request mapping more accurate.

/ * * params and headers can be used to map requests more accurately. Params and headers support simple expressions. * * @ return * / @ RequestMapping (value = "testParamsAndHeaders", params = {"username", "headers" 10 "}, headers = {" Accept-Language=en-US,zh;q=0.8 "}, method = RequestMethod.POST) public String test () {System.out.println (" test... "); return" success " } 3) support Ant style

?: matches a character in the file name

/ user/createUser?

Match URL such as / user/createUsera or user/createUserb

*: matches any character in the file name

/ user/*/createUser

Match URL such as / user/aaa/createUser or / user/bbb/createUser

* *: match multi-layer paths

/ user/\ / createUser**

Match URL such as / user/createUser or / user/aaa/bbb/createUser

Four, @ PathVariable

Mapping placeholders bound by URL

Placeholder URL is a new feature of Spring3.0, which is a milestone in the development of SpringMVC towards the goal of REST.

The placeholder parameter in URL can be bound to the input parameter of the controller processing method through @ PathVariable: the {xxx} placeholder in URL can be bound to the input parameter of the action method through @ PathVariable ("xxx").

/ * * @ PathVariable can be used to map placeholders in URL to parameters of the target method. * / @ RequestMapping ("/ testPathVariable/ {id}") public String test (@ PathVariable ("id") Integer id) {System.out.println ("id:" + id); return "success";} copy Code V, REST style

"

REST: Representational State Transfer. (resource) the state transformation of the presentation layer. It is the most popular Internet software architecture at present. It is clear in structure, up to standard, easy to understand and easy to expand, so it is being adopted by more and more websites.

Example:

/ order/1 HTTP GET: get the order record with id = 1

/ order/1 HTTP DELETE: delete the order record with id = 1

/ order/1 HTTP PUT: update the order record with id = 1

/ order HTTP POST: add an order record

6. @ RequestParam bind request parameter value

Use @ RequestParam at the processing method input to pass request parameters to the request method

Value: parameter name

Required: required; default is true, which means that the request parameter must contain the corresponding parameter. If it does not exist, an exception will be thrown.

/ * * @ RequestParam to map the request parameters. The value value is the parameter name of the request parameter required whether the parameter is required. Default is true * defaultValue request parameter default * / RequestMapping (value = "/ testRequestParam") public String testRequestParam (@ RequestParam (value = "username") String username, @ RequestParam (value = "age", required = false, defaultValue = "0") int age) {System.out.println ("testRequestParam, username:" + username + ", age:" + age); return "success" } 7. @ RequestHeader binding request header attribute value / * Mapping request header information is the same as @ RequestParam * / @ RequestMapping ("/ testRequestHeader") public String testRequestHeader (@ RequestHeader (value = "Accept-Language") String al) {System.out.println ("testRequestHeader, Accept-Language:" + al); return "success";} eight, @ CookieValue binding request Cookie value / * * @ CookieValue: map a Cookie value. Attribute is the same as @ RequestParam * / @ RequestMapping ("/ testCookieValue") public String testCookieValue (@ CookieValue ("JSESSIONID") String sessionId) {System.out.println ("testCookieValue: sessionId:" + sessionId); return "success";} IX. POJO object binding request parameter value / * Spring MVC automatically matches the request parameter name and POJO attribute name, and automatically populates the attribute value for the object. Cascading attributes are supported. * for example: dept.deptId, dept.address.tel, etc. * / @ RequestMapping ("/ testPojo") public String testPojo (User user) {System.out.println ("testPojo:" + user); return "success";} X, parameters of ServletAPI type that can be received by the Handler method in MVC

HttpServletRequest

HttpServletResponse

HttpSession

Writer

Java.security.Principal

Locale

InputStream

OutputStream

Reader

(recommended micro-class: Spring micro-class)

Eleventh, processing model data

1) ModelAndView

When the return type of the processing method is ModelAndView, the method body can add model data through this object, and the ModelAndView contains both view information and model data information.

2) Map and Model

When the input parameter is org.springframework.ui.Model, org.springframework.ui.ModelMap, or java.uti.Map, the data in Map is automatically added to the model when the processing method returns.

3) @ SessionAttributes:

Temporarily save an attribute in the model to the HttpSession so that it can be shared among multiple requests (obtained from the session field)

If you want to share a model property data among multiple requests, you can mark a @ SessionAttributes,Spring MVC on the controller class to temporarily store the corresponding properties in the model in the HttpSession.

In addition to specifying the properties that need to be placed in the session through the property name, @ SessionAttributes can also specify which model properties need to be placed in the session through the object type of the model properties

1) @ SessionAttributes (types=User.class): all attributes of type User.class in the implicit model are added to the session

2) @ SessionAttributes (value= {"user1", "user2"}): an attribute named user1,user2 in the implied model is added to the session

3) @ SessionAttributes (types= {User.class,Dept.class}): all attributes of type User.class,Dept.class in the implicit model are added to the session

4) @ SessionAttributes (value= {"user1", "user2"}, types= {Dept.class}): an attribute named user1,user2 in the implied model and all attributes of type Dept.class are added to the session

4) @ ModelAttribute

After the method input parameter is annotated, the object of the input parameter will be placed in the data model

Twelve, @ ModelAttribute

Use @ ModelAttribute annotation on method definition: Spring MVC calls methods marked @ ModelAttribute at the method level one by one before calling the target processing method.

Use the @ ModelAttribute annotation before the input of the method:

You can get the object from the implicit model data from the implicit object, bind the request parameters to the object, and then pass in the input parameters

Add method input objects to the model

XIII. Views and view parsers

After the request processing method is executed, a ModelAndView object is finally returned. For processing methods that return types such as String,View or ModeMap, Spring MVC also internally assembles them into a ModelAndView object that contains the logical name and the view of the model object.

Spring MVC gets the final view object (View) with the help of the view parser (ViewResolver), and the final view can be JSP, Excel, JFreeChart and other forms of view.

The processor does not care about which view object is adopted to render the model data, and the processor focuses on the work of the production model data, so as to realize the full decoupling of MVC.

1) View

We only need to implement the interface View to customize the view.

Example: @ Componentpublic class HelloView implements View {@ Override public String getContentType () {return "text/html";} @ Override public void render (Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {response.getWriter (). Print ("hello view, time:" + new Date ();}} @ RequestMapping ("/ testView") public String testView () {System.out.println ("testView") Return "helloView"; / / what is returned here is our custom view} 2) View parser

SpringMVC provides different strategies for the resolution of logical view names, and you can configure one or more resolution policies in the context of Spring WEB and specify the order between them. Each mapping strategy corresponds to a specific view parser implementation class.

The role of the view parser is relatively simple, parsing the logical view into a specific view object.

All view parsers must implement the ViewResolver interface.

Programmers can choose a view parser or mix multiple view parsers.

Each view parser implements the Ordered interface and exposes an order property to specify the parser priority through the order attribute. The smaller the order, the higher the priority.

SpringMVC parses the logical view name in the order of the view parser, until the parsing succeeds and the view object is returned, otherwise a ServletException exception is thrown

Configuration in SpringMVC.xml:

This is the end of the article on "SpringMVC usage case Analysis". Thank you for reading! I believe you all have a certain understanding of the knowledge of "SpringMVC use case Analysis". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report