Spring MVC learning notes

SpringMVC

Chapter I overview of SprngMVC

1.1 basic description of spring MVC

springmvc is based on spring and is a module in spring. It is used for web development. springmvc is called spring web mvc, which shows that it is the core technology of spring. For web development, springmvc is the internal mvc architecture mode

Spring MVC is a container that manages objects. Using IOC core technology, spring MVC manages controller objects in the interface layer

The bottom layer of spring MVC is also Servlet, which takes Servlet as the core, receives requests, processes requests, and displays the processing results to users

Process user requests:

User initiated request - > spring MVC – > spring – > mybatis – > MySQL database

1.2 core Servlet in spring MVC – DisPatcherServlet

Dispatcher Servlet is a Servlet object of the framework, which is responsible for receiving requests and responding to processing results

Dispatcher servlet, whose parent is HttpServlet,

Dispatcher servlet is also called front controller

Spring MVC is a management controller object. Before spring MVC, Servlet was used as the controller object. Now an object called controller is created through spring MVC container to replace Servlet to perform the role and function of controller

Spring MVC mainly uses annotations to create controller objects and process requests,

Requirements:

The user initiates a request, spring MVC receives the request and displays the processing result of the request

Implementation of servlet:

jsp initiate request – > servlet – > jsp display result

springmvc implementation steps:
  1. New web application

  2. Join web dependency

    Spring webmvc dependency (spring MVC framework dependency), servlet dependency

    <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <maven.compiler.source>1.8</maven.compiler.source>
      <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    
    <dependencies>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.5.RELEASE</version>
      </dependency>
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
      </dependency>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
      </dependency>
    </dependencies>
    
    <build>
      <plugins>
        <!-- Coding and compiling JDK edition -->
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.1</version>
          <configuration>
            <source>1.8</source>
            <target>1.8</target>
          </configuration>
        </plugin>
      </plugins>
    </build>
    
  3. Declare the spring MVC core object DispatcherServlet

    (1) DispatcherServlet is a servlet object

    (2) The dispatcherservlet is called the front controller

    (3) Dispatcherservlet functions:

    [1] in init() method of servlet, create container object in spring MVC

    [2] receive the request as a servlet

  4. Create a jsp to initiate the request

  5. Create a common type for use as a controller (instead of the previous servlet)

    (1) Add the @ Controller annotation on the class

    (2) Define the method in the class, and add the @ RequestMapping annotation above the method

    Method to process the request, which is equivalent to the doget and dopost of the servlet

  6. Create a jsp page as a result

  7. Create spring MVC configuration file (same as spring configuration file)

    (1) Declare the component scanner and specify the package name where the @ Controller annotation is located

    (2) Declare view parser object

Initialize web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
<!--    statement springMVC Core object of

           visit mymvc After address, Error file not found./WEB-INF/springmvc-servlet.xml
           By default: Registered with central server servlet What's the name, Its file name is /WEB-INF/xxx-servlet.xml
                    For example, the registered name is myweb,The file name is /WEB-INF/myweb-servlet.xml

            Error reason: stay servlet of init()Method, establish springmvc Container object used WebApplicationContext
            WebApplicationContext wac = new ClassPathXMLApplicationContext(Profile name);
            The default path for the configuration file is : /WEB-INF/<servlet-name>-servlet.xml

		DispatcherServlet Role of:
            1. stay init()Create in SpringMVC Container object for,WebApplicationContext. establish
            springmvc Objects that exist in the configuration file,namely Controller object.
            2. DispactcherServlet It's a Servlet , Able to accept requests.
-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/mymvc</url-pattern>
    </servlet-mapping>
</web-app>

You can also customize the configuration file location of spring MVC and the time when the object is created

 <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--        Custom profile location-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
<!--        This label represents the server tomcat The order in which objects are created,Is an integer value, Greater than or equal to 0
        The smaller the number,The earlier the object is created.
-->
        <load-on-startup>1</load-on-startup>
    </servlet>

Set request path

 <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
<!--     url-pattern effect: Send some requests to the designated servlet handle
            Using the central scheduler(DispatcherServlet)
            1. Use extension mode, format: *.xxx, xxx Is a custom extension
                for example : *.do , *.action, *.mvc wait,But it cannot be used *.jsp
                Because it will cause ambiguity, The server does not know whether to access the page or process the request.
             2. use "/" 
   -->
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

The front page initiates a request

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="some.do">launch some.do request</a>
</body>
</html>

Server return page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>msg data: ${msg}</h3>
    <h3>fun data: ${fun}</h3>
</body>
</html>

Server processing request

package com.nguyenxb.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Controller : Create controller (processor) object
 *  Controller: it is called back controller, a custom class that handles requests
 *  Location: it is written on the top of the class, indicating the creation of such an object, which is placed in the spring container
 */
@Controller
public class MyController {
    // Define methods to process requests. Previously, the get() and post() methods were used


    /**
     *  springmvc Framework, using the methods in the controller class to process requests
     *  Characteristics of the method:
     *   1.Method, representing the parameters in the request
     *   2.Method, representing the processing request of this request
     */

    /**
     * @RequestMapping : Request mapping
     *      Attribute: Value: uri address in the request, unique value, starting with "/"
     *      Location: 1. Must be above the method, 2. Above the class definition (optional)
     *      Function: submit the specified request to the specified method for processing, which is equivalent to URL pattern
     *
     * Return value ModelAndView: indicates the processing result (data and view) of this request
     *      Model : Represent data
     *      View : Representation view
     *
     * */
    @RequestMapping(value = "/some.do")
    public ModelAndView doSome(){ // doGet()
        // The doSome method of myController is executed
        // Use this method to process requests. The method that can process requests is called the controller method
        // Call the service object to process the request and return data
        ModelAndView modelAndView = new ModelAndView();
        // Add data
        modelAndView.addObject("msg","Handled Some.do request");
        modelAndView.addObject("fun","Yes doSome method");

        // Specifies the view to display the data
        modelAndView.setViewName("/show.jsp");
        // Return results
        return modelAndView;
    }
    /**
     * Operation process of the framework:
     *  When the framework calls the doSome() method, it gets the return value ModelAdnView
     *  The framework will deal with logical values and data and views of mv object class names
     *  Execute request.setAttribute("msg", "processed Some.do request") on the data and put the data into the request scope
     *  forward the view, which is equivalent to the domain request.getRequestDispatcher("/show.jsp").forward(req,resp);
     *
     * */
}

1.3 spring MVC request processing

Simple process:

The user initiates a request some.do - > Tomcat receives the request - > dispatcher servlet - > assign the request to mycontroller (the dosome () method returns the modelAndView object) - > modelAndView is displayed to the user

Omit tomcat

User some.do - > dispatcherservlet - > mycontroller

If you use a servlet to process requests

User initiated request - > no other objects - > Servlet

Spring MVC has a central scheduler than the previous servlet s, which can add more functions in the middle

1.4 view parser

In a web program, the WEB-INF folder is a protected file that cannot be accessed by external requests, but only within the program

springmvc.xml configuration view parser

<!--    view resolver ,Help process views-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--        prefix,Specifies the path to the view file-->
        <property name="prefix" value="/WEB-INF/view/"/>
<!--        suffix, The extension of the view file-->
        <property name="suffix" value=".jsp"/>
    </bean>

Write the following code in the method of processing the request. You can use the view parser to simplify the code

 // No view parser specified:
//   modelAndView.setViewName("/WEB-INF/view/show.jsp");

/*
*  When the view parser is configured, the file name is used as the view name, which is called the view logical name
* The logical name is used. The framework uses the prefix and suffix of the view parser in the configuration file to splice into a complete view path
* /WEB-INF/view/show.jsp
* */
modelAndView.setViewName("show");

For example, the same processing method can be used for different requests through the central scheduler,

Request page:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="some.do">launch some.do request</a>
    <br/>
    <a href="first.do">launch first.do request</a><br/>
    <a href="other.do">launch other.do request</a><br/>
    <a href="test/second.do">launch test.second.do request</a><br/>
</body>
</html>

Method of processing request

 // The value of the annotation indicates the request path that can be responded to
@RequestMapping(value = {"/other.do","/first.do","/test/second.do"})
    public ModelAndView doOther(){ // doGet()
        // The doOther method of myController is executed
        // Use this method to process requests. The method that can process requests is called the controller method
        // Call the service object to process the request and return data
        ModelAndView modelAndView = new ModelAndView();
        // Add data
        modelAndView.addObject("msg","Handled Other.do request");
        modelAndView.addObject("fun","Yes doOther method");

        // Specifies the view to display the data
//        modelAndView.setViewName("/WEB-INF/view/show.jsp");

        /*
        *  When the view parser is configured, the file name is used as the view name, which is called the view logical name
        * The logical name is used. The framework uses the prefix and suffix of the view parser in the configuration file to splice into a complete view path
        * /WEB-INF/view/show.jsp
        * */
        modelAndView.setViewName("other");
        // Return results
        return modelAndView;
    }
}

1.5 basic idea of CPU implementation

When all requests pass through the central processor, the central processor assigns them to different controllers according to the type and name of the request

The user initiates some.do - dispatcher servlet (servlet receiving request) - and forwards it to MyController

public class DispatcherServlet extends HttpServlet{
    public void service(HttpServletRequest request, HttpServletResponse response){
		 if("some.do".equals(request.getURI())){
             //Get MyController from container
             MyController c  = ctx.getBean("some"));
             c.doSome();
         } else if( "other.do".equals(request.getURI())){
             OtherController c  = ctx.getBean("other"));
             c.doOther();
         }
    }
}

1.6 description of configuration file in Web Development

  1. web.xml deployment descriptor file for the server (tomcat).

    Function: when the server starts, it reads web.xml and creates various objects according to the declaration in the file,

    According to the declaration in the file, the server can know the relationship between the request and objects such as servlet s.

  2. Framework configuration file, spring MVC configuration file

    Function: declare various objects in the project created by the framework, mainly to create Controller objects

Loading order and function of configuration file

  1. The tomcat server starts, reads web.xml, and creates objects according to the instructions in the web.xml file.

    <servlet>
            <servlet-name>myweb</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!--Custom profile location-->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc.xml</param-value>
            </init-param>
            <!--
               Represents the server tomcat The order in which objects are created is an integer value greater than or equal to 0.
               The smaller the value, the earlier the object is created.
            -->
            <load-on-startup>1</load-on-startup>
        </servlet>
    

    When the DispatcherServlet object is created, the init() method will be executed. Spring MVC container object creation is performed in the init() method

    WebApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:springmvc.xml")

  2. Spring MVC framework, new ClassPathXmlApplicationContext() reads the configuration file of spring MVC.

     <context:component-scan base-package="com.bjpowernode.controller" />
    
        <!--Declarative view parser: help with views-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!--Prefix: Specifies the path to the view file-->
            <property name="prefix" value="/WEB-INF/view/" />
            <!--Suffix: extension of the view file-->
            <property name="suffix" value=".jsp" />
        </bean>
    

    Use the component scanner base package = "com.bjpowernode.controller", traverse all classes in the controller package, MyController class, find the @ controller, @ RequestMapping annotation in this class, and then you can create the MyContoller object.

    Know that the request for some.do is to execute the doSome() method

    The above 1 and 2. Are the process of project startup without executing any user requests.

  3. User initiated request some. Do --- dispatcherservlet

    There is a WebApplicationContext in the dispatcher servlet. There is a MyController object in the WebApplicationContext.

    When some.do is requested, the dispatcher servlet will know that it is handled by MyController.

1.7 internal execution process of spring MVC

Spring MVC internal request processing:

  1. The user initiates a request to the dispatcher servlet

  2. The dispatcher servlet gives the request to the processor mapper.

    Processor mapper: an object in the spring MVC framework that needs to implement the HandlerMapping interface.

    Role of mapper: get the controller object (MyController) from the spring MVC container, put the found controller and interceptor objects into the processor execution chain object, save them, and return them to the central scheduler. (MyController controller = ApplicationContext.getBean())

  3. The dispatcher servlet gives the controller object in the processor execution chain to the processor adapter

    Processor adapter: an object in the spring MVC framework that implements the HandlerAdapter interface.

    Adapter function: execute the controller method, that is, execute the MyController.doSome() method. Get the result ModelAndView

  4. The dispatcher servlet gives the controller execution result mv to the view parser

    View parser: the object in spring MVC needs to implement the ViewResolver interface.

    Function of View parser: handle the of the View and the complete path of the View. It can create View type objects

  5. DispatcherServlet calls the method of the View class to put the data in the Model into the request scope. Execute request.setAttribute(), forward() forwarding the View, request. Getrequestdispatcher ("/ show. JSP"). Forward (request, response)

1.8 web request processing sequence using spring MVC framework

1.9 MVC components of spring MVC

1.10 execution process of spring MVC

Perform simple process analysis

(1) The browser submits the request to the central scheduler

(2) The central scheduler forwards the request directly to the processor mapper.

(3) The processor mapper will find the processor processing the request according to the request, encapsulate it as a processor execution chain, and then return it to the central scheduler.

(4) The central scheduler finds the processor adapter that can execute the processor according to the processor in the processor execution chain. (5) the processor adapter calls the execution processor.

(6) The processor encapsulates the processing result and the view to jump into an object ModelAndView, and returns it to the processor adapter.

(7) The processor adapter returns the result directly to the central scheduler.

(8) The central scheduler calls the view parser to encapsulate the view name in ModelAndView as a view object.

(9) The view parser returns the encapsulated view object to the central scheduler

(10) The central scheduler calls the view object to render by itself, that is, data filling to form a response object. (11) the central scheduler responds to the browser

Server response interface:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <p>Handled show request</p>
    <h3>Enter your name: ${myname}</h3>
    <h3>Enter your age: ${myage}</h3>
</body>
</html>

Chapter 2 spring MVC annotated development

2.1 notes: @ RequestMapping

@RequestMapping can be used in two places: one is on the class name and the other is on the method

/**
 * @Controller : Create controller (processor) object
 *  Controller: it is called back controller, a custom class that handles requests
 *  Location: it is written on the top of the class, indicating the creation of such an object, which is placed in the spring container
 *
 * @RequestMapping
 *  Attribute value: represents the public prefix of all request addresses, which is equivalent to the name of the module
 *  Position above class
 */
@RequestMapping("/test")
@Controller
public class MyController {
    /**
     * @RequestMapping : Request mapping
     *      Attribute: Value: uri address in the request, unique value, starting with "/"
     *      Location: 1. Must be above the method, 2. Above the class definition (optional)
     *      Function: submit the specified request to the specified method for processing, which is equivalent to URL pattern
     *
     * Return value ModelAndView: indicates the processing result (data and view) of this request
     *      Model : Represent data
     *      View : Representation view
     *
     * */
//    @RequestMapping(value = {"test/some.do","test/first.do"}) / / no public prefix is declared above the class
    @RequestMapping(value = {"/some.do","/first.do"})//The public prefix / test is declared above the class
    public ModelAndView doSome(){
        System.out.println("doSome()Method is executed");
        ModelAndView modelAndView = new ModelAndView();
        // Add data
        modelAndView.addObject("msg","Handled Some.do request");
        modelAndView.addObject("fun","Yes doSome method");

        modelAndView.setViewName("show");
        // Return results
        return modelAndView;
    }
//    @RequestMapping(value = {"test/other.do","/test/second.do"}) / / there is no public prefix declared above the class
    @RequestMapping(value = {"/other.do","/second.do"})//The public prefix / test is declared above the class
    public ModelAndView doOther(){

        ModelAndView modelAndView = new ModelAndView();
        // Add data
        modelAndView.addObject("msg","Handled Other.do request");
        modelAndView.addObject("fun","Yes doOther method");

        modelAndView.setViewName("other");
        // Return results
        return modelAndView;
    }
}

The attribute method is the request method. The enumeration of the RequestMehtod class is used to represent the request method. If there is no method attribute, the request can succeed in both get and post methods. If the get or post attribute is specified, it can only use one request method

@RequestMapping(value ="/other.do",method = RequestMethod.POST)
public ModelAndView doOther(){

2.2 parameters in receive request

The corresponding HttpServletRequest, httpservletresponse and httpsession only need to be defined in the formal parameter list of the controller method. The framework will assign values to parameters. request, response and session parameters can be directly used inside the controller method.

@RequestMapping(value = "/receive-param.do", method = RequestMethod.POST)//The public prefix / test is declared above the class
public ModelAndView doSome(HttpServletRequest request, HttpServletResponse response, HttpSession session){}

400: http status, indicating client exception. It mainly occurs in the process of user submitting parameters.

Parameters in receive request: receive one by one, object by object

2.2.1 receiving one by one

Receive one by one: the parameter name in the request is the same as the formal parameter name of the controller method. Receive parameters by name object

<p>Receive request parameters one by one</p>
<form action="receive-property.do" method="post">
    full name:<input type="text" name="name"> <br/>
    Age:<input type="text" name="age"> <br/>
    <input type="submit" value="Submit parameters">
</form>

Controller receive parameters

/**
 * Receive request parameters one by one,
 *  Requirement: the parameter name in the request should be the same as the formal parameter name of the controller method, and the request parameters are received by the name object
 *
 *  Internal implementation of parameter reception:
 *  1. The framework uses the request object to receive parameters
 *      String name = request.getParameter("name");
 *      String age = request.getParameter("age");
 *  2. When the doProperParam method is called inside the central scheduler, the parameters are passed by name object
 *      doPropertyParam(name,Integer.valueOf(age))
 *      The framework can convert request parameters from String to int,long,float,double and other types
 * */
@RequestMapping(value ="/receive-property.do")
public ModelAndView doPropertyParam1(String name , Integer age){
        System.out.println("doPropertyParam1()Method is executed");
        ModelAndView modelAndView = new ModelAndView();
        System.out.println(name+":"+age);
        // Add data
        modelAndView.addObject("myname",name);
        modelAndView.addObject("myage",age);
        modelAndView.setViewName("show");
        // Return results
        return modelAndView;
    }

Problems with receiving parameters:

  1. It is best to use the packing type for the parameter. For example, Integer can receive null values and null values
  2. The framework can use String to int, long, float, double and other type conversions.
  3. If there is a problem of garbled code in the post request, use the character set filter.

2.2.2 configure character set filter in web.xml. Characterencoding filter

 <!--    Declaration filter,Provided by the framework,solve post Garbled code problem-->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <!--            Character encoding used by the project: utf-8-->
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
        <init-param>
            <!--            Mandatory request(request)Object use encoding Coding method of(Namely utf-8)-->
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <!--            Forced response(response) Object use encoding Coding method of-->
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <!--       Force all requests to go through the filter -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>

2.2.3 if the parameter name and formal parameter name in the request are different, use @ RequestParam

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Request mode</title>
</head>
<body>
    <p>Receive request parameters one by one</p>
    <form action="receive-param.do" method="post">
        full name:<input type="text" name="AAname">
        Age:<input type="text" name="AAage">
        <input type="submit" value="Submit parameters">
    </form>
</body>
</html>
 /* @RequestParam : Solve the problem of different names
 *      Attribute: parameter name in value request
 *           required : boolean Type. The default is true
 *              true : This parameter must be present in the request, otherwise an error will be reported
 *             false : This parameter may not be present in the request
 *      Position: in front of parameter definition
 * */
@RequestMapping(value = "/receive-param.do", method = RequestMethod.POST)//The public prefix / test is declared above the class
public ModelAndView doPropertyParam
    (@RequestParam(value = "AAname",required = true) String name ,
     @RequestParam(value = "AAage",required = false) Integer age){}

/*
	In addition, value = AAname is the same as the value passed by the form at the front end
	The above means that name must have a value, and age can pass the value or not
*/

2.2.4 object reception

public class Student {
    String name;
    Integer age;
	// There must be a parameterless constructor
    public Student() {
    }
	// The set method must be implemented, and the get method and toString method can be implemented optionally, which has been omitted here
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Request mode</title>
</head>
<body>

    <p>Object receive request parameters: The parameter name in the request is the same as the property name of the object</p>
    <form action="receive-param3.do" method="post">
        full name:<input type="text" name="name">
        Age:<input type="text" name="age">
        <input type="submit" value="Submit parameters">
    </form>

</body>
</html>
/*
* Use the object to receive the parameters in the request,
*   Requirement: the parameter name is the same as the object attribute name of java
*           java Class needs a parameterless constructor and property has a set method
*   How does the framework handle object parameters?
*      1. Call the parameter construction method of the Student object to create the object
*       2.Call the set method of the object, and call the corresponding set method for the parameter with the same name
*           If the parameter is name, call setname (parameter value)
*     Note: if you use an object to receive parameters, you cannot use an alias to receive parameters,
*           The property name and parameter name of the object must be the same
* */
@RequestMapping(value = "/receive-param3.do", method = RequestMethod.POST)//The public prefix / test is declared above the class
public ModelAndView doPropertyParam3(Student student){}

2.3 return value of controller method

The return value of the controller method represents the processing result of this request. The return values include modelandview, string, void and object

The processing result of the request includes: data and view

2.3.1 ModelAndView data and views

The results of the request have data and views, and ModelAndView is the most convenient

Data: store request scope

View: performing forward forwarding operations

2.3.2 String view

The return value corresponding to the framework is String, which performs forward forwarding operation (which is used to operate the view)

Views can be expressed as the path of the full view or the logical name of the view in a string

Request page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Request mode</title>
</head>
<body>
    <p>Controller method return String-Logical view name</p>
    <form action="return-string-view1.do" method="post">
        full name:<input type="text" name="name">
        Age:<input type="text" name="age">
        <input type="submit" value="Submit parameters">
    </form>
</body>
</html>
Logical name
/**
 * The control method returns a String representing the logical name. The view parser needs to be configured in the project
 */
@RequestMapping(value = "/return-string-view1.do", method = RequestMethod.POST)//The public prefix / test is declared above the class
public String doReturnStringView1(HttpServletRequest request,String name , Integer age){
    System.out.println("doReturnStringView1()Method is executed");
    // You can also process data here
    request.setAttribute("myname",name);
    request.setAttribute("myage",age);
    // The returned result, forward, is forwarded to show.jsp
    return "show";
}
Full path
@RequestMapping(value = "/return-string-view2.do", method = RequestMethod.POST)//The public prefix / test is declared above the class
   public String doReturnStringView2(String name , Integer age){
       System.out.println("doReturnStringView2()Method is executed");

       // The returned result, forward, is forwarded to show.jsp,
       // The view parser is not used. If the view parser is used, its actual address is like this
      //  Of: / WEB-INF/view/WEB-INF/view/show.jsp.jsp
       return "/WEB-INF/view/show.jsp";
   }

2.3.3 void has no data and view

void: without data and view, you can use HttpServletResponse object to output data and respond to ajax requests

Environment construction, pom.xml introduces json dependency
<!--    jackson-->
    <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>
Request page: jquery-3.4.1.js package needs to be imported
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Request mode</title>
    <script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<%--    Give button btnAjax Binding event: Click the button to initiate ajax request--%>
    <script type="text/javascript">
        $(function(){
            $("#btnAjax").on("click",function () {
                $.ajax({
                    url:"return-void-ajax1.do",
                    method:"post",
                    data:{
                        name:"Zhang San ajax",
                        age:20
                    },
                    dataType:"json",
                    success:function (resp) {
                        // resp = XMLHttpRequest.responseText;
                        alert("resp=="+resp+":"+"name="+resp.name+"-"+resp.age);

                    }
                })
            })
        })
    </script>
</head>
<body>
    <p>launch ajax request</p>
    <button id="btnAjax" type="button">launch ajax request</button>
</body>
</html>
Server response request
  // The controller method returns void, responds to ajax requests, and uses HttpServletResponse to output data
@RequestMapping(value = "return-void-ajax1.do", method = RequestMethod.POST)//The public prefix / test is declared above the class
    public void doReturnVoidAjax1(HttpServletResponse response,String name , Integer age) throws IOException {
        System.out.println("doReturnVoidAjax1()Method is executed");
        // Processing data from clients
        Student student = new Student();
        student.setName(name+"classmate");
        student.setAge(age);

        // Convert object to json
        ObjectMapper om = new ObjectMapper();
        String json = om.writeValueAsString(student);
        System.out.println("Server converts object to json:"+json);

        // Output json in response to ajax
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(json);
        writer.flush();
        writer.close();
    }

2.3.4 return Object

For example, the returned Student represents data. So the controller method returns the Object object to respond to the ajax request. The returned Object can be List, Student, Map,String, Integer, etc. These are all data. In the ajax request, the data in json format is generally returned from the server, It is often necessary to handle the conversion from java objects to json. In addition, it also needs to output data to respond to ajax requests. The framework also provides the work (Methods) to handle the conversion from java objects to json and output data

2.2.4.1 HttpMessageConverter message converter

HttpMessageConverter interface, function:

(1) the requested data can be converted into java objects,

(2) convert the object returned by the controller method into data in different formats such as json, xml, text, binary, etc

MediaType is the media type. It represents the format of data in the Internet. For example, application/json, text/html, image/gif

public interface HttpMessageConverter<T> {
   /** 
   	Function: check whether the object of clazz type can be converted to the data format represented by mediaType
   		If it can be converted to the type represented by mediaType, return true and call read()
   			Otherwise, false will be returned and read() will not be called
    */
   boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);
   /**
  		Function: receive the data in the request and convert the data into the object represented by clazz
    */
   T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
         throws IOException, HttpMessageNotReadableException;
  
    /**
   		Function: check whether clazz this data type can be converted to the data type represented by mediaType
   			If it can be converted to the type represented by mediaType, return true and call write()
   				Otherwise, false is returned and write() is not called
   		
    */
    boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);
   /**
   Function: convert the t object into json or xml according to the format described by contentType
    */
   void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage)
         throws IOException, HttpMessageNotWritableException;

}
2.3.4.2 implementation class of data format conversion
//Implementation class of HttpMessageConverter interface:
MappingJackson2HttpMessageConverter : use jsckson In the tool library ObjectMapper hold java Object to json data format
    
StringHttpMessageConverter : String type data,Format conversion and coding.
2.3.4.3 how to use implementation classes

The framework automatically finds the implementation class used according to the method return type of the controller

First, according to the return value type of the doReceiveObject() method, pass the type into the canwrite() method to judge whether it can be converted into the mediaType type. If so, return true, and call the write() method to convert it into json format

 @RequestMapping(value = "/receive-param1.do", method = RequestMethod.POST)//The public prefix / test is declared above the class
    public Student doReceiveObject(String name , Integer age){
        System.out.println("doReceiveObject()Method is executed");
       	Student student = new Student();
        student.setName("Li Si");
        student.setAge(20);
        return student;
    }

By default, springmvc uses four implementation classes of the httpmessageconverter interface, including StringHttpMessageConverter. You need to add the annotation driven label MVC: annotation driven in the configuration file of springmvc. After adding this label, the seven implementation class objects of the httpmessageconverter interface will be automatically created after the springmvc project is started, Including StringHttpMessageConverter and MappingJackson2HttpMessageConverter, which can complete the conversion from java objects to json

<!--  springMVC Annotation driven is declared in the configuration file: establish HttpMessageConverter Seven implementation classes of the interface
	http://www.springframework.org/schema/mvc
-->
    <mvc:annotation-driven/>
HttpMessageConverter interface implementation classeffect
ByteArrayHttpMessageConverterBe responsible for reading data in binary format and writing data in binary format
StringHttpMessageConverterResponsible for reading string format data and writing string format data
ResourceHttpMessageConverterBe responsible for reading resource files and writing out resource file data
SourceHttpMessageConverterjavax.xml.transform.Source that can read / write requests and responses from HTTP, and supports XML formats of DOMSource, SAXSource, and StreamSource
AllEncompassingFormHttpMessageConverterResponsible for processing form data
Jaxb2RootElementHttpMessageConverterJAXB is responsible for reading and writing data in xml tag format
MappingJackson2HttpMessageConverterResponsible for reading and writing data in json format. Use Jackson's ObjectMapper to read and write json data, operate Object type data, and read application/json. The response media type is application/json
2.3.4.5 @ResponseBody

@The use of the ResponseBody annotation is to output the json after student conversion to the browser object through the HttpServletResponse object

The basic implementation code is as follows:

// Output json in response to ajax
response.setContentType("application/json;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.write(json);
writer.flush();
writer.close();

// @The ResponseBody annotation is used to implement the above code
2.3.4.6 steps of converting the returned object of the controller method to json

(1) pom.xml, add Jackson dependency and spring MVC framework. By default, jackson.xml is used to process json

(2) In the spring MVC configuration file, add the annotation driven label MVC: annotation - dirty

(3) Add @ ResponseBody annotation on the controller method to represent the return value data and output it to the browser

Return object data

Request page;

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Request mode</title>
    <script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<%--    Bind event to button--%>
    <script type="text/javascript">
        $(function () {
            $("#btnAjax1").on("click",function () {
                $.ajax({
                    url:"doStudentJson.do",
                    method: "post",
                    data: {
                        name:"Li Si",
                        age:40
                    },
                    dataType: "json",
                    success:function (resp) {
                        alert("resp=="+resp+":"+"name="+resp.name+"-"+resp.age);
                    }

                })
            })
        })
    </script>
</head>
<body>
    <p>launch ajax request:Return object Student</p>
    <button id="btnAjax1" type="button">launch ajax request</button>

</body>
</html>

Processing requests

/**
 * The controller method returns Student and converts the object to json
 * Coding format: application/json;charset=utf-8
 *
 * Processing mode of framework:
 *  1. The framework finds the implementation class of HttpMessageConverter interface according to the return value type of the controller
 *      The last one found is MappingJackson2HttpMessageConverter
 *  2. Use the implementation class MappingJackson2HttpMessageConverter. To execute his write() method,
 *      The student object is converted into json format data
 *  3. The framework uses the @ ResponseBody annotation to output the json in 2 to the browser
 *      
 * */
@RequestMapping("/doStudentJson.do")
@ResponseBody
public Student doAjaxJson(String name, Integer age){
    System.out.println("The controller method returns a custom object, Turn into json:"+name+"=="+age);
    Student student = new Student();
    student.setName(name+"classmate");
    student.setAge(age);
    return student;
}
Return collection data
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Request mode</title>
    <script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<%--    Bind event to button--%>
    <script type="text/javascript">
        $(function () {
            $("#btnAjax2").on("click",function () {
                $.ajax({
                    url:"doAjaxJsonArray.do",
                    method: "post",
                    data: {
                        name:"Li Si",
                        age:40
                    },
                    dataType: "json",
                    success:function (resp) {
                        // Resp: [{"name": "classmate Li Si", "age":40},{"name": "classmate Zhang San", "age: null}]
                       $.each(resp,function (i,n) {
                       //     i is a cyclic variable
                       //    n is the member, that is, the Student object in the list collection, {"name": "Li Si classmate", "age":40}
                           alert("resp:=="+i+"=:="+"name="+n.name+"-"+n.age);
                           // resp:==0=:=name = classmate Li Si - 40
                           // resp:==1=:=name = Zhang San - null
                       })
                    }
                })
            })
        })
    </script>
</head>
<body>
    <p>launch ajax request:Return object List</p>
    <button id="btnAjax2" type="button">launch ajax request</button>

</body>
</html>
/*
   Returns the List collection
* */
@RequestMapping("/doAjaxJsonArray.do")
@ResponseBody
public List<Student> doAjaxJsonArray(String name, Integer age){
    System.out.println("The controller method returns a custom object, Turn into json:"+name+"=="+age);
    Student student = new Student();
    student.setName("Li Si");
    student.setAge(age);
    Student student1 = new Student();
    student1.setName("Zhang San");
    List<Student> students = new ArrayList<>();
    students.add(student);
    students.add(student1);
    return students;
}
Return string data
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Request mode</title>
    <script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<%--    Bind event to button--%>
    <script type="text/javascript">
        $(function () {
            $("#btnAjax3").on("click",function () {
                $.ajax({
                    url:"doStringData.do",
                    method: "post",
                    data: {
                        name:"Li Si",
                        age:40
                    },
                    dataType: "text",
                    success:function (resp) {
                      alert("Returned data"+resp);
                    }

                })
            })
        })
    </script>
</head>
<body>
    <p>launch ajax request:return String data</p>
    <button id="btnAjax3" type="button">launch ajax request</button>

</body>
</html>

Processing requests

/*
  The controller method returns String type data,

      The way to distinguish whether the returned value is view or data is to see whether there is @ ResponseBody annotation on the method
      If there is no view, if there is data

       This annotation the default transport type
      Content-Type: text/plain;charset=ISO-8859-1

      To solve the Chinese problem, you need to use the @ RequestMapping products attribute
      produces Property: Specifies the value of content type

      The framework handles the String return value
       1.StringHttpMessageConverten used by the framework
       2. StringHttpMessageConverter Text / plain is used by default; charset=ISO-8859-1

   * */
   @RequestMapping(value = "/doStringData.do",produces = "text/plain;charset=utf-8")
   @ResponseBody
   public String doStringData(String name, Integer age){
       System.out.println("Controller method return String,It's data");

       return "Hello Springmvc Annotated development";
   }

2.4 static resource processing

Access address:

When the URL pattern of the central scheduler (DispatcherServlet) in web.xml is *. do

http://localhost:8080/ch05_url_pattern/index.jsp tomcat processing request

http://localhost:8080/ch05_url_pattern/js/jquery-3.4.1.js tomcat processing request

http://localhost:8080/ch05_url_pattern/images/p1.jpg tomcat processing request

http://localhost:8080/ch05_url_pattern/html/test.html tomcat processing request

http://localhost:8080/ch05_url_pattern/some.do DispatcherServlet (spring MVC framework) handles requests

2.4.1 default servlet of Tomcat

In the tomcat installation directory, / conf/web.xml

<!-- The default servlet for all web applications, that serves static     -->
  <!-- resources.  It processes all requests that are not mapped to other   -->
  <!-- servlets with servlet mappings (defined either here or in your own   -->
  <!-- web.xml file).  This servlet supports the following initialization   -->
  <!-- parameters (default values are in square brackets):                  -->

<servlet>
    <servlet-name>default</servlet-name>
    <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
    <init-param>
        <param-name>debug</param-name>
        <param-value>0</param-value>
    </init-param>
    <init-param>
        <param-name>listings</param-name>
        <param-value>false</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>


<!-- The mapping for the default servlet -->
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>


default Is the default servlet 
	effect: 
	1. It provides processing of static resources.
	2.It handles all request processing that is not mapped to other requests.(That is, there are no in the project web.xml to configure servlet Tagged)

2.4.2 central scheduler setting "/"

http://localhost:8080/ch05_url_pattern/index.jsp tomcat processing request

http://localhost:8080/ch05_url_pattern/js/jquery-3.4.1.js 404 DispatcherServlet handles the request. It has no object to handle the request

http://localhost:8080/ch05_url_pattern/images/p1.jpg 404 DispatcherServlet handles the request. It has no object to handle the request

http://localhost:8080/ch05_url_pattern/html/test.html 404 DispatcherServlet handles the request. It has no object to handle the request

http://localhost:8080/ch05_url_pattern/some.do 200 DispatcherServlet handles the request. It has the object MyController.com that handles the request

Reasons for the above situation:

    When web.xml Central scheduler(DispatcherServlet)of url-pattern Yes, use slashes "/" . This causes the central scheduler to be called the default default servlet. 
    Static resources and other unmapped requests need to be processed. The default central scheduler does not process
    Static resources are controller objects, so static resources are 404. some.do This request
    yes MyController Object, so it can be accessed.

    If the central scheduler is set in the project“/" , Dynamic resources can be accessed, while static resources cannot.
    Then you need to handle the access of static resources.

2.4.3 the first method deals with static resources

Add the MVC: default servlet handler tag to the spring MVC configuration file. The spring MVC framework will add the DefaultServletHttpRequestHandler object to handle the access of static resources when the project is running.

Add the < MVC: default servlet handler / > tag to the spring MVC configuration file to access static resources. However, dynamic resources cannot be requested. At this time, you only need to add the < MVC: annotation driven / > tag to access static resources

<!--Declarative annotation driven
    default-servlet-handler and@RequestMapping Conflicting use
-->
<mvc:annotation-driven />

<!--The first way to declare static resources
    establish DefaultServletHttpRequestHandler Processing static resources.
    DefaultServletHttpRequestHandler Forward the address of the received static resource to tomcat of default

    advantage:
      The solution is simple
    Disadvantages:
      rely on tomcat The capabilities provided by the server.
-->
<mvc:default-servlet-handler />

2.4.4 processing method of the second static resource

Add a < MVC: Resources / > tag to the spring MVC configuration file. The framework will create a ResourceHttpRequestHandler controller object, which will be used to handle the access of static resources. This approach is independent of the tomcat server. Recommended.

<!--Declarative annotation driven
        resources and@RequestMapping Conflicting use
    -->
    <mvc:annotation-driven />

    <!--The second way to declare static resources
        mapping: Access to static resources uri Address, wildcards can be used(**). 
                  ** : Represents any directory and resource name
        location: Do not use the location of static resources in the project/WEB-INF catalogue

    -->
    <mvc:resources mapping="/images/**" location="/images/" />
    <mvc:resources mapping="/html/**" location="/html/" />
    <mvc:resources mapping="/js/**" location="/js/" />



    <!--Set static resources in one sentence : All static resources are stored in static Directory-->
    <!--<mvc:resources mapping="/static/**" location="/static/" />-->

Chapter III SSM integrated development

3.1 SSM integration ideas

Spring MVC + Spring + MyBatis (ibatis), so it is called SSI integration. SSM integration is the advantage function of using three frameworks. The three frameworks correspond to the three layers of the three-tier architecture. Spring MVC is the view layer, spring is the business layer and MyBatis persistence layer.

For SSM integration, you need to hand over the objects to the container management, and let the container create java objects to be used in the project. Now there are two containers

The first is the Spring container: the Spring container manages objects such as service and dao. It is the container of business layer objects

The second is the spring MVC container: the view layer object that manages the controller object

SSM integration is to hand over objects to container management. Two containers coexist. Each is responsible for managing different objects. Declare the objects in the configuration file and let the two containers create objects. Spring creates service and dao; spring MVC creates controller.

3.2 creation of container

Spring container creation: the listener ContextLoaderListener is declared in web.xml, and the function framework is written. The function is to create the spring container object WebApplicationContext. When creating the WebApplicationContext object, read the spring configuration file. When reading the file, when encountering bean tags or annotations, you can create service,dao and other objects into the container

Spring MVC container: the central scheduler DispatcherServlet is declared in web.xml. In the init () method of this servlet, the container object WebApplicationContext is created. When creating the WebApplicationContext object and reading the springmvc configuration file, when reading the file, the @ Controller annotation is encountered, the Controller controller object is created and placed in the container.

In memory, the implementation code for creating the object:

WebApplicationContext spring = new WebApplicationContext(); //spring–map(service, dao)

WebApplicationContext springmvc = new WebApplicationContext(); //springmvc–map(controller)

Relationship between spring MVC container and spring container: Spring MVC container object is designed to be a child container of spring container.

Spring is the parent container. Spring MVC is the child container. It is equivalent to the inheritance relationship in java.

3.3 SSM integration development steps

  1. Used student2 table (id, name, age)

  2. Create maven web project

  3. Modify pom.xml and add dependencies: spring, springmvc, mybatis, mybatis spring, MySQL driver, druid, jackson

  4. Writing web.xml: declaring container objects

    1) Declare spring listener ContextLoaderListener: create spring container object, service object and dao object

    2) Declare the DispatherServlet of the central scheduler of spring MVC: create the spring MVC container object and the controller object

    3) Declare the filter characterencoding filter of the character set to solve the problem of garbled code in post requests

  5. Create packages, dao, service, controller and entity in the program

  6. Write spring, spring MVC and mybatis configuration files

  7. Write java code, entity class, dao interface and mapper file, service class and controller class. Object declaration and assignment using annotations

  8. Create view files, various JSPS

    An example of inserting and querying students into mysql database

3.4 relative path

In the page, there is a path problem. The access path starts with "/" and does not have "/".

<a href="test/some.do">No slash start</a>
<a href="/test/some.do">Start with a slash</a>
<a href="http://Www.baidu.com "> there is an address at the beginning of the agreement</a>

Address difference, now look at the address in the page.

1) With the beginning of the agreement, e.g http://www.baidu.com , called the absolute address. The address is unique and you can access it directly

2) If there is no protocol beginning, for example, test / some.do, / test / some.do is called a relative address. A relative address used alone cannot represent a resource and cannot be accessed. A relative address must have a reference address together to represent the complete address of a resource and can be accessed.

Reference address: there are "/" and no "/" reference addresses different.

1) Address without slash. Reference address: the access path of the current resource

Currently accessed address: http://localhost:8080/ch07_path/index.jsp

Resource Name: index.jsp

Resource path: http://localhost:8080/ch07_path

There is an access address a href = "test/some.do" in index.jsp

After clicking some.do, the address becomes http://localhost:8080/ch07_path/test/some.do

At this time: http://localhost:8080/ch07_path/test/some.do
 Resource Name: some.do
 Resource path: http://localhost:8080/ch07_path/test/

Click on test/some.do Address: http://localhost:8080/ch07_path/test/test/some.do

Address without slash: the combination of reference address + current relative address is the last access address

Solution:

1)use ${pageContext.request.contextPath}.  Indicates the path to access the project (upper and lower files) context path)
<a href="${pageContext.request.contextPath}/test/some.do">Initiate request test/some.do</a>

Advantages: easy to understand
 Disadvantages: each link address needs to be added el expression

2)No fixed in the current page“/"Reference address of the beginning address
 use html in base label
<!--http://localhost:8080/ch07_path/test/some.do-->
<%	 
  String basePath = request.getScheme() + "://" + request.getServerName()
          +":"+request.getServerPort()+request.getContextPath()+"/";
%>
<head>
  <title>Browse students</title>
  <base href="<%=basePath%>">
</head>
  1. Address with slash

a href="/test/some.do"

Visit now http://localhost:8080/ch07_path/index.jsp
 stay index.jsp There are  /test/some.do.
click/test/some.do,Address becomes http://localhost:8080/test/some.do

The address that begins with a slash. The reference address is the server address, that is, the position from the beginning of the protocol to the port number http://localhost:8080

Address composition: http://localhost:8080/test/some.do

The address will be missing the project access path, ch07_path. 

Solution: add the el expression ${pageContext.request.contextPath} in front of your path

<p>yes/Start address</p>
<a href="${pageContext.request.contextPath}/test/some.do">/test/some.do</a>

The fourth chapter is the core technology of spring MVC.

4.1 forwarding and redirection

forward: view full path

/*
* The controller method returns ModelAndView to implement forward
*
*   Syntax: modelAndView.setViewName("forward: View completion path");
*
*   forward The feature that does not work with the view parser is that even if the view parser is configured in the project,
*       The view parser does not process this path either
*
* */
@RequestMapping("/doForward.do")
public ModelAndView doForward(){
    ModelAndView modelAndView =  new ModelAndView();
    modelAndView.addObject("msg","doForward Method is executed");
    modelAndView.addObject("fun","Entered doForward method");
    // The forward forwarding operation is displayed. That is, forwarding without forward is also forwarding, but its central feature is that it can not be limited by the view parser
    modelAndView.setViewName("forward:/WEN-INF/jsp/show.jsp");

    return modelAndView;
}

redirect: view full path

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>redirect</h1>
    <h2>adopt el Expression value</h2>
    <h3>myname: ${myname}</h3>
    <h3>myage: ${myage}</h3>
    <hr/>
    <h2>adopt param aggregate</h2>
    <h3>myname: ${param.myname}</h3>
    <h3>myage: ${param.myage}</h3>
    <hr/>
    <h2>java Code value</h2>
    <h3>myname: <%= request.getParameter("myname")%>></h3>
    <h3>myage:  <%= request.getParameter("myname")%></h3>

</body>
</html>
/*When the controller method returns ModelAndView, redirect is implemented
*   Syntax: modelAndView.setViewName("redirect: full path of the view");
*   redirect Features: it does not work with the view parser, just as there is no view parser in the project,
*
*   Redirection provided by the framework
*   1. The framework can realize the data transfer between two requests and put the Model in the first request
* Simple type data is converted into a string, attached to the back of the target page, and passed as a get parameter,
*   You can get the parameter value in the target page
*   2.In the target page, you can use ${param. Parameter name} to get the value of the parameter
*   3. Redirection cannot access the protected directory / WEB-INF
*
* */
@RequestMapping(value = "/doRedirect.do")
public ModelAndView doRedirect(String name,Integer age){
    System.out.println("doRedirect:"+name+":"+age);
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("myname",name);
    modelAndView.addObject("myage",age);
    //  modelAndView.setViewName("redirect:/WEN-INF/jsp/other.jsp");//  cannot access
    modelAndView.setViewName("redirect:/other.jsp");
    return modelAndView;
}
mv.setViewName("forward:/hello.jsp");
mv.setViewName("redirect:/other.jsp");

4.2 exception handling

CH08 exception handler: exception handling

Steps:
1. Create a new web application
2. Add web dependency
Spring webmvc dependency (spring MVC framework dependency), servlet dependency.

3. Declare the spring MVC core object DispatcherServlet
1) Dispatcher Servlet is a Servlet object.
2) The dispatcher servlet is called a front controller
3) Dispatcher servlet functions:
(1) . in the init () method of the servlet, create the container object in spring MVC.
WebApplicationContext ctx = new ClassPathXmlApplicationContext("appliationContext.xml")

(2) receive the request as a servlet.

4. Create a jsp and initiate a request with parameters name and age

5. Create the exception class MyUserException,
Subclass nameexception, ageexception

6. Create a common class to be used as a controller (instead of the previous servlet)
1) Add the @ Controller annotation on the class
2) Define the method in the class. Throw nameexception and ageexception according to the values of the request parameters name and age

7. Create the resulting jsp page

8. Create a common class as an exception handling class.
1) Add @ ControllerAdvice to the class

2) define methods in the class, and each method handles the corresponding exception. Add the @ ExceptionHandler annotation above the method

9. Create a jsp page to handle exceptions.

10. Create the spring MVC configuration file (the same as the spring configuration file)
1) Declare the component scanner and specify the package name where the @ Controller annotation is located
2) Declare view parser object

3)Declaration component scanner, found@ControllerAdivce Annotation package name
 4)Declarative annotation driven

The framework uses centralized exception handling. Collect the exceptions thrown in each Controller to one place for processing. An exception handler is called an exception handler.

Two annotations are used in the framework to complete the centralized processing of exceptions. In this way, each controller does not have to handle exceptions separately. The notes are:

1) @ ExceptionHandler: placed above the method, indicating that this method can handle a certain type of exception. This method is executed when an exception occurs.

  1. @ControllerAdvice: placed on the top of the class, indicating that there are exception handling methods in this class. Equivalent to @ Aspect. In aop

@ ControllerAdvice is regarded as Controller enhancement, which is to add exception (aspect) handling function to the Controller class

Exception class definition

MyUserException

package com.nguyenxb.exception;

public class MyUserException extends Exception{
    public MyUserException() {
        super();
    }
    public MyUserException(String message) {
        super(message);
    }
}

NameException

package com.nguyenxb.exception;

public class NameException extends MyUserException{
    public NameException() {
        super();
    }

    public NameException(String message) {
        super(message);
    }
}

AgeException

package com.nguyenxb.exception;

public class AgeException extends MyUserException{
    public AgeException() {
        super();
    }

    public AgeException(String message) {
        super(message);
    }
}

Exception handling class

/*
*  @ControllerAdvice : Indicates that the current class is an exception handling class,
*       Adding functions to the controller,
*   Location: above the class
*
* */

@ControllerAdvice
public class GlobalExceptionHandler {
    // Define a method to handle exceptions, and execute this method when exceptions occur
    // The method definition is in the same format as the method definition in the Controller class

    /*
    * This method handles exceptions of type NameException
    * Parameters:
    *   Exception: Represents the exception object thrown by the Controller
    *
    *   ExceptionHandler : Indicates that this method handles exceptions
    *          Attribute: type of value exception
    *           Location: above the method
    * */
    @ExceptionHandler(value = NameException.class)
    public ModelAndView doNameException(Exception e){
        System.out.println("doNameException");
        /*
        * Exception occurred:
        *    1. Record exceptions and record them in the log file
        *    2. Occurrence notification, email, SMS, etc
        *     3.Improve user friendliness
        * */
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("tips","The name can only be Zhang San");
        modelAndView.setViewName("nameError");
        return modelAndView;
    }
    /*
    Handling AgeException
    * */
 @ExceptionHandler(value = AgeException.class)
    public ModelAndView doAgeException(Exception e){
     System.out.println("doAgeException");
        /*
        * Exception occurred:
        *    1. Record exceptions and record them in the log file
        *    2. Occurrence notification, email, SMS, etc
        *     3.Improve user friendliness
        * */
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("tips","Age cannot be greater than 80");
        modelAndView.setViewName("ageError");
        return modelAndView;
    }
    // Handle other exceptions
@ExceptionHandler
    public ModelAndView doOtherException(Exception e){
    System.out.println("doOtherException");
        /*
        * Exception occurred:
        *    1. Record exceptions and record them in the log file
        *    2. Occurrence notification, email, SMS, etc
        *     3.Improve user friendliness
        * */
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("tips","Please try again later");
        modelAndView.setViewName("defaultError");
        return modelAndView;
    }
}

Controller class:

@Controller
public class MyController {
    /*
    * The controller method returns ModelAndView to implement forward
    *
    *   Syntax: modelAndView.setViewName("forward: View completion path");
    *
    *   forward The feature that does not work with the view parser is that even if the view parser is configured in the project,
    *       The view parser does not process this path either
    *
    * */
    @RequestMapping("/some.do")
    public ModelAndView doSome(String name, Integer age) throws NameException, AgeException {
        System.out.println("Yes doSome method"+name+":"+age);
        if (!"Zhang San".equals(name)){
            throw new NameException("Incorrect name");
        }
        if (age==null || age.intValue() > 80){
            throw new AgeException("Too old");
        }
        ModelAndView modelAndView =  new ModelAndView();
        modelAndView.addObject("myname",name);
        modelAndView.addObject("myage",age);
        // Show forward forwarding operation. That is, forwarding without forward is also forwarding, but its feature is that it can not be limited by the view parser
        modelAndView.setViewName("show");

        return modelAndView;
    }


}

4.3 interceptor

Interceptor: it is an object in the spring MVC framework. It needs to implement the interface HandlerInterceptor to intercept user requests. Intercepted the controller's request.

**Function: * * intercept the user's request and process the request in advance. Decide whether to execute the controller according to the processing result. You can also define functions shared by multiple controllers to interceptors.

characteristic:

  1. Interceptors can be divided into system interceptors and custom interceptors.
  2. A project can have multiple interceptors. There are 0 or more custom interceptors.
  3. Interceptors focus on intercepting user requests.
  4. Interceptors are executed before request processing.

Definition of Interceptor:

1) Create a class to implement the interceptor interface HandlerInterceptor and implement the methods in the interface (3)

2) In the spring MVC configuration file, declare the interceptor object and specify the uri address of the interceptor

Ch10 Interceptor: interceptor, an interceptor

Steps:
1. Create a new web application
2. Add web dependency
Spring webmvc dependency (spring MVC framework dependency), servlet dependency.

3. Declare the spring MVC core object DispatcherServlet
1) Dispatcher Servlet is a Servlet object.
2) The dispatcher servlet is called a front controller
3) Dispatcher servlet functions:
(1) In the init () method of the servlet, create the container object in spring MVC.
WebApplicationContext ctx = new ClassPathXmlApplicationContext("appliationContext.xml")

(2) receive the request as a servlet.

4. Create a jsp and initiate a request with parameters name and age

5. Create a common class to be used as a controller (instead of the previous servlet)
1) Add the @ Controller annotation on the class
2) Define methods in a class

6. Create a jsp page as a result

7. Create a common class to implement HandlerInterceptor
override method

8. Create the spring MVC configuration file (the same as the spring configuration file)
1) Declare the component scanner and specify the package name where the @ Controller annotation is located
2) Declare view parser object
3) Declare the interceptor object and specify the uri address of the interceptor

4.3.1 example of an interceptor

controller:

@Controller
public class MyController {
    @RequestMapping("/some.do")
    public ModelAndView doSome(HttpSession httpSession,String name, Integer age) {
        System.out.println("Yes doSome method"+name+":"+age);

        // A temporary data
        httpSession.setAttribute("attr","MyController A temporary data.");

        ModelAndView modelAndView =  new ModelAndView();
        modelAndView.addObject("myname",name);
        modelAndView.addObject("myage",age);
        // Show forward forwarding operation. That is, forwarding without forward is also forwarding, but its feature is that it can not be limited by the view parser
        modelAndView.setViewName("show");

        return modelAndView;
    }


}

Interceptor

package com.nguyenxb.handler;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

/*
* Interceptor:
* */
public class MyInterceptor implements HandlerInterceptor {

    /** preHandle: The method of pre - request processing
     *
     * @param handler Intercepted controller object (MyController)
     * @return  Boolean value
     *      true: The request is correct and can be processed by the Controller. Output:
     *          preHandle()Method is executed
     *          The doSome method is implemented. Li Qing: 23
     *          postHandle()Method is executed
     *          afterCompletion()Method is executed
     *
     *      false: The request cannot be processed, the controller cannot be executed, and the request is terminated. Output:
     *          preHandle()Method is executed
     *
     *
     *
     * characteristic:
     *  1. Preprocessing method its execution time: it is executed before the controller method
     *  2. You can process requests, check login, judge permissions, statistics, etc
     *  3. Decide whether to execute the request
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle()Method is executed");
        return true;
    }

    /** postHandle : Post processing method
     *
     * @param handler Intercepted controller object (MyController)
     * @param modelAndView Return value of the controller (execution result of the request)
     *
     * characteristic:
     *   1. Its execution time: executed after the controller method
     *   2. The execution result of the controller method can be obtained and the original execution result can be modified
     *         You can modify data or view
     *   3. The request can be processed twice
     *
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle()Method is executed");

        // Second process the request
        if (modelAndView != null){
            // Modify data
            modelAndView.addObject("mydate",new Date());
            // Modify view
            modelAndView.setViewName("other");
        }
    }

    /** afterCompletion: Final execution method
     *
     * @param handler  Intercepted controller object (MyController)
     * @param ex Exception object
     *
     *   characteristic:
     *     1. Its execution time: it is executed after the request processing is completed
     *        The flag after the request processing is completed is that the view processing is completed, and after the forward operation is performed on the view
     *      2. You can do the last job of the program, free memory and clean up temporary variables
     *      3. Execution conditions of the method:
     *         (1) The current interceptor must execute its preHandle() method
     *         (2) preHandle Must return true
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion()Method is executed");

        // get data
        HttpSession httpSession = request.getSession();
        Object attr = httpSession.getAttribute("attr");
        System.out.println("attr="+attr);

        // Delete data
        httpSession.removeAttribute("attr");

        // Determine whether the data has been deleted
        attr = httpSession.getAttribute("attr");
        System.out.println("Check the data again : attr1 = "+attr);
    }
}

When your preHandle returns true, the execution result:

preHandle()Method is executed
 Yes doSome Methods Li Qing:23
postHandle()Method is executed
afterCompletion()Method is executed
attr=MyController A temporary data.
Check the data again : attr1 = null

When your preHandle returns false, the execution result:

preHandle()Method is executed

4.3.2 multiple interceptors

Two interceptors are used, mainly depending on the execution order of the interceptor and controlling the execution of the request according to one method

1) Two interceptors, the first preHandle=true and the second preHandle=true

MyInterceptor 11111 of preHandle()Method is executed
MyInterceptor 2222 of preHandle()Method is executed
 Yes doSome Methods Li Qing:23
MyInterceptor 2222 of postHandle()Method is executed
MyInterceptor 11111 of postHandle()Method is executed
MyInterceptor 2222 of afterCompletion()Method is executed
MyInterceptor 11111 of afterCompletion()Method is executed

Order of execution of requests:

User some.do - preHandle of interceptor 1 - interceptor 2preHandle - controller doSome - interceptor 2postHandle - postHandle of interceptor 1 - afterCompletion of interceptor 2 - afterCompletion of interceptor 1.

2) Two interceptors, the first preHandle=true and the second preHandle=false

MyInterceptor 11111 of preHandle()Method is executed
MyInterceptor 2222 of preHandle()Method is executed
MyInterceptor 11111 of afterCompletion()Method is executed

3) Two interceptors, the first preHandle=false and the second preHandle=true|false

MyInterceptor 11111 of preHandle()Method is executed

Why use multiple interceptors?

  1. Distribute the verification function to independent interceptors. Each interceptor performs a single verification process.
  2. Combine multiple interceptors.

Summary:

Multiple interceptors, strung on a chain. Multiple interceptors and a controller object are on a chain. The framework uses the handler execution chain to represent the execution chain

public class HandlerExecutionChain {
   
    private final Object handler;  // Where the controller object is stored, MyController
    @Nullable
    private HandlerInterceptor[] interceptors; // To store multiple interceptor objects. MyInterceptor 1, 2
    @Nullable
    private List<HandlerInterceptor> interceptorList;
}

How does the interceptor implement the execution order of 1,2 and 2,1, and traverse the HandlerInterceptor[] interceptors array

HandlerInterceptor[] interceptors = { MyInterceptor1, MyInterceptor2};
//Loop call method 1-2
for(int i=0;i<interceptors.length;i++){
      HandlerInterceptor  obj= interceptors[i];
      obj.preHandle();
}

MyController.doSome();

// 2-1
for(int i=interceptors.length-1 ;i>=0;i--){
      HandlerInterceptor obj= interceptors[i];
      obj.postHandle();
}

4.3.3 comparison of interceptors and filters

1) Interceptors are objects in the spring MVC framework. Filters are objects in servlet s.

2) The interceptor object is created by the framework container, and the filter object is created by tomcat.

  1. Interceptors focus on judging and processing requests, and can truncate requests. The filter focuses on setting values for the properties and parameters of request and response objects. For example, request.setCharacterEncoding("utf-8")

  2. There are three execution times of the interceptor, before the controller method, after the request is completed. The filter is before the request.

5) The interceptor intercepts requests for controller and dynamic resources. Filters can filter all requests, both dynamic and static.

6) Interceptors and filters are executed together. The first filter is executed, followed by the central scheduler, followed by interceptors, followed by controller methods

4.4 login permission interceptor

CH12 permission Interceptor: use the interceptor to authenticate the logged in user

Steps:
1. Create a new web application
2. Add web dependency
Spring webmvc dependency (spring MVC framework dependency), servlet dependency.

3. Declare the spring MVC core object DispatcherServlet
1) Dispatcher Servlet is a Servlet object.
2) The dispatcher servlet is called a front controller
3) Dispatcher servlet functions:
(1) . in the init () method of the servlet, create the container object in spring MVC.
WebApplicationContext ctx = new ClassPathXmlApplicationContext("appliationContext.xml")

(2) receive the request as a servlet.

4. Create a jsp and initiate a request with parameters name and age

5. Create a common class to be used as a controller (instead of the previous servlet)
1) Add the @ Controller annotation on the class
2) Define methods in a class

6. Create a jsp page as a result

7. Create login.jsp to simulate login and store an account in session.
Create logout.jsp to simulate exiting the system and delete the data in the session

8. Create a common class to implement HandlerInterceptor
In the preHandle() method, obtain the login account information and judge whether the account can access the system.
If you can access the system, preHandle returns true, and other cases return false

9. Create a jsp to display the processing results.

10. Create the spring MVC configuration file (the same as the spring configuration file)
1) Declare the component scanner and specify the package name where the @ Controller annotation is located
2) Declare view parser object
3) Declare the interceptor object and specify the uri address of the interceptor

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle()Method is executed");
        String username = "";
        // Get login account information
        Object attribute = request.getSession().getAttribute("username");
        if (attribute != null){
            username = (String) attribute;
        }
        // Determine whether the account number is correct
        if ("Zhang San".equals(username)){
            return true;
        }
        request.getRequestDispatcher("/tips.jsp").forward(request,response);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle()Method is executed");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion()Method is executed");
    }
}

Tags: Java Spring mvc

Posted on Wed, 15 Sep 2021 22:27:53 -0400 by pr0x