7th. Advanced Techniques of Spring MVC

Source: Internet
Author: User

1. Configure other Servlets and filter

According to the definition of abstractannotationconfigdispatcherservletinitializer, it will create
Built Dispatcherservlet and Contextloaderlistener. But what if you want to register for another Servlet, Filter, or Listener?
One benefit of the Java-based initializer (initializer) is that we can define any number of initializer classes. So, if we want to register other components in the Web container,
, you can simply create a new initializer. The simplest way is to implement the Spring Webapplicationinitializer interface.

However, if you simply register the filter and the filter is only mapped to Dispatcherservlet, then
There is also a quick way in Abstractannotationconfigdispatcherservletinitializer.
In order to register the Filter and map it to Dispatcherservlet, all you need to do is re-
The Getservlet-filters () method that contains Abstractannotationconfigdispatcherservletinitializer. For example, in the following code, a heavy
The Abstractannotationconfig-dispatcherservletinitializer getservletfilters () method is loaded to register the Filter:

2, processing multipart form of data

Simply put, the file box upload process for form forms, spring MVC needs to configure the processor

Starting with Spring 3.1, Spring has built in two multipartresolver implementations for us to choose from:

    • Commonsmultipartresolver: Use Jakarta Commons FileUpload to parse the multipart request;
    • Standardservletmultipartresolver: Dependent on Servlet 3.0 support for multipart requests (starting with Spring 3.1)

Here we only say Servlet3.0 form of configuration, also recommended this way, at least do not need other third-party jar package:

The first step

Standardservletmultipartresolver compatible with Servlet 3.0 has no constructor parameters and no properties to set. In this way, in the context of the Spring application, it
Declaring a bean is very simple, as follows:

Step Two

If we configure Dispatcherservlet, the Servlet initialization class inherits the Abstract
Annotationconfigdispatcherservletinitializer or Abstractdispatcher-servletinitializer words, then we won't be straight
Create an Dispatcherservlet instance and register it in the Servlet context. In this case, there will be no references to the Dynamic Servlet registration for our use
The However, we can configure the specifics of multipart by overloading the Customizeregistration () method (which will get a Dynamic as a parameter):

The constructor supports setting parameters:

    • The maximum size, in bytes, of the uploaded file. The default is no limit.
    • The maximum capacity, in bytes, for the entire multipart request, and does not care about how many part and the size of each part. The default is no limit.
    • During the upload process, if the file size reaches a specified maximum capacity (in bytes), it will be written to the temporary file path. The default value is 0, which means that all uploads
    • Files will be written to disk

Step Three

Configuration we need to take the file in the controller, we can use Multipartfile, of course, we can also use part,

To accept file uploads in the form of part parameters, there is no need to configure Multipartresolver. Only make
When we use multipartfile, we need multipartresolver. However, it is important to note that the temporary path must be configured, and of course you can write the saved logic yourself without having to provide the interface after accepting it.

@RequestMapping (value ="/upload", method =requestmethod.post) PublicModelandview Upload (@RequestParam ("file") multipartfile file, HttpServletRequest request) {String msg=""; Try{File root=NewFile ("d:/uploads/"); if(!root.exists ())            {Root.mkdir (); } File F=NewFile ("/uploads/"+file.getoriginalfilename ()); FileOutputStream Fos=NewFileOutputStream (f);            Fos.write (File.getbytes ());            Fos.flush ();            Fos.close (); Msg="Upload success!"; } Catch(IOException e) {e.printstacktrace (); Msg="upload failed!"; } modelandview Mav=NewModelandview ("result"); Mav.addobject ("msg", MSG); returnMav; } @RequestMapping (Value="/upload2", method =requestmethod.post) PublicModelandview Upload2 (@RequestParam ("file") part file) {String msg=""; Try{System. out. println (File.getsubmittedfilename ()); File F=NewFile ("/uploads/"+file.getsubmittedfilename ()); InputStream is=File.getinputstream (); FileOutputStream Fos=NewFileOutputStream (f); intindex; byte[] bytes =New byte[1024x768];  while(index = is. Read (bytes))! =-1) {fos.write (bytes,0, index);            Fos.flush ();            } fos.close ();  is. Close (); Msg="Upload success!"; } Catch(IOException e) {e.printstacktrace (); Msg="upload failed!"; } modelandview Mav=NewModelandview ("result"); Mav.addobject ("msg", MSG); returnMav; }
3. Handling Exceptions

Spring provides several ways to convert an exception to a response:

    • The specific Spring exception will be automatically mapped to the specified HTTP status code;
    • You can add @ResponseStatus annotations to an exception to map it to an HTTP status code;
    • You can add @ExceptionHandler annotations to the method to handle exceptions.
Specific exceptions are converted to HTTP status codes

You can add @ResponseStatus annotations to an exception to map it to an HTTP status code
" Not found! " )publicclass  codefoundexception extends RuntimeException {    public codefoundexception () {}      Public codefoundexception (String msg) {        super (msg);}    }

You can add @ExceptionHandler annotations to the method to handle exceptions
@RequestMapping (value ="/error", method =requestmethod.get) PublicModelandview Error (@RequestParam ("Code") (String code) {if("1". Equals (code))//throw new Codefoundexception ("Just test it!");            Throw NewDuplicatecodefoundexception ("just test it!"); Modelandview Mav=NewModelandview ("Error"); returnMav; } @ExceptionHandler (duplicatecodefoundexception.class)     PublicModelandview Handleduplicatecodefound () {Modelandview Mav=NewModelandview ("Codefound"); returnMav; }

This can be a lot easier if the specific facets of the controller class can be applied to all the controllers in the entire application. For example, if you want to handle exceptions in multiple controllers,
That @ExceptionHandler annotations are useful in the way they are labeled. However, if a particular exception is thrown in multiple controller classes, you may find that you want to
Repeat the same @ExceptionHandler method in the Controller method. Or, to avoid duplication, we'll create a base controller class, and all the controller classes will extend this
Class to inherit the common @ExceptionHandler method.
Spring 3.2 introduces a new solution for this type of problem: Controller notifications. Controller advice is any class with @ControllerAdvice annotations.
This class will contain one or more of the following types of methods:

    • @ExceptionHandler the method of annotating annotations;
    • @InitBinder the method of annotating annotations;
    • @ModelAttribute the method for annotating annotations.

In classes with @ControllerAdvice annotations, the methods described above apply to all controllers in the entire application with @RequestMapping annotations
On
@ControllerAdvice annotations themselves already use @Component, so the classes labeled @ControllerAdvice annotations are automatically retrieved by component scans, like
The same class with @Component annotations.

One of the most practical scenarios for @ControllerAdvice is to collect all the @ExceptionHandler methods into a class so that all controller exceptions can be
The parties to the process uniformly. For example, we want to use the duplicatespittleexception approach to all the controllers of the entire application. The following list of programs shows
Appwideexceptionhandler can accomplish this task, which is a class with @ControllerAdvice annotations.

4. Redirect and forward

In the view name returned by the Controller method, we use the power of the "redirect:" prefix. When the Controller method returns a String value that starts with "redirect:"
, then this String is not used to find the view, but rather to guide the browser to redirect the path

return New Modelandview ("redirect:/")

We know that redirects are missing parameters, but spring has a way to save data using the Flash properties.

forwarding, URL invariant, parameter not missing, prefix forward:

return New Modelandview ("Forward:/denglupost")

7th. Advanced Techniques of Spring MVC

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.