SpringMVC Chapter 3 (Request redirection and forwarding, exception handling, interceptor, SSM integration)

I am a sophomore major in Internet of Things Engineering, and a small wave in the Internet. Blogging is to record my lea...
Request redirection and forwarding
exception handling
Interceptor
Integration of SSM

I am a sophomore major in Internet of Things Engineering, and a small wave in the Internet. Blogging is to record my learning process, and I hope to help many of them in their infancy.Linyuan admires fish, so it's better to go back and make a net.Let's come on together!
Blog Home Page: https://blog.csdn.net/qq_44895397

SpringMVC Complete General Mind Map

Request redirection and forwarding

When the processor has finished processing the request and jumps to other resources, there are two ways to jump: request forwarding and redirection.Depending on the type of resource you want to jump, there are two categories: jumping to a page and jumping to other processors.
For pages that request forwarding, they can be pages in WEB-INF; for redirected pages, they cannot be pages in WEB-INF.Because redirection is equivalent to a second request from the user, who cannot directly access resources in WEB-INF

The SpringMVC framework encapsulates request forwarding and redirection operations in the original Servlet.Forwarding and redirection can now be achieved in a simple way.

  • Forward: Represents forwarding, implementsRequest.getRequestDispatcher("xx.jsp"). forward()
  • Redirect: Represents redirect, implementsResponse.sendRedirect("xxx.jsp")

Request Forwarding

When the processor method returns ModelAndView, add forward:, before the view specified by setViewName(), and the view no longer works with the view parser, so that you can specify a view at a different location when configuring the parser.The view page must write a path relative to the project root.The forward operation does not require a view resolver.The processor method returns a String, prefixing the view path with the forward: view full path.
Syntax: setViewName("forward: the complete path of the apostles");

@RequestMapping("/handlerIntercwptor.do") public ModelAndView forwardDemo(String name ,Integer age){ ModelAndView mv = new ModelAndView(); mv.addObject("myname",name); mv.addObject("myage",age); mv.setViewName("forward:/WEB-INF/view/forward.jsp"); return mv; }

request redirections

A redirect jump can be achieved by adding redirect: before the view string returned by the processor method.
Processor method definition:

@RequestMapping("/handlerIntercwptor.do") public ModelAndView redirectDemo(String name ,Integer age){ ModelAndView mv = new ModelAndView(); mv.addObject("myname",name); mv.addObject("myage",age); mv.setViewName("redirect:/redirect.jsp"); //mv.setViewName("redirect:/WEB-INF/view/forward.jsp"); return mv; }

exception handling

@ExceptionHandler annotation

A method can be specified as an exception handling method using the annotation @ExceptionHandler.The annotation has only one optional attribute value, which is an array of Class<?> used to specify the exception class to be handled by the annotation's method, that is, the exception to be matched.

The annotated methods can return ModelAndView, String, or void with arbitrary method names, and method parameters can be Exception and its subclass objects, HttpServletRequest, HttpServletResponse, and so on.The system automatically assigns values to these method parameters.

For the use of exception handling annotations, exception handling methods can also be directly annotated in Controller

public @interface ExceptionHandler { Class<? extends Throwable>[] value() default {}; }

Steps to use:

  1. Custom exception class
  2. Modifying Controller throws an exception
  3. Customize Exception Response Page
  4. Customize a global processing class
  5. Modify the configuration file (declare the existence of an exception class)

Controller throws an exception:

@RequestMapping("/some.do") public ModelAndView addStudent(String name, Integer age) throws MyException { ModelAndView mv = new ModelAndView(); if (!"zs".equals(name)) { throw new NameException("Wrong name"); } if(age==null||age>100){ throw new AgeException("Age abnormalities"); } mv.addObject("myname", name); mv.addObject("myage", age); mv.setViewName("show"); return mv; }

/** * @ControllerAdvice :Controller enhancements to controller classes * Use on classes * A component scanner is required to let the framework know the package name where this annotation is located * * The method of handling exceptions can have as many parameters as the definition of the controller method and can return ModelAndView * String,void Object Return Value * Parameter: Exception, get information about the exception * @ExceptionHandler : Exception class, indicating the type of exception that occurred */ @ControllerAdvice public class MyHandler { @ExceptionHandler(NameException.class) public ModelAndView ageExcrption(Exception e){ ModelAndView mv = new ModelAndView(); mv.addObject("msg","Ning Input Name Exception"); mv.addObject("message",e.getMessage()); mv.setViewName("ageErorr"); return mv; } }

Interceptor

The Interceptor interceptor in SpringMVC is designed to intercept specified user requests and perform appropriate preprocessing and postprocessing.The point at which it intercepts is "The processor mapper maps the processor class to be executed based on a request submitted by the user, and it also finds the processor adapter to execute the processor class, before the processor adapter executes the processor."Of course, when the processor mapper maps out the processor class to be executed, the interceptor and the processor are combined into a processor execution chain and returned to the central dispatcher.

Execution of an interceptor

  1. preHandle(request,response, Object handler):

This method is executed before the processor method executes.The return value is boolean, if true, then the processor method is executed, and the afterCompletion() method is placed on a dedicated method stack for execution.

/** * preHandle: Pre-treatment method, * Object handler: Intercepted Controller Object * Return value: boolean * true:Indicates access to control methods, * false: Request intercepted * Characteristic: * 1,Method is executed before controller method * 2,This method validates the requested information and whether the request meets the requirements * Validation failure can truncate the request */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle,Verification Passed"); return true; }
  1. postHandle(request,response,Objecthandler,modelAndView):

This method is executed after the processor method executes.Processor methods will not execute if they are not executed eventually.Since this method is executed after the processor method has executed and the method parameter contains ModelAndView, it can modify the processor method's processing result data and modify the jump direction.

/** *Post-processing method: * handler : Intercepted Processor Object * modelAndView: The return value of the processor method, which can be modified * Processor method followed, no return value * Ability to get processor return values, modify views and values * Secondary correction of execution results */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle"); }
  1. afterCompletion(request,response, Object handler, Exception ex):

When the preHandle() method returns true, it is placed on a dedicated method stack until all the work that responds to the request is complete before the method is executed.That is, after the response page is rendered (populated with data) by the central dispatcher, re-manipulating the ModelAndView will not help the response.
The last method executed by afterCompletion to clean up resources, such as adding data to the Controller method

/** * Last Executed Method * *Exception: Program exception * When the request is processed and the view is processed, forward ing the view is considered complete * Do resource recycling in general */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion"); }

The execution order of methods in interceptors and processor methods is as follows:

Execution of multiple interceptors

When there are multiple interceptors, an interceptor chain is formed.The execution order of the interceptor chain is the same as its registration order.It is important to reiterate that when an interceptor's preHandle() method returns true and is executed, the interceptor's afterCompletion() method is placed in a dedicated method stack.

Integration of SSM

Two containers:

  1. SpringMVC Container, Manage Controller Objects
  2. Spring Container, Management service, dao, Tool Class

Steps to achieve:

  1. Building tables

  2. New maven project

  3. Join dependency:
    Spring MVC, servlet, jsp, jackson, Spring, Spring transaction, Spring-MyBatis, Mybatis, mysql driver, druid connection pool

  4. web.xml
    1) Register Dispatcher Servlet for the purpose of creating a springmvc container to create Controller class objects
    2) Register the spring listener: ContextLoaderListener, create the spring container object, create the service, dao, etc.
    3) Register Character Set Filter, post request garbled code

  5. Create package, Controller, service, dao, entity class

  6. Configuration files for springmvc, spring, mybatis

pom.xml:

<dependencies> <!--Add Dependency--> <!--servlet rely on--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- jsp rely on --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2.1-b03</version> <scope>provided</scope> </dependency> <!--springmvc Dependency, automatically imported spring Dependency on--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.5.RELEASE</version> </dependency> <!--spring Manage Transaction Dependencies--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.5.RELEASE</version> </dependency> <!--jkson Dependency on--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> <!--mybatis Dependency, spring-mybatis Dependency, Druid Connection Pool--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.12</version> </dependency> <!--Resource Annotations are not available--> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.3.1</version> </dependency> </dependencies>

spring's main profile:

<bean id="sqlSessionFactory"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:conf/mybatis.xml" /> </bean> <bean> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <property name="basePackage" value="com.yky.dao" /> </bean> <!--Create service Objects are finished with annotations, and annotation scanners are added--> <context:component-scan base-package="com.yky.service" />

Configuration file for springmvc:

  1. Component Scanner
  2. view resolver
  3. Start with the @ResponseBody annotation when the data type changes to json
    Ability to resolve conflicts when accessing static resources
<context:component-scan base-package="com.yky.Controller"/> <bean> <property name="prefix" value="/WEB-INF/view/"/> <property name="suffix" value=".jsp"/> </bean> <mvc:annotation-driven/>

All articles on this site are original. Welcome to reprint them. Please indicate where they came from: Code-knocking kid

15 June 2020, 21:41 | Views: 5977

Add new comment

For adding a comment, please log in
or create account

0 comments