"Spring" Spring MVC advanced Technology

Source: Internet
Author: User

Objective

Learn the simple knowledge ahead Spring Web and then learn the higher-order Web techniques.

Advanced technology substitution Scenarios for spring MVC configuration Custom Dispatcherservlet configuration

In the fifth chapter we have written the following code.

public  class  Spitterwebinitializer extends  Abstractannotationconfigdispatcherservletinitializer { @Override   class<?>[] getrootconfigclasses  () {return  span class= "kw" >new  class<?>[] {rootconfig.}; }  @Override  protected  class<?>[]  () {return  new  class<?>[] {We Bconfig. class }; }  @Override  protected  string[] getservletmappings  () {return  new  string[] { "/" }; }} 

You can see spitterwebinitializer implemented Abstractannotationconfigdispatcherservletinitializer Abstract class, and overrides the three required methods, you can actually override more methods to implement additional configurations, such as overriding the customizeregistration method, which is a Abstractdispatcherservletinitializer the method of , there is no actual method body. When Abstractannotationconfigdispatcherservletinitializer registers Dispatcherservlet with the In the Servlet container, the customizeregistration method is called and the Servlet is registered after the Registration.dynamic incoming. You can set multipartconfigelement by overriding the customizeregistration method, as shown below.

    @Override    protectedvoidcustomizeRegistration(Dynamic registration) {        registration.setMultipartConfig(                newMultipartConfigElement("/tmp/spittr/uploads"));    }
Add additional servlets and filter

AbstractAnnotationConfigDispatcherServletInitializerwill create DispatcherServlet and ContextLoaderListener , when you need to add other Servlet and Filter when, just need to create a new initializer, the simplest way is to implement the WebApplicationInitializer interface.

import Org.springframework.web.WebApplicationInitializer;import javax.servlet.FilterRegistration;import Javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.ServletRegistration.Dynamic; Public classMyservletinitializerImplementsWebapplicationinitializer { Public void Onstartup(ServletContext ServletContext)throwsservletexception {Dynamic servlet = ServletContext.Addservlet("Myservlet", Myservlet.class); Servlet.addmapping("/custom/**"); Filterregistration.DynamicFilter = ServletContext.addfilter("Myfilter", Myfilter.class); Filter.Addmappingforurlpatterns(NULL,false,"/custom/*"); }}
Declaring Dispatcherservlet in an XML file

For basic Spring MVC applications, configuration DispatcherServlet and configuration are required ContextLoaderListener web.xml .

<web-app>  <display-name>Archetype Created Web Application</display-name>  <context-param>    <param-name>Contextconfiglocation</param-name>    <param-value>/web-inf/spring/root-context.xml</param-value>  </context-param>    <listener>    <listener-class>Org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>    <servlet>    <servlet-name>Appservlet</servlet-name>    <servlet-class>Org.springframework.web.servlet.DispatcherServlet</servlet-class>    <load-on-startup>1</load-on-startup>  </servlet>    <servlet-mapping>    <servlet-name>Appservlet</servlet-name>    <url-pattern>/</url-pattern>  </servlet-mapping>  </web-app>

The

can see that dispatcherservlet and Contextloaderlistener are configured in Web. Xml , and the context is defined. The context is loaded by Contextloaderlistener , which reads the bean . You can also specify the application context for Dispatcherservlet and complete the load, and configure Web. XML as follows.

 <SERVLET>     <SERVLET-NAME>  appservlet</SERVLET-NAME>  <SERVLET-CLASS>  Org.springframework.web.servlet.DispatcherServlet    </SERVLET-CLASS>       <INIT-PARAM>  <PARAM-NAME>  contextconfiglocation</PARAM-NAME>  span class= "kw" ><PARAM-VALUE>  web-inf/spring/appservlet/servlet-context.xml</ Param-value>,  </INIT-PARAM>  <load-on-startup>  1</LOAD-ON-STARTUP>  </SERVLET>   

The above uses DispatcherServlet and ContextLoaderListener loads the respective context, but in reality, Java the configuration based is more general and only needs to be configured DispatcherServlet and ContextLoaderListener used AnnotationConfigWebApplicationContext , so that it can load the Java configuration class, not use xml , can set contextClass and DispathcerServletinitialization parameters, as shown below.

<web-app>  <display-name>Archetype Created Web Application</display-name>  <context-param>    <param-name>Contextclass</param-name>    <param-value>Org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>  </context-param>  <context-param>    <param-name>Contextconfiglocation</param-name>    <param-value>Ch7. RootConfig</param-value>  </context-param>    <listener>    <listener-class>Org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>    <servlet>    <servlet-name>Appservlet</servlet-name>    <servlet-class>Org.springframework.web.servlet.DispatcherServlet</servlet-class>    <init-param>      <param-name>Contextclass</param-name>      <param-value>Org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>    </init-param>        <init-param>      <param-name>Contextconfiglocation</param-name>      <param-value>Ch7. Webconfig</param-value>    </init-param>    <load-on-startup>1</load-on-startup>  </servlet>    <servlet-mapping>    <servlet-name>Appservlet</servlet-name>    <url-pattern>/</url-pattern>  </servlet-mapping></web-app>
Processing multipart form data

Processing multipart data is primarily used to process file upload operations. A multipart parser read request needs to be configured multipart .

Configuring the Multipart Parser

DispatcherServletDoes not implement any parsing multipart request data functionality, it simply delegates the task to the MultipartResolver policy interface implementation, through which the multipart request content is parsed, Spring CommonsMultipartResolver and StandardServletMultipartResolver Two parsers are built in.

    • Using Standardservletmultipartresolver

Use the Java following configuration

@OverrideprotectedvoidcustomizeRegistration(Dynamic registration) {    registration.setMultipartConfig(newMultipartConfigElement("/tmp/spittr/uploads"2102410244102410240));}

Use the xml configuration below to configure it in the servlet label multipart-config .

      <multipart-config>        <location>/tmp/spittr/uploads</location>        <max-file-size>2 * 1024 * 1024</max-file-size>        <max-request-size>4 * 1024 * 1024</max-request-size>      </multipart-config>
    • Using Commonsmultipartresolver

Use the Java following configuration

    @Bean    publicmultipartResolverthrows IOException {        newCommonsMultipartResolver();        commonsMultipartResolver.setUploadTempDir(newFileSystemResource("/tmp/spittr/uploads"));        return commonsMultipartResolver;    }
Handling multipart Requests

Annotations can be added to the controller's method parameters @RequestPart , as shown below.

@RequestMapping(value="/register", method=POST)publicprocessRegistration(    @RequestPart("profilePicture"byte[] profilePicture,    @Valid Spittr spitter,    Errors errors) {    profilePicture.transferTo(new File("/data/spittr" + profilePicture.getOriginalFilename()));}
Handling Exceptions

SpringProvides several ways to convert an exception to a response

    • The specific exception is automatically mapped to the specified HTTP status code.
    • Annotations can be added to the exception to @ResponseStatus map it to a HTTP status code.
    • Annotations can be added to the method to @ExceptionHandler handle exceptions.
To map an exception to an HTTP status code

SpringThe corresponding relationship between the exception and the status code is as follows.

Writing Exception Handling methods

You can use the processing exception directly in the request, which is the try/catch Java same as in the normal method, and you try/catch can also write the processor to handle a particular exception, and when a particular exception occurs, there will be a processor delegate method to process it.

@ExceptionHandler(DuplicateSpittleException.class)publichandleDuplicateSpittle() {    return"error/duplicate";}
To add a notification to a controller

A controller notification is any @ControllerAdvice class with annotations that contains one or more of the following types of methods.

    • @ExceptionHandlerThe method for annotating annotations.
    • @InitBinderThe method for annotating annotations.
    • @ModelAttributeThe method for annotating annotations.

The method above will be applied to all the controllers in the entire application with @RequestMapping annotations.

@ControllerAdvicepublicclass AppWideExceptionHandler {    @ExceptionHandler(DuplicateSpittleException.class)    publicduplicateSpittleHandler() {        return"error/duplicate";    }}

After the above configuration, any controller method throws an DuplicateSpittleException exception, it will call this duplicateSpittleHandler method to handle the exception.

Passing data across redirect requests

For redirection, if you need to pass data from a method that initiates redirection to a processing redirection method, there are two ways

    • Use URL templates to pass data in the form of path variables and/or query parameters.
    • flashsend data through attributes.
redirect via URL template

As mentioned earlier, redirect:/spitter/{username} the method is directly based on the username determination url , not very secure, and can be used for the following processing.

model.addAttribute("username", spitter.getUsername());return"redirect:/spitter/{username}";

When you need to pass parameters, such as an ID, you can do the following processing.

model.addAttribute("username", spitter.getUsername());model.addAttribute("spitterId", spitter.getId());return"redirect:/spitter/{username}";

If it username is leesf , id for 123456 . This accesses the url /spitter/leesf?spitterId=123456 . This method can only pass a simple value and cannot send a more complex value, and the property needs to be used at this time flash .

Using the Flash Properties

By RedirectAttributes setting flash properties, you can pass objects directly.

@ReuqestMapping(value="/register", method=POST)publicprocessRegistration(Spitter spitter, RedirectAttributes model) {    spitterRepository.save(spitter);    model.addAttribute("username", spitter.getUsername());    model.addFlashAttribute("spitter", spitter);    return"redirect:/spitter/{username}";}

The spitter object is also passed to the redirect page, allowing direct access to the spitter object.

Summarize

This blog post explains how to configure DispatcherServlet and how to ContextLoaderListener handle exceptions and controller notifications, and finally analyzes how data is passed during redirection.

Spring Spring MVC Advanced Technology

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.