In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "the workflow and use of Spring MVC". In the daily operation, I believe that many people have doubts about the workflow and use of Spring MVC. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "the workflow and use of Spring MVC". Next, please follow the editor to study!
Process:
(1) first, the user sends the request-- > DispatcherServlet. After receiving the request, the front-end controller does not process it by itself, but entrusts it to other parsers to handle it as a unified access point for global flow control.
(2) DispatcherServlet-- > HandlerMapping, the mapping processor will map the request to a HandlerExecutionChain object (including a Handler processor (page controller) object, multiple HandlerInterceptor interceptors)
(3) DispatcherServlet-- > HandlerAdapter, the processor adapter will package the processor as an adapter, thus supporting multiple types of processors, that is, the application of adapter design patterns, so that many types of processors can be easily supported.
(4) HandlerAdapter-- > calls the corresponding function processing method of the processor and returns a ModelAndView object (including model data, logical view name)
(5) ModelAndView object (the Model part is the model data returned by the business object, and the View part is the logical view name)-- > ViewResolver. The view parser will parse the logical view name into a concrete View.
(6) View-- > render. View will render based on the incoming Model model data. The Model here is actually a Map data structure.
(7) the control is returned to DispatcherServlet, and the response is returned to the user by DispatcherServlet, at the end of this process.
Configure DispatcherServlet
DispatcherServlet is a Servlet, so you can configure multiple DispatcherServlet.
DispatcherServlet is the front controller and is configured in the web.xml file. To intercept matching requests, the Servlet intercept matching rules should be self-defined, and the intercepted requests should be distributed to the target Controller (the Action we wrote) according to the so-and-so rules for processing.
Web.xml:
DispatcherServlet org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:springmvc-servlet.xml DispatcherServlet /
Here are the main points to pay attention to:
(1) classpath:springmvc-servlet.xml is used to load the springmvc configuration file under the classpath, and the file name can be customized. If no label is defined, the path where the configuration file is loaded by default is under WEB-INF.
(2) / indicates that all requests are filtered.
Springmvc-servlet.xml:
Error
Scan for comments on classes in the specified package. Common annotations are:
@ Controller declares the Action component
@ Service declares Service component @ Service ("myMovieLister")
@ Repository declares the Dao component
@ Component generally refers to components, when it is difficult to classify.
@ RequestMapping ("/ menu") request mapping
@ Resource is used for injection, (provided by j2ee) is assembled by name by default, @ Resource (name= "beanName")
@ Autowired is used for injection, which is assembled by type by default (provided by srping)
@ Transactional (rollbackFor= {Exception.class}) transaction management
@ ResponseBody
@ Scope ("prototype") sets the scope of bean
Is a shorthand form, can be manually configured to replace this shorthand form, abbreviated form allows beginners to quickly apply the default configuration scheme. The DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter bean are automatically registered, which is necessary for spring MVC to distribute the request for @ Controllers.
And provide: data binding support, @ NumberFormatannotation support, @ DateTimeFormat support, @ Valid support, read-write XML support (JAXB), read-write JSON support (Jackson).
There are three ways for Spring unified exception handling, which are:
Use @ ExceptionHandler annotations
Implement the HandlerExceptionResolver interface
Use @ controlleradvice annotations
Use @ ExceptionHandler annotations
A downside to using this annotation is that the exception handling method must be in the same Controller as the error method. The use is as follows:
@ Controller public class GlobalController {/ * the * @ return * / @ ExceptionHandler ({MyException.class}) public String exception (MyException e) {System.out.println (e.getMessage ()); e.printStackTrace (); return "exception" for handling exceptions } @ RequestMapping ("test") public void test () {throw new MyException ("error!") ;}}
As you can see, the biggest drawback of this approach is that exceptions cannot be controlled globally. Each class should be written once.
Implement the HandlerExceptionResolver interface
In this way, global exception control can be performed. For example:
@ Component public class ExceptionTest implements HandlerExceptionResolver {/ * TODO briefly describes the implementation function of this method (optional). * @ see org.springframework.web.servlet.HandlerExceptionResolver#resolveException (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception) * / public ModelAndView resolveException (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {System.out.println ("This is exception handler method!"); return null;} use @ ControllerAdvice+ @ ExceptionHandler annotation
As mentioned above, @ ExceptionHandler's method that requires exception handling must be in the same Controller as the method that went wrong. Then contemporary code adds @ ControllerAdvice, so it doesn't have to be in the same controller. This is also a new feature of Spring 3.2. As can be seen from the name, it generally means controller enhancement. In other words, @ controlleradvice + @ ExceptionHandler can also achieve global exception catching.
Make sure that this WebExceptionHandle class can be scanned and loaded into the Spring container.
@ ControllerAdvice@ResponseBodypublic class WebExceptionHandle {private static Logger logger = LoggerFactory.getLogger (WebExceptionHandle.class); / * 400-Bad Request * / @ ResponseStatus (HttpStatus.BAD_REQUEST) @ ExceptionHandler (HttpMessageNotReadableException.class) public ServiceResponse handleHttpMessageNotReadableException (HttpMessageNotReadableException e) {logger.error ("parameter resolution failed", e); return ServiceResponseHandle.failed ("could_not_read_json") } / * 405-MethodNot Allowed * / @ ResponseStatus (HttpStatus.METHOD_NOT_ALLOWED) @ ExceptionHandler (HttpRequestMethodNotSupportedException.class) public ServiceResponse handleHttpRequestMethodNotSupportedException (HttpRequestMethodNotSupportedException e) {logger.error ("current request method is not supported", e); return ServiceResponseHandle.failed ("request_method_not_supported") } / * 415-Unsupported MediaType * / @ ResponseStatus (HttpStatus.UNSUPPORTED_MEDIA_TYPE) @ ExceptionHandler (HttpMediaTypeNotSupportedException.class) public ServiceResponse handleHttpMediaTypeNotSupportedException (Exception e) {logger.error ("current media type is not supported", e); return ServiceResponseHandle.failed ("content_type_not_supported") } / * 500-Internal Server Error * / @ ResponseStatus (HttpStatus.INTERNAL_SERVER_ERROR) @ ExceptionHandler (Exception.class) public ServiceResponse handleException (Exception e) {if (e instanceof BusinessException) {return ServiceResponseHandle.failed ("BUSINESS_ERROR", e.getMessage ());} logger.error ("Service running exception", e); e.printStackTrace () Return ServiceResponseHandle.failed ("server_error");}}
If the exception type to be handled is not declared in the @ ExceptionHandler annotation, it defaults to the exception type in the parameter list. So it can also be written like this:
@ ControllerAdvicepublic class GlobalExceptionHandler {@ ExceptionHandler () @ ResponseBody String handleException (Exception e) {return "Exception Deal!" + e.getMessage ();}}
Inherits the ResponseEntityExceptionHandler class to implement global exception trapping for the Rest interface, and can return a custom format:
@ Slf4j@ControllerAdvicepublic class ExceptionHandlerBean extends ResponseEntityExceptionHandler {/ * data cannot find exceptions * @ param ex * @ param request * @ return * @ throws IOException * / @ ExceptionHandler ({DataNotFoundException.class}) public ResponseEntity handleDataNotFoundException (RuntimeException ex, WebRequest request) throws IOException {return getResponseEntity (ex,request,ReturnStatusCode.DataNotFoundException);} / * build ResponseEntity entities based on various exceptions. Serve the above exceptions * @ param ex * @ param request * @ param specificException * @ return * / private ResponseEntity getResponseEntity (RuntimeException ex, WebRequest request, ReturnStatusCode specificException) {ReturnTemplate returnTemplate = new ReturnTemplate (); returnTemplate.setStatusCode (specificException); returnTemplate.setErrorMsg (ex.getMessage ()); return handleExceptionInternal (ex, returnTemplate, new HttpHeaders (), HttpStatus.OK, request) }} spring mvc common notes
1. @ Controller only defines a controller class, and the method annotated with @ RequestMapping is the real processor that handles the request.
We need to give this controller class to Spring to manage. There are two ways:
(1) define the bean object of MyController in the configuration file of SpringMVC.
(2) tell Spring where to find the Controller controller marked @ Controller in the SpringMVC configuration file.
< context:component-scan base-package = "com.host.app.web" />/ / the path is written to the upper layer of the controller (for more information on the scan package, see the following analysis)
2. @ RequestMapping
RequestMapping is an annotation that handles request address mapping and can be used on classes or methods. Used on a class, the method that represents all response requests in the class has this address as the parent path.
RequestMapping annotations have six attributes, so let's divide them into three categories (there are examples below).
2.1 、 value, method
Value: specify the actual address of the request, which can be in URI Template mode (described later)
Method: specify the method type of the request, such as GET, POST, PUT, DELETE, etc.
2.2 、 consumes,produces
Consumes: specifies the submitted content type (Content-Type) to process the request, such as application/json, text/html
Produces: specifies the content type to be returned, only if the (Accept) type in the request request header contains the specified type
2.3 、 params,headers
Params: specifies that some parameter values must be included in the request to be handled by this method.
Headers: specifies that some specified header value must be included in the request for this method to process the request.
3, @ Resource and @ Autowired
@ Resource and @ Autowired are both used for bean injection. In fact, @ Resource is not a Spring annotation. Its package is javax.annotation.Resource and needs to be imported, but Spring supports the injection of this annotation.
3.1. Common ground
Both can be written on fields and setter methods. If both are written on the field, there is no need to write the setter method.
3.2. Differences
(1) @ Autowired
The annotations provided by @ Autowired for Spring require the import package org.springframework.beans.factory.annotation.Autowired; to be injected only according to byType.
Public class TestServiceImpl {/ / the following two @ Autowired can be used in only one way @ Autowired private UserDao userDao; / / for @ Autowired public void setUserDao (UserDao userDao) {/ / methods for attributes this.userDao = userDao;}}
The @ Autowired annotation assembles dependent objects by type (byType). By default, it requires that dependent objects must exist. If null values are allowed, you can set its required property to false. If we want to assemble by name (byName), we can use it with the @ Qualifier annotation. As follows:
Public class TestServiceImpl {@ Autowired @ Qualifier ("userDao") private UserDao userDao;}
(2) @ Resource
@ Resource is automatically injected according to ByName by default, which is provided by J2EE. You need to import the package javax.annotation.Resource. @ Resource has two important attributes: name and type, while Spring resolves the name attribute of the @ Resource annotation to the name of bean, while the type attribute resolves to the type of bean. Therefore, if the name attribute is used, the automatic injection policy of byName is used, and the byType automatic injection policy is used when the type attribute is used. If neither the name nor the type attribute is specified, the byName automatic injection strategy will be used through the reflection mechanism.
Public class TestServiceImpl {/ / the following two @ Resource can be used for @ Resource (name= "userDao") private UserDao userDao; / / for @ Resource (name= "userDao") public void setUserDao (UserDao userDao) {/ / this.userDao = userDao;} on the setter method for attributes.
Note: it is best to put @ Resource on the setter method, because this is more in line with the object-oriented idea of manipulating properties through set and get rather than directly.
@ Resource assembly sequence:
① if both name and type are specified, a unique matching bean is found in the Spring context to assemble, and an exception is thrown if it is not found.
② if name is specified, a bean with a matching name (id) is found in the context for assembly, and an exception is thrown if it is not found.
③ if type is specified, a unique bean with a similar match is found in the context to assemble. If no or more than one is found, an exception will be thrown.
④ automatically assembles in byName mode if neither name nor type is specified; if there is no match, it falls back to an original type for matching, and if there is a match, it automatically assembles.
@ Resource is equivalent to @ Autowired, except that @ Autowired is automatically injected according to byType.
4, @ ModelAttribute and @ SessionAttributes
It represents that all methods of the Controller execute the @ ModelAttribute method before it is called, which can be used in annotations and method parameters. You can apply this @ ModelAttribute feature to BaseController. All Controller inherits BaseController, so that the @ ModelAttribute method can be executed when Controller is called. The main function is to add data to the model object for use when displaying the view page.
@ SessionAttributes puts the value in the session scope and writes it on the class.
5. @ PathVariable
It is used to map the template variables in the request URL to the parameters of the function processing method, that is, to take the variables in the uri template as parameters. Such as:
6. @ requestParam
@ requestParam is mainly used to obtain parameters in the SpringMVC background control layer. Similar to request.getParameter ("name"), it has three commonly used parameters: defaultValue = "0", required = false, and value = "isApp". DefaultValue means to set the default value, whether the required over boolean setting is a parameter that must be passed, and the value value indicates the accepted passed parameter name.
7, @ ResponseBody
Purpose: this annotation is used to write the object returned by the Controller method to the body data area of the Response object after it is converted to the specified format through the appropriate HttpMessageConverter.
Timing of use: the returned data is not a page with html tags, but is used when data in some other format (such as json, xml, etc.)
8. @ Component
Equivalent to a general annotation, used when you don't know which layer some classes belong to, but it's not recommended.
9, @ Repository
Used to annotate the dao layer, annotating the daoImpl class.
Note: 1. Use @ RequestMapping to map the Request request to the processor
Way 1. Access the controller method through the combination of common classpath and method path
Method 2. Use the uri template
@ Controller@RequestMapping ("/ test/ {variable1}") public class MyController {@ RequestMapping ("/ showView/ {variable2}") public ModelAndView showView (@ PathVariable String variable1, @ PathVariable ("variable2") int variable2) {ModelAndView modelAndView = new ModelAndView (); modelAndView.setViewName ("viewName") ModelAndView.addObject ("property name to be put in model", "corresponding property value, it is an object"); return modelAndView;}}
In addition to using the URI template to define variables in the request path, the wildcard "*" is also supported in @ RequestMapping. As in the code below, I can use / myTest/whatever/wildcard.do to access the testWildcard method of Controller. Such as:
@ Controller@RequestMapping ("/ myTest") public class MyController {@ RequestMapping ("* / wildcard") public String testWildcard () {System. Out .println ("wildcard-"); return "wildcard";}}
When no parameter name is specified in @ RequestParam, Spring defaults to the parameter with the same name as the method parameter if the code is compiled by debug, and an error will be reported if it is not compiled by debug.
2. Some advanced uses of @ RequestMapping
(1) params attribute
RequestMapping (value= "testParams", params= {"param1=value1", "param2", "! param3"}) public String testParams () {System. Out .println ("test Params."); return "testParams";}
Three parameters are specified with the params attribute of @ RequestMapping. These parameters are for the request parameters. They mean that the value of the parameter param1 must be equal to value1, the parameter param2 must exist, the value does not matter, and the parameter param3 must not exist. The method can be accessed only when the request / testParams.do and the specified three parameter conditions are met. Therefore, the testParams method can be accessed correctly when / testParams.do?param1=value1¶m2=value2 is requested, but it cannot be accessed normally when / testParams.do?param1=value1¶m2=value2¶m3=value3 is requested, because the parameter param3 cannot exist if you specify the parameter param3 in the params parameter of @ RequestMapping.
(2) method attribute
@ RequestMapping (value= "testMethod", method= {RequestMethod. GET, RequestMethod. DELETE}) public String testMethod () {return "method";}
The use of the method parameter in the above code restricts access to the testMethod method of the Controller when / testMethod is requested with the GET or DELETE method.
(3) headers attribute
RequestMapping (value= "testHeaders", headers= {"host=localhost", "Accept"}) public String testHeaders () {return "headers";}
The usage and function of the headers property is similar to that of the params property. In the above code, when requesting / testHeaders.do, the testHeaders method can be accessed correctly only if the request header contains Accept information and the requested host is localhost.
3. The method parameters and return types supported by the processor methods of the @ RequestMapping tag. Supported method parameter types
(1) HttpServlet objects, including HttpServletRequest, HttpServletResponse and HttpSession objects. These parameters Spring will automatically assign values to them when you call the processor method, so when you need to use these objects in the processor method, you can directly give a method parameter declaration on the method and then use it directly in the method body. However, it is important to note that when using the HttpSession object, there will be a problem if the HttpSession object has not been established at this time.
(2) Spring its own WebRequest object. Use this object to access the property values stored in HttpServletRequest and HttpSession.
(3) InputStream, OutputStream, Reader and Writer. InputStream and Reader are for HttpServletRequest, and you can take data from them; OutputStream and Writer are for HttpServletResponse, and you can write data into them.
(4) use the parameters of the @ PathVariable, @ RequestParam, @ CookieValue, and @ RequestHeader tags.
(5) use the parameters marked with @ ModelAttribute.
(6) Model and ModelMap encapsulated by java.util.Map and Spring. All of these can be used to encapsulate the model data and to present to the view.
(7) entity class. Can be used to receive uploaded parameters.
(8) MultipartFile encapsulated by Spring. Used to receive uploaded files.
(9) Errors and BindingResult objects encapsulated by Spring. These two object parameters must be immediately after the entity object parameter that needs to be validated, which contains the validation result of the entity object.
3.2. Supported return types
(1) A ModelAndView object that contains models and views.
(2) A model object, which mainly includes Model and ModelMap encapsulated by Spring, and java.util.Map. When no view is returned, the view name will be determined by RequestToViewNameTranslator.
(3) A View object. At this point, if the model is in the process of rendering the view, you can define a model parameter for the processor method, and then add a value to the model in the method body.
(4) A String string. This often represents a view name. At this point, if you need a model in the process of rendering the view, you can give the processor a model parameter, and then add a value to the model in the method body.
(5) the return value is void. In this case, we usually write the returned result directly to HttpServletResponse. If not, Spring will use RequestToViewNameTranslator to return a corresponding view name. If a model is needed in the view, it is handled in the same way as if a string is returned.
(6) if the processor method is annotated with the @ ResponseBody flag, then any return type of the processor method will be written to HttpServletResponse after HttpMessageConverters conversion, instead of being treated as a view or model as in the above case.
(7) any return type except for the above cases will be treated as an attribute in the model, and the returned view is still determined by RequestToViewNameTranslator. The attribute name added to the model can be defined with @ ModelAttribute ("attributeName") on this method, otherwise it will be represented in lowercase with the first letter of the class name of the return type. The method using the @ ModelAttribute tag is executed before the method of the @ RequestMapping tag is executed.
5. The difference between @ PathVariable and @ RequestParam
There is a variable value of id on the request path. You can get @ RequestMapping through @ PathVariable (value = "/ page/ {id}", method = RequestMethod.GET).
@ RequestParam is used in action to get static URL request input parameter spring comments.
Brief introduction:
Handler method parameter binding notes are commonly used. According to the different content parts of the Request they deal with, we can be divided into four categories: (mainly explain common types)
A. comments dealing with the requet uri part (in this case, the variable in uri template, excluding the queryString part): @ PathVariable
B. Notes for dealing with request header: @ RequestHeader, @ CookieValue
C. Comments on dealing with request body: @ RequestParam, @ RequestBody
D. Attribute type is annotated: @ SessionAttributes, @ ModelAttribute
(1), @ PathVariable
When you use the @ RequestMapping URI template style mapping, that is, someUrl/ {paramId}, the paramId can bind its passed value to the parameters of the method through the @ Pathvariable annotation.
Sample code:
@ Controller @ RequestMapping ("/ owners/ {ownerId}") public class RelativePathUriTemplateController {@ RequestMapping ("/ pets/ {petId}") public void findPet (@ PathVariable String ownerId, @ PathVariable String petId, Model model) {/ / implementation omitted}} this is the end of the study on "the workflow and use of Spring MVC". I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.