Request Response\File UploadExceptionInterceptor for SpringMVC

Posted by velanzia on Sat, 13 Jun 2020 04:12:07 +0200

SpringMVC

Summary

Spring MVC is an excellent Web framework based on MVC design concept provided by Spring for presentation layer, and it is one of the most mainstream MVC frameworks at present.Spring MVC makes POJO the controller for processing requests through a set of MVC annotations without implementing any interfaces.

Support restful style URL requests.It uses a loosely coupled pluggable component structure, which is more scalable and flexible than other MVC frameworks.

HelloWorld

1. Import jar packages or dependencies

2. ConfigurationWeb.xml

Configure Dispatcher Servlet to customize the location and name of the configuration file through contextConfigLocation initialization parameters

<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--An initialization parameter for configuring Dispatcher Servlet: Configure the location and name of the SpringMVC configuration file-->
    <!--
        Instead of configuring the Spring MVC configuration file through contextConfigLocation, you can actually use the default.
        The default configuration file is: /WEB-INF/<servlet-name>-Servlet.xml
    -->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

3. Create a Spring MVC profile to configure the package and view resolver for automatic scanning (Internal ResourceViewResolver)

View Name Resolver: Resolve the view logical name to: /WEB-INF/pages/<viewName>.jsp

<context:component-scan base-package="com.xingyu"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
</bean>

4. Create a request processor class

  • Use the @RequestMapping annotation to map the requested URL
  • The return value is resolved to the actual physical view through the view resolver, which is interpreted as follows for the InternalResourceViewResolver view resolver:
    • Get the actual physical view by prefix + returnVal + suffix and do the forwarding
    • The actual physical view is: /WEB-INF/views/success.jsp
@Controller
public class HelloWorld {
    @RequestMapping("/helloworld")
    public String hello(){
        System.out.println("Hello World!");
        return "success";
    }
}

@RequestMapping

The @RequestMapping annotation specifies which URL requests can be processed by the controller, which can be labeled at the controller's class and method definitions.

  • Class Definition: Provides preliminary request mapping information.Relative to the root directory of the WEB application.
  • Method: Provide further detailed mapping information.Relative to the URL at the class definition.If the class definition is not labeled, the URL labeled at the method is relative to the root directory of the WEB application

After the Dispatcher Servlet intercepts the request, it determines how the request is handled by the mapping information provided by @RequestMapping on the controller.

In addition to mapping requests using request URLs, @RequestMapping can also map requests using request methods, request parameters, and request headers.The @RequestMapping value s, methods, params, and heads represent mapping criteria for request URLs, request methods, request parameters, and request headers, respectively. They are related to each other, and using multiple criteria together can make request mapping more precise.

params and headers support simple expressions:

  • param1: Indicates that the request must contain a request parameter named param1
  • !param1: Indicates that a request cannot contain a request parameter named Param1
  • Param1!= value1: Indicates that the request contains a request parameter named param1, but its value cannot be value1
  • {"param1=value1", "param2"}: Request must contain two request parameters named Param1 and param2, and the value of the Param1 parameter must be value1
@RequestMapping(value = "/hello", method = RequestMethod.GET, params = "userId")

@RequestMapping also supports Ant-style URL s:

  • /user/*/createUser: match/user/aaa/createUser, /user/bbb/createUser and other URL s
  • /user/**/createUser: match/user/createUser, /user/aaa/bbb/createUser and other URL s
  • /user/createUser??: Match/user/createUseraa, /user/createUserbb and other URL s

@PathVariable

Placeholder URLs are new to Spring 3.0.The placeholder parameter in the URL can be bound to the incoming parameter of the controller's processing method through @PathVariable: that is, the {xxx} placeholder in the URL can be bound to the input parameter of the operation method through @PathVariable("xxx")

@RequestMapping("/helloworld/{id}")
public String hello(@PathVariable("id") Integer id){
    ...
}

REST

REST: Representational State Transfer.(Resource) Presentation layer state transition is currently a popular Internet software architecture.

GET, POST, PUT, DELETE.They correspond to four basic operations: GET to get resources, POST to create new resources, PUT to update resources, and DELETE to delete resources.

Browser form forms only support GET and POST requests, but methods such as DELETE and PUT do not. Spring 3.0 adds a filter, HiddenHttpMethodFilter, that converts these requests into standard http methods to support GET, POST, PUT, and DELETE requests.

Processing request parameters

By analyzing the signature of the processing method, Spring MVC binds the HTTP request information to the corresponding incoming parameters of the processing method and makes subsequent processing according to the return value type of the method.Methods and methods can be labeled with comments (@PathVariable, @RequestParam, @RequestHeader, and so on).

@RequestParam

Request parameters can be passed to the request method using @RequestParam at the processing method entry.

  • value: parameter name of the request parameter
  • Required: Request parameter is required.The default is true, meaning the request parameter must contain the corresponding parameter, if it does not exist, an exception will be thrown
  • defaultValue: Default value for request parameter
@RequestMapping("handler2")
public String handler2(@RequestParam("name",required = false)) String username, @RequestParam("password") String password){
    ...
}

@RequestBody

Get the body of the request (the get request method is not applicable because the get request parameter is in the url and not the body of the request).

The result is key=value&key=value &...

@RequestMapping("handler2")
public String handler2(@RequestBody String body){
    ...
}

@RequestHeader

The request header contains several attributes from which the server knows the client's letter and uses @RequestHeader to bind the attribute values in the request header to the incoming parameters of the processing method.

@RequestMapping("handler3")
public String handler3(@RequestHeader("Accept-Encoding") String ecoding, @RequestHeader("Keep-Alive") long isAlive){
    ...
}

@CookieValue

@CookieValue allows a processing method to join to bind a Cookie value

@RequestMapping("handler4")
public String handler4(@CookieValue("JSESSEIONID",required=false) String sessionId, @RequestParam("password") String password){
    ...
}

POJO Object Binding

Spring MVC automatically matches the request parameter name to the POJO property name and automatically populates the property value for the object.Supports cascading attributes.For example:dept.deptId,Dept.address.teletc.

@RequestMapping("handler5")
public String handler5(User user){
    ...
}

Using the Servlet API

You can accept parameters of the following Servlet API types: (This increases the coupling between programs and servlet-related classes)

  • HttpServletRequest
  • HttpServletResponse
  • HttpSession
  • java.security.Principal
  • Locale
  • InputStream
  • OutputStream
  • Reader
  • Writer
    @RequestMapping("/testServletAPI")
   public void testServletAPI(HttpServletRequest request,
         HttpServletResponse response, Writer out) throws IOException {
       System.out.println("testServletAPI, " + request + ", " + response);
       out.write("hello springmvc");
   }

Processing model data

Spring MVC provides several ways to output model data:

  • ModelAndView: When a processing method returns a value of type ModelAndView, the body of the method can add model data through that object
  • Map and Model:Enter asOrg.springframework.uiModel,org.springframework.ui. ModelMap orJava.uti.MapWhen the processing method returns, the data in the Map is automatically added to the model
  • @SessionAttributes: Temporarily save an attribute in the model to HttpSession so that it can be shared among multiple requests
  • @ModelAttribute: When a method is included to label the comment, the object is put into the data model

ModelAndView

If the return value of the controller processing method is ModelAndView, it contains both view information and model data information.

Add model data:

  • MoelAndView addObject(String attributeName, Object attributeValue)
  • ModelAndView addAllObject(Map<String, ?> modelMap)

Set View:

  • void setView(View view)
  • void setViewName(String viewName)
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
   String viewName = SUCCESS;
   ModelAndView modelAndView = new ModelAndView(viewName);//viewname is the view name
   modelAndView.addObject("time", new Date());//Add date data
   return modelAndView;
}

Map and Model

Spring MVC uses an internalOrg.springframework.uiThe.Model interface stores model data.Specific steps:

  • Spring MVC creates an implicit model object as a storage container for model data before calling a method.
  • If the method's input is of type Map or Model, Spring MVC passes references to the implicit model to those inputs.Within the method body, the developer can access all the data in the model through this reference object, or add new attribute data to the model.
@RequestMapping("/testMap")
public String testMap(Map<String, Object> map){//When you pass in a map, you can also pass in a model
   System.out.println(map.getClass().getName()); 
   map.put("names", Arrays.asList("Tom", "Jerry", "Mike"));
   return SUCCESS;
}

@SessionAttributes

If you want to share a model attribute data among multiple requests, you can label a @SessionAttributes on the controller class and Spring MVC will temporarily store the corresponding attributes in the model in HttpSession.Note that this annotation can only be placed on classes, not methods.Parameter sharing between methods is implemented.

@SessionAttributes can specify which model attributes need to be placed in the session (type) in addition to the attributes that need to be placed in the session (value) through the attribute name, through the object type of the model attributes:

  • @SessionAttributes(types=User.class) All types in the implicit model will beUser.classThe property of is added to the session.
  • @SessionAttributes(value={"user1", "user2"})
  • @SessionAttributes(types={User.class, Dept.class})
  • @SessionAttributes(value={"user1", "user2"}, types={Dept.class})
@SessionAttributes(value={"user"}, types={String.class})//Both request and session domains
@RequestMapping("/springmvc")
@Controller
public class SpringMVCTest {
	@RequestMapping("/testSessionAttributes")
	public String testSessionAttributes(Model model){//Save to session domain
        User user = new User("Tom", "123456", "tom@atguigu.com", 15);
        model.addAttribute("user", user);
        return SUCCESS;
	}
    
    @RequestMapping("/testGetSessionAttributes")//Obtain
    public String testGetSessionAttributes(ModelMap modelMap){
        User user = (User) modelMap.get("user");
        return "success";
    }
    
    @RequestMapping("/testDelSessionAttributes")//delete
    public String testDelSessionAttributes(SessionStatus status){
        status.setComplete();
        return "success";
    }
}

@ModelAttribute

Can be used on methods or parameters.

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

Use the @ModelAttribute annotation before entering the method:

  • Obtain objects from implicit model data, bind request parameters to objects, and pass in parameters
  • Add Method Input Object to Model
@ModelAttribute
public void getUser(@RequestParam(value="id",required=false) Integer id, 
      Map<String, Object> map){
   System.out.println("modelAttribute method");
   if(id != null){
       //Simulate object removal from database
      User user = new User(1, "Tom", "123456", "tom@atguigu.com", 12);
      System.out.println(user);
      map.put("user", user);
   }
}

@RequestMapping("/testModelAttribute")
public String testModelAttribute(@ModelAttribute("user") User user){
    System.out.println(user);
    return SUCCESS;
}

response

String type

Save it in a Model object or a Map object, then use the EL expression in the JSP user.username,{user.username},user.username,{user.email} Get.

@RequestMapping("/springmvc")
@Controller
public class SpringMVCTest {
	@RequestMapping("/testSessionAttributes")
	public String testSessionAttributes(Model model){//Save to session domain
        User user = new User("Tom", "123456", "tom@atguigu.com", 15);
        model.addAttribute("user", user);
        return "success";
	}
}

void type

(The void type defaults to the JSP file in the directory specified by @RequestMapping(").)

Method 1: Use Servlet request forwarding to jump.

@RequestMapping("/springmvc")
@Controller
public class SpringMVCTest {
	@RequestMapping("/testSessionAttributes")
	public String testSessionAttributes(HttpServletRequest requset, HttpServletResponse response){
        request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request, response);
        //SpringMVC does not automatically match the prefix and suffix when forwarding requests using the HttpServletRequest object and needs to be specified by itself.
	}
}

Method 2: Use Servlet request redirection to jump.

response.sendRendirct(request.getContextPath()+"/WEB-INF/pages/success.jsp").forward(request, response);//Request redirection cannot directly access resources under WEB-INF

Method 3: Respond directly to the browser

response.getWriter().print("hello");

Supplement: Keyword forwarding or redirection:

@RequestMapping("/testForwardOrRedirect")
public String testForwardOrRedirect(){
    // Transfer of Request
    // return "forward:/WEB-INF/pages/success.jsp";

    // Request redirection
    return "redirect:/index.jsp";
}

ModelAndView Type

@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
    // Create ModelAndView object
    ModelAndView mv = new ModelAndView();
    // Simulate querying User objects from a database
    User user = new User();
    user.setUsername("Xiao Feng");
    user.setPassword("456");
    user.setAge(30);
    // Storing the user object in the mv object also puts the user object in the request object
    mv.addObject("user",user);
    // Which page to jump to
    mv.setViewName("success");
    return mv;
}

@ResponseBody responds to JSON

Convert the controller method return object to a json response to the client using the @ResponseBody annotation.(jackson-related jar packages need to be introduced)

@RequestMapping("/testAjax")
public @ResponseBody User testAjax(@RequestBody User user){
    // The client sends an ajax request, passing a json string, and the back end encapsulates the json string into the user object
    System.out.println(user);
    // Response, simulate query database
    user.setUsername("haha");
    user.setAge(40);
    // Respond
    return user;
}

SpringMVC file upload

1. Cross-server file upload:

<dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-client</artifactId>
   <version>1.18.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.18.1</version>
 </dependency>

@RequestMapping("/fileupload3")
public String fileuoload3(MultipartFile upload) throws Exception {
    String path = "http://localhost:9090/uploads/";
    String filename = upload.getOriginalFilename();
    String uuid = UUID.randomUUID().toString().replace("-", "");
    filename = uuid+"_"+filename;
    
    Client client = Client.create();
    WebResource webResource = client.resource(path + filename);
    webResource.put(upload.getBytes());
    return "success";
}

2. SpringMVC local file upload:

 	@RequestMapping("/fileupload2")
    public String fileuoload2(HttpServletRequest request, MultipartFile upload) throws Exception {
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }

        String filename = upload.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid+"_"+filename;
        upload.transferTo(new File(path,filename));

        return "success";
    }

SpringMVC exception handling

Controller calls Service and Service calls Dao. Exceptions are thrown up, and Dispatcher Servlet finds the exception handler to handle them.

Implementation process:

1. Write custom exception classes (including hints) (extends Exception)

public class SysException extends Exception{

    // Storing hints
    private String message;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public SysException(String message) {
        this.message = message;
    }

}

2. Write exception handlers (implements HandlerExceptionResolver)

3. Configure exception handler (jump to error page)

public class SysExceptionResolver implements HandlerExceptionResolver{
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // Get Exception Object
        SysException e = null;
        if(ex instanceof SysException){
            e = (SysException)ex;
        }else{
            e = new SysException("The system is under maintenance....");
        }
        // Create ModelAndView object
        ModelAndView mv = new ModelAndView();
        mv.addObject("errorMsg",e.getMessage());
        mv.setViewName("error");
        return mv;
    }
}

4. Exceptions are thrown at the last possible method throws at the controller, sevice, dao layers

throw new SysException("Error querying all users...");

SpringMVC Interceptor

Filters are part of the sevlet specification and can be used by any java web project; the interceptor is the SpringMVC framework itself, and can only be used by projects that use the SpringMVC framework.

A filter is a url-pattern with /* configured to intercept all static resources to be accessed, including css, js, etc. The interceptor will only intercept the access controller method (controller) and will not intercept the static resources.

Custom interceptors implement the HandlerInterceptor interface.

Implementation process:

1. Write interceptor class to implement HandlerInterceptor interface

public class MyInterceptor2 implements HandlerInterceptor{

    /**
     * Preprocessing, before the controller method executes
     * return true Let go, execute the next interceptor, if not, execute the method in the controller
     * return false No release
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor1 Executed...Top 2222");
        // request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);
        return true;
    }

    /**
     * The postprocessing method, after the controller method is executed,Success.jspBefore execution
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor1 Executed...Last 2222");
        // request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);
    }

    /**
     * success.jsp When the page executes, the method executes
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor1 Executed...Last 2222");
    }

}

2. Configure interceptors and configure them in the Spring MVC configuration file

<!--Configure Interceptors-->
<mvc:interceptors>
    <!--Configure Interceptors-->
    <mvc:interceptor>
        <!--Specific methods to intercept-->
        <mvc:mapping path="/user/*"/>
        <!--Ways not to intercept
        <mvc:exclude-mapping path=""/>
        -->
        <!--Configure Interceptor Objects-->
        <bean class="com.xingyu.interceptor.MyInterceptor1" />
    </mvc:interceptor>

    <!--Configure the second interceptor-->
    <mvc:interceptor>
        <!--Specific methods to intercept-->
        <mvc:mapping path="/**"/>
        <!--Ways not to intercept
        <mvc:exclude-mapping path=""/>
        -->
        <!--Configure Interceptor Objects-->
        <bean class="com.xingyu.interceptor.MyInterceptor2" />
    </mvc:interceptor>
</mvc:interceptors>

Topics: Spring JSP Session Attribute