Spring MVC learning notes

1. SpringMVC

ssm: mybatis + Spring + spring MVC MVC three-tier architecture

JavaSE: study hard and get started quickly

JavaWeb: study hard, teachers lead, and get started quickly

SSM framework: study official documents, exercise self-study ability, exercise note taking ability and exercise project ability

 

SpringMVC + SpringBoot + SpringCloud + Linux

 

SSM=JavaWeb project:

 

Spring: IOC and AOP

 

Spring MVC: the execution process of spring MVC!

Spring MVC: SSM framework integration!

 

Spring

 

MVC: model (dao service), view (jsp), controller (servlet)

 

dao

service

servlet: receive the front-end data, hand over the data to the service layer, forward and redirect

jsp/html

 

Front end data transmission entity class

Entity class: user name, password, birthday, hobby... 20

Front end: user name, password

 

pojo: User

vo: UserVo

dto:

 

JSP: essentially a servlet

 

Hypothesis: is the architecture of your project designed or evolved. It must be said to be evolutionary

  • Alibaba PHP

  • With the increasing number of users, Java

  • Wang Jian goes to IOE MySQL

  • MySQL: MySQL--->ALISQL,ALIRedis

  • All in one -- > microservices

2. Review

  1. Injection dependency

    <!--rely on-->
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.3.6</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.2</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
        </dependencies>
  2. Building web Framework

    test.jsp

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

    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">
    ​
        <servlet>
            <servlet-name>hello</servlet-name>
            <servlet-class>com.dary.servlet.HelloServlet</servlet-class>
        </servlet>
    ​
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
    ​
    <!--    <session-config>-->
    <!--        <session-timeout>15</session-timeout>-->
    <!--    </session-config>-->
    ​
    <!--    <welcome-file-list>-->
    <!--        <welcome-file>index.jsp</welcome-file>-->
    <!--    </welcome-file-list>-->
    </web-app>

    from.xml

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    ​
    <form action="/hello" method="post">
        <input type="text" name="method">
        <input type="submit">
    </form>
    ​
    </body>
    </html>
  3. Create entity class

    public class HelloServlet extends HttpServlet {
    ​
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //1. Get front-end parameters
            String method = req.getParameter("method");
            if(method.equals("add")){
                req.getSession().setAttribute("msg","Yes add method");
            }
            if(method.equals("delete")){
                req.getSession().setAttribute("msg","Yes delete method");
            }
            //2. Call the business layer
             
            //3. View forwarding or redirection
            req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp);
        }
    ​
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }

3. Get to know spring MVC

advantage:

  • Lightweight and easy to learn

  • Efficient, request response based MVC framework

  • Good compatibility with Spring and seamless combination

  • Agreement is better than configuration

  • Powerful functions: restful, data validation, formatting, localization, theme, etc

  • Concise and flexible

Spring: a hodgepodge. We can register the bean s used in spring MVC with spring!

Spring's web framework is designed around dispatcher servlet. The purpose of dispatcher servlet is to distribute requests to different processors. Starting from Spring 2.5, users using Java 5 or above can adopt annotation based controller declaration.

Like many other MVC frameworks, the Spring MVC framework is request driven. It distributes requests and provides other functions around a central Servlet. The dispatcher Servlet is an actual Servlet (it inherits from the HttpServlet base class).

 

The principle of spring MVC is shown in the following figure:

When a request is initiated, the front controller intercepts the request, generates a proxy request according to the request parameters, finds the actual controller corresponding to the request, processes the request, creates a data model, accesses the database, and responds to the model to the central controller. The controller renders the view result using the model and view, and returns the result to the central controller, Then return the result to the requester.

 

2.3 implementation principle of spring MVC

Briefly analyze the execution process

 

  1. Dispatcher servlet represents the front controller and is the control center of the whole spring MVC. The user sends a request, and the dispatcher servlet receives the request and intercepts the request.

    We assume that the requested url is: http://localhost:8080/SpringMVC/hello

    As above, the url is divided into three parts:

    http://localhost:8080 Server domain name

    Spring MVC web site deployed on the server

    hello indicates the controller

    Through analysis, the above url is expressed as: request the hello controller of the spring MVC site located on the server localhost:8080.

  2. HandlerMapping is processor mapping. DispatcherServlet calls HandlerMapping, which looks up the Handler according to the request url.

  3. HandlerExecution refers to a specific Handler. Its main function is to find the controller according to the url. The controller found by the url above is: hello.

  4. HandlerExecution passes the parsed information to DispatcherServlet, such as parsing controller mapping.

  5. HandlerAdapter represents the processor adapter, which executes the Handler according to specific rules.

  6. The Handler lets the specific Controller execute.

  7. The Controller returns the specific execution information to the HandlerAdapter, such as ModelAndView.

  8. The HandlerAdapter passes the logical name or model of the view to the dispatcher servlet.

  9. DispatcherServlet calls the view resolver to resolve the logical view name passed by the HandlerAdapter.

  10. The view parser passes the parsed logical view name to the dispatcher servlet.

  11. DispatcherServlet calls the specific view according to the view result parsed by the view parser.

  12. The final view is presented to the user.

3.1 HelloSpringMVC

  1. Create a JSP package under the WEB-INF under the web, and create a new hello. Inf package under the package jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    ${msg}
    </body>
    </html>
  2. Make sure there are spring MVC dependencies and project constructor dependencies

  3. On the web DispatcherServlet is configured in XML, which is the core of spring MVC, request distributor and front-end controller

    <?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">
    ​
            <!--register DispatcherServlet-->
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--Associate a springmvc Your profile[ servlet-name]-servlet.xml-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
            <!--Startup level-1-->
            <load-on-startup>1</load-on-startup>
        </servlet>
            <!--    
            / :  Only match all requests, not match jsp page
            /* :  Match all requests, also match jsp page
            -->
    ​
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    ​
    </web-app>
  4. Write a configuration file, springmvc servlet xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">
    ​
         <!--Processor mapper-->
        <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
        <!--Processor adapter-->
        <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
    ​
        <!--View parser: DispatcherServlet Give it to him ModelAndView
        1.Got it ModelAndView Data
        2.analysis ModelAndView View name
        3.Splice the view name and find the corresponding view
        4.Render the data to this view
        -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
                <!--prefix-->
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <!--suffix-->
            <property name="suffix" value=".jsp"/>
        </bean>
    ​
        <bean id="/hello" class="com.dary.controller.HelloController"/>
    ​
    </beans>
  5. Create a package under java and a HelloController class under the package

    public class HelloController implements Controller {
        public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)throws Exception{
            //ModelAndView models and views
            ModelAndView mv = new ModelAndView();
    ​
            //Encapsulate objects in ModelAndView
            mv.addObject("msg","HelloSpringMVC");
            //Encapsulate the view to jump to and put it in ModelAndView
            mv.setViewName("hello");//:/WEB-INF/jsp/hello.jsp
            return mv;
        }
    }

3.2 developing spring MVC with annotations

  1. In POM XML injection Maven

<build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
        </resource>
    </resources>
</build>
  1. Configure 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">
    ​
        <!--1.register servlet-->
        <servlet>
            <servlet-name>SpringMVC</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!--Specified by initialization parameters SpringMVC The location of the configuration file is associated-->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc-servlet.xml</param-value>
            </init-param>
            <!-- Start sequence: the smaller the number, the earlier the start -->
            <load-on-startup>1</load-on-startup>
        </servlet>
    ​
        <!--All requests will be rejected springmvc intercept -->
        <servlet-mapping>
            <servlet-name>SpringMVC</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    ​
    </web-app>
  2. Configure spring servlet xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:context="http://www.springframework.org/schema/context"
          xmlns:mvc="http://www.springframework.org/schema/mvc"
          xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/mvc
           https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    ​
       <!-- Automatically scan the package to make the comments under the specified package effective,from IOC Unified container management -->
       <context:component-scan base-package="com.kuang.controller"/>
       <!-- Give Way Spring MVC Do not process static resources -->
       <mvc:default-servlet-handler />
       <!--
       support mvc Annotation driven
           stay spring Generally used in@RequestMapping Annotation to complete the mapping relationship
           To make@RequestMapping Note effective
           Must register with context DefaultAnnotationHandlerMapping
           And one AnnotationMethodHandlerAdapter example
           These two instances are handled at the class level and method level respectively.
           and annotation-driven Configuration helps us automatically complete the injection of the above two instances.
        -->
       <mvc:annotation-driven />
    ​
       <!-- view resolver  -->
       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
             id="internalResourceViewResolver">
           <!-- prefix -->
           <property name="prefix" value="/WEB-INF/jsp/" />
           <!-- suffix -->
           <property name="suffix" value=".jsp" />
       </bean>
    ​
    </beans>
  3. Write a controller

    @Controller
    @RequestMapping("/HelloController")
    public class HelloController {
    ​
        //Real access address: project name / HelloController/hello
        @RequestMapping("/hello")
        public String sayHello(Model model){
            //Add attributes msg and values to the model, which can be taken out and rendered in the JSP page
            model.addAttribute("msg","hello,SpringMVC");
            //web-inf/jsp/hello.jsp
            return "hello";
        }
    }

4. Controller and RestFul style

Controller controller

  • The complex controller provides the behavior of accessing the application program, which is usually realized by interface definition or annotation definition.

  • The controller is responsible for parsing the user's request and transforming it into a model.

  • In Spring MVC, a controller class can contain multiple methods

  • In Spring MVC, there are many ways to configure the Controller

     

Implement Controller interface

Controller is an interface, which is located at org springframework. web. servlet. Under MVC package, there is only one method in the interface;

//The class that implements the interface obtains the controller function
public interface Controller {
   //Process the request and return a model and view object
   ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponsevar2) throws Exception;
}

test

  1. Create a new Moudle, springmvc-04-controller

    • Delete HelloController

    • mvc's configuration file only leaves the view parser!

  2. <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/mvc
           https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    ​
    ​
    <!--    <context:component-scan base-package="com.dary.controller"/>-->
    <!--    <mvc:default-servlet-handler/>-->
    <!--    <mvc:annotation-driven/>-->
    ​
        <!-- view resolver  -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
              id="internalResourceViewResolver">
            <!-- prefix -->
            <property name="prefix" value="/WEB-INF/jsp/" />
            <!-- suffix -->
            <property name="suffix" value=".jsp" />
        </bean>
    ​
        <bean name="/t1" class="com.dary.controller.ControllerTest1"/>
    </beans>
  3. Write a Controller class, ControllerTest1

    //Define controller
    //Note: do not import the wrong package, implement the Controller interface and rewrite the method;
    public class ControllerTest1 implements Controller {
    ​
       public ModelAndView handleRequest(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception {
           //Returns a model view object
           ModelAndView mv = new ModelAndView();
           mv.addObject("msg","Test1Controller");
           mv.setViewName("test");
           return mv;
      }
    }
  4. After writing, register the requested bean in the Spring configuration file; name corresponds to the request path, and class corresponds to the class that handles the request

    <bean name="/t1" class="com.dary.controller.ControllerTest1"/>
  5. Write front-end test JSP. Note that it is written in the WEB-INF/jsp directory, which corresponds to our view parser

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
       <title>dary</title>
    </head>
    <body>
    ${msg}
    </body>
    </html>js

explain:

  • It is an old method to implement the interface Controller and define the Controller

  • Disadvantages: there is only one method in a Controller. If you want multiple methods, you need to define multiple controllers; The way of definition is troublesome;

Use annotation @ Controller

  • @The Controller annotation type is used to declare that the instance of Spring class is a Controller;

  • Spring can use the scanning mechanism to find all annotation based controller classes in the application. In order to ensure that spring can find your controller, you need to declare component scanning in the configuration file.

    <!-- Automatically scan the specified package and submit all the following annotation classes to IOC Container management -->
    <context:component-scan base-package="com.dary.controller"/>
  • Add a ControllerTest2 class and implement it with annotations;

    //@The class annotated by the Controller is automatically added to the Spring context
    @Controller
    public class ControllerTest2{
    ​
       //Map access path
       @RequestMapping("/t2")
       public String index(Model model){
           //Spring MVC will automatically instantiate a Model object to pass values to the view
           model.addAttribute("msg", "ControllerTest2");
           //Return to view location
           return "test";
      }
    ​
    }

It can be found that both of our requests can point to a view, but the results of the page results are different. From here, we can see that the view is reused, and there is a weak coupling relationship between the controller and the view.

Annotation is the most commonly used method!

RequestMapping

@RequestMapping

  • @The RequestMapping annotation is used to map URLs to a controller class or a specific handler method. Can be used on classes or methods. Used on a class, indicating that all methods in the class that respond to requests take this address as the parent path.

  • In order to test the conclusion more accurately, we can add a project name to test myweb

  • Only annotate on Methods

    @Controller
    public class TestController {
       @RequestMapping("/h1")
       public String test(){
           return "test";
      }
    }

    Access path: http://localhost:8088 /Project name / h1

  • Annotate classes and methods at the same time

    @Controller
    @RequestMapping("/admin")
    public class TestController {
       @RequestMapping("/h1")
       public String test(){
           return "test";
      }
    }

    Access path: http://localhost:8088 /Project name / admin /h1, you need to specify the path of the class first and then the path of the method;

 

RestFul style

concept

Restful is a style of resource positioning and resource operation. It's not a standard or agreement, it's just a style. The software designed based on this style can be more concise, more hierarchical, and easier to implement caching and other mechanisms.

function

Resources: all things on the Internet can be abstracted as resources

Resource operation: use POST, DELETE, PUT and GET to operate resources with different methods.

Add, delete, modify and query respectively.

Operate resources in traditional way: achieve different effects through different parameters! Single method, post and get

http://127.0.0.1/item/queryItem.action?id=1 Query, GET

http://127.0.0.1/item/saveItem.action New, POST

http://127.0.0.1/item/updateItem.action Update, POST

http://127.0.0.1/item/deleteItem.action?id=1 Delete, GET or POST

Using RESTful operation resources: different effects can be achieved through different request methods! As follows: the request address is the same, but the function can be different!

http://127.0.0.1/item/1 Query, GET

http://127.0.0.1/item New, POST

http://127.0.0.1/item Update, PUT

http://127.0.0.1/item/1 DELETE

Learning test

  1. Create a new class RestFulController

    @Controller
    public class RestFulController {
    }
  2. In Spring MVC, you can use the @ PathVariable annotation to bind the value of the method parameter to a URI template variable.

    @Controller
    public class RestFulController {
    ​
       //Map access path
       @RequestMapping("/commit/{p1}/{p2}")
       public String index(@PathVariable int p1, @PathVariable int p2, Model model){
           
           int result = p1+p2;
           //Spring MVC will automatically instantiate a Model object to pass values to the view
           model.addAttribute("msg", "result:"+result);
           //Return to view location
           return "test";
           
      }
       
    }
  3. advantage:

    • Make the path more concise;

    • It is more convenient to obtain parameters, and the framework will automatically carry out type conversion.

    • Access parameters can be constrained by the type of path variable. If the type is different, the corresponding request method cannot be accessed. For example, if the access path here is / commit/1/a, the path does not match the method, rather than parameter conversion failure.

    • More secure servers

  4. Let's modify the corresponding parameter type and test again

    //Map access path
    @RequestMapping("/commit/{p1}/{p2}")
    public String index(@PathVariable int p1, @PathVariable String p2, Model model){
    ​
       String result = p1+p2;
       //Spring MVC will automatically instantiate a Model object to pass values to the view
       model.addAttribute("msg", "result:"+result);
       //Return to view location
       return "test";
    ​
    }

Use the method property to specify the request type

It is used to restrict the type of request and narrow the request range. Specify the type of request predicate, such as GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE, etc

Let's test:

  • Add a method

    //The mapped access path must be a POST request
    @RequestMapping(value = "/hello",method = {RequestMethod.POST})
    public String index2(Model model){
       model.addAttribute("msg", "hello!");
       return "test";
    }
  • We use the browser address bar to access. By default, it is a Get request, and an error 405 will be reported:

  • If you change POST to GET, it is normal;

    //The mapped access path must be a Get request
    @RequestMapping(value = "/hello",method = {RequestMethod.GET})
    public String index2(Model model){
       model.addAttribute("msg", "hello!");
       return "test";
    }

Summary:

The @ RequestMapping annotation of Spring MVC can handle HTTP requests, such as GET, PUT, POST, DELETE and PATCH.

All address bar requests will be of HTTP GET type by default.

Method level annotation variants are as follows: combined annotation

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping

@GetMapping is a combined annotation, which is often used!

It acts as a shortcut to @ RequestMapping(method =RequestMethod.GET).

5. Redirection and forwarding

Result jump mode

ModelAndView

Set the ModelAndView object and jump to the specified page according to the name of the view and the view parser

Page: {view parser prefix} + viewName + {view parser suffix}

<!-- view resolver  -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
     id="internalResourceViewResolver">
   <!-- prefix -->
   <property name="prefix" value="/WEB-INF/jsp/" />
   <!-- suffix -->
   <property name="suffix" value=".jsp" />
</bean>

Corresponding controller class

public class ControllerTest1 implements Controller {
​
   public ModelAndView handleRequest(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception {
       //Returns a model view object
       ModelAndView mv = new ModelAndView();
       mv.addObject("msg","ControllerTest1");
       mv.setViewName("test");
       return mv;
  }
}

ServletAPI

By setting the servlet API, no view parser is required

1. Output through HttpServletResponse

2. Redirection via HttpServletResponse

3. Forward through HttpServletResponse

@Controller
public class ResultGo {
​
   @RequestMapping("/result/t1")
   public void test1(HttpServletRequest req, HttpServletResponse rsp) throwsIOException {
       rsp.getWriter().println("Hello,Spring BY servlet API");
  }
​
   @RequestMapping("/result/t2")
   public void test2(HttpServletRequest req, HttpServletResponse rsp) throwsIOException {
       rsp.sendRedirect("/index.jsp");//redirect
  }
​
   @RequestMapping("/result/t3")
   public void test3(HttpServletRequest req, HttpServletResponse rsp) throwsException {
       //forward
       req.setAttribute("msg","/result/t3");
       req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp);//forward
  }
​
}

 

SpringMVC

Realize forwarding and redirection through spring MVC - no view parser is required;

Before testing, you need to comment out the view parser

@Controller
public class ResultSpringMVC {
   @RequestMapping("/rsm/t1")
   public String test1(){
       //forward
       return "/index.jsp";
  }
​
   @RequestMapping("/rsm/t2")
   public String test2(){
       //Forwarding II
       return "forward:/index.jsp";
  }
​
   @RequestMapping("/rsm/t3")
   public String test3(){
       //redirect
       return "redirect:/index.jsp";
  }
}

 

Forward and redirect through spring MVC - view parser;

Redirection does not require a view parser. Its essence is to re request a new place, so pay attention to the path problem

You can redirect to another request implementation

@Controller
public class ResultSpringMVC2 {
   @RequestMapping("/rsm2/t1")
   public String test1(){
       //forward
       return "test";
  }
​
   @RequestMapping("/rsm2/t2")
   public String test2(){
       //redirect
       return "redirect:/index.jsp";
       //return "redirect:hello.do"; //hello.do for another request/
  }
​
}

data processing

Process submitted data

1. The submitted domain name is consistent with the parameter name of the processing method

Submit data: http://localhost:8088/hello?name=dary

Treatment method:

@RequestMapping("/hello")
public String hello(String name){
   System.out.println(name);
   return "hello";
}

Background output: dary

2. The submitted domain name is inconsistent with the parameter name of the processing method

Submit data: http://localhost:8088/hello?username=dary

Treatment method:

//@Requestparam ("username"): the name of the domain submitted by username
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
   System.out.println(name);
   return "hello";
}

Background output: dary

3. Submitted is an object

It is required that the submitted form field and the attribute name of the object are consistent, and the parameter can use the object

1. Entity class

public class User {
   private int id;
   private String name;
   private int age;
   //structure
   //get/set
   //tostring()
}

2. Submit data: http://localhost:8088/mvc04/user?name=dary&id=1&age=15

3. Treatment method:

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

Background output: user {id = 1, name ='dary ', age = 15}

Note: if an object is used, the parameter name passed by the front end must be consistent with the object name, otherwise it is null.

Data display to front end

First: through ModelAndView

This has always been the case before us Just explain more

public class ControllerTest1 implements Controller {
​
   public ModelAndView handleRequest(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception {
       //Returns a model view object
       ModelAndView mv = new ModelAndView();
       mv.addObject("msg","ControllerTest1");
       mv.setViewName("test");
       return mv;
  }
}

 

Second: through ModelMap

ModelMap

@RequestMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap model){
   //Encapsulates the data to be displayed in the view
   //Equivalent to req setAttribute("name",name);
   model.addAttribute("name",name);
   System.out.println(name);
   return "hello";
}

 

Third: through Model

Model

@RequestMapping("/ct2/hello")
public String hello(@RequestParam("username") String name, Model model){
   //Encapsulates the data to be displayed in the view
   //Equivalent to req setAttribute("name",name);
   model.addAttribute("msg",name);
   System.out.println(name);
   return "test";
}

 

contrast

For novices, the simple difference is:

Model There are only a few methods that are only suitable for storing data, simplifying novices' understanding of Model Operation and understanding of objects;
​
ModelMap Inherited LinkedMap ,In addition to implementing some of its own methods, the same inheritance LinkedMap Methods and characteristics of;
​
ModelAndView While storing data, you can set the returned logical view and control the jump of the display layer.

Of course, more future development is more about performance and optimization, so it can't be limited to this understanding.

Please use 80% of the time to lay a solid foundation, and the remaining 18% of the time to study the framework and 2% of the time to learn some English. The official document of the framework is always the best tutorial.

 

Garbled code problem

Test steps:

1. We can write a submission form on the home page

<form action="/e/t" method="post">
 <input type="text" name="name">
 <input type="submit">
</form>

2. Write the corresponding processing class in the background

@Controller
public class Encoding {
   @RequestMapping("/e/t")
   public String test(Model model,String name){
       model.addAttribute("msg",name); //Get the value of the form submission
       return "test"; //Jump to the test page and display the entered value
  }
}

3. Input Chinese test, found garbled code

It has to be said that the problem of garbled code is a very common problem in our development, and it is also a big problem for our program ape!

In the past, the problem of garbled code was solved through filters, and spring MVC provided us with a filter, which can be found on the web Configuration in XML

The xml file has been modified. You need to restart the server!

<filter>
   <filter-name>encoding</filter-name>
   <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
   <init-param>
       <param-name>encoding</param-name>
       <param-value>utf-8</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>encoding</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

But we found that in some extreme cases This filter does not support get well

Treatment method:

1. Modify tomcat configuration file: set code!

<Connector URIEncoding="utf-8" port="8080" protocol="HTTP/1.1"
          connectionTimeout="20000"
          redirectPort="8443" />

2. Custom filter

package com.dary.filter;
​
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
​
/**
* Filter to solve all the garbled codes of get and post requests
*/
public class GenericEncodingFilter implements Filter {
​
   @Override
   public void destroy() {
  }
​
   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChainchain) throws IOException, ServletException {
       //Handle the character encoding of the response
       HttpServletResponse myResponse=(HttpServletResponse) response;
       myResponse.setContentType("text/html;charset=UTF-8");
​
       // Transformation into agreement related objects
       HttpServletRequest httpServletRequest = (HttpServletRequest) request;
       // Enhanced request packaging
       HttpServletRequest myrequest = new MyRequest(httpServletRequest);
       chain.doFilter(myrequest, response);
  }
​
   @Override
   public void init(FilterConfig filterConfig) throws ServletException {
  }
​
}
​
//Custom request object, wrapper class of HttpServletRequest
class MyRequest extends HttpServletRequestWrapper {
​
   private HttpServletRequest request;
   //Coded flag
   private boolean hasEncode;
   //Define a constructor that can be passed into the HttpServletRequest object to decorate it
   public MyRequest(HttpServletRequest request) {
       super(request);// super must write
       this.request = request;
  }
​
   // Override methods that need to be enhanced
   @Override
   public Map getParameterMap() {
       // Request first
       String method = request.getMethod();
       if (method.equalsIgnoreCase("post")) {
           // post request
           try {
               // Handle post garbled code
               request.setCharacterEncoding("utf-8");
               return request.getParameterMap();
          } catch (UnsupportedEncodingException e) {
               e.printStackTrace();
          }
      } else if (method.equalsIgnoreCase("get")) {
           // get request
           Map<String, String[]> parameterMap = request.getParameterMap();
           if (!hasEncode) { // Make sure that the get manual encoding logic runs only once
               for (String parameterName : parameterMap.keySet()) {
                   String[] values = parameterMap.get(parameterName);
                   if (values != null) {
                       for (int i = 0; i < values.length; i++) {
                           try {
                               // Handle get garbled code
                               values[i] = new String(values[i]
                                      .getBytes("ISO-8859-1"), "utf-8");
                          } catch (UnsupportedEncodingException e) {
                               e.printStackTrace();
                          }
                      }
                  }
              }
               hasEncode = true;
          }
           return parameterMap;
      }
       return super.getParameterMap();
  }
​
   //Take a value
   @Override
   public String getParameter(String name) {
       Map<String, String[]> parameterMap = getParameterMap();
       String[] values = parameterMap.get(name);
       if (values == null) {
           return null;
      }
       return values[0]; // Retrieve the first value of the parameter
  }
​
   //Take all values
   @Override
   public String[] getParameterValues(String name) {
       Map<String, String[]> parameterMap = getParameterMap();
       String[] values = parameterMap.get(name);
       return values;
  }
}

6. JSON

What is JSON?

  • JSON (JavaScript object notation) is a lightweight data exchange format, which is widely used at present.

  • Data is stored and represented in a text format completely independent of the programming language.

  • The concise and clear hierarchy makes JSON an ideal data exchange language.

  • It is easy for people to read and write, but also easy for machine analysis and generation, and effectively improves the network transmission efficiency.

In the JavaScript language, everything is an object. Therefore, any type supported by JavaScript can be represented by JSON, such as string, number, object, array, etc. Look at his requirements and grammatical format:

  • Objects are represented as key value pairs, and data is separated by commas

  • Curly braces save objects

  • Square brackets hold the array

JSON key value pair is a way to save JavaScript objects, which is also similar to the writing method of JavaScript objects. The key name in the key / value pair combination is written in front and wrapped in double quotation marks "", separated by colon: and then followed by the value:

{"name": "QinJiang"}
{"age": "3"}
{"sex": "male"}

Many people don't know the relationship between JSON and JavaScript objects, or even who they are. In fact, it can be understood as follows:

JSON is a string representation of JavaScript objects. It uses text to represent the information of a JS object, which is essentially a string.

var obj = {a: 'Hello', b: 'World'}; //This is an object. Note that the key name can also be wrapped in quotation marks
var json = '{"a": "Hello", "b": "World"}'; //This is a JSON string, which is essentially a string

JSON and JavaScript objects interoperate

To convert from a JSON string to a JavaScript object, use JSON Parse() method:

var obj = JSON.parse('{"a": "Hello", "b": "World"}');
//The result is {a: 'Hello', b: 'World'}

To convert from a JavaScript object to a JSON string, use JSON Stringify() method:

var json = JSON.stringify({a: 'Hello', b: 'World'});
//The result is' {"a": "Hello", "b": "World"} '

Code test

1. Create a new module, spring mvc-05-json, and add web support

2. Create a new jsontest in the web directory HTML, write test content

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>JSON_Qin Jiang</title>
</head>
<body>
​
<script type="text/javascript">
   //Write a js object
   var user = {
       name:"Qin Jiang",
       age:3,
       sex:"male"
  };
   //Convert js object to json string
   var str = JSON.stringify(user);
   console.log(str);
   
   //Convert json string to js object
   var user2 = JSON.parse(str);
   console.log(user2.age,user2.name,user2.sex);
​
</script>
​
</body>
</html>

JSON data returned by Controller

Jackson should be a better json parsing tool at present

Of course, there are more than one tool, such as Alibaba's fastjson and so on.

We use Jackson here. To use it, we need to import its jar package;

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.9.8</version>
</dependency>

Configuration required to configure spring MVC

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">
​
   <!--1.register servlet-->
   <servlet>
       <servlet-name>SpringMVC</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <!--Specified by initialization parameters SpringMVC The location of the configuration file is associated-->
       <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:springmvc-servlet.xml</param-value>
       </init-param>
       <!-- Start sequence: the smaller the number, the earlier the start -->
       <load-on-startup>1</load-on-startup>
   </servlet>
​
   <!--All requests will be rejected springmvc intercept -->
   <servlet-mapping>
       <servlet-name>SpringMVC</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>
​
   <filter>
       <filter-name>encoding</filter-name>
       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
       <init-param>
           <param-name>encoding</param-name>
           <param-value>utf-8</param-value>
       </init-param>
   </filter>
   <filter-mapping>
       <filter-name>encoding</filter-name>
       <url-pattern>/</url-pattern>
   </filter-mapping>
​
</web-app>

springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:mvc="http://www.springframework.org/schema/mvc"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">
​
   <!-- Automatically scan the specified package and submit all the following annotation classes to IOC Container management -->
   <context:component-scan base-package="com.kuang.controller"/>
​
   <!-- view resolver  -->
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
         id="internalResourceViewResolver">
       <!-- prefix -->
       <property name="prefix" value="/WEB-INF/jsp/" />
       <!-- suffix -->
       <property name="suffix" value=".jsp" />
   </bean>
​
</beans>

We randomly write an entity class of User, and then we write our test Controller;

package com.dary.pojo;
​
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
​
//Need to import lombok
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
​
   private String name;
   private int age;
   private String sex;
   
}

Here we need two new things, one is @ ResponseBody and the other is ObjectMapper object. Let's see the specific usage

Write a Controller;

@Controller
public class UserController {
​
   @RequestMapping("/json1")
   @ResponseBody
   public String json1() throws JsonProcessingException {
       //Create an object mapper of jackson to parse the data
       ObjectMapper mapper = new ObjectMapper();
       //Create an object
       User user = new User("dary", 3, "male");
       //Parse our object into json format
       String str = mapper.writeValueAsString(user);
       //Due to the @ ResponseBody annotation, str will be converted into json format and returned here; Very convenient
       return str;
  }
​
}

Configure Tomcat and start the test!

http://localhost:8088/json1

It is found that there is a garbled code problem. We need to set its encoding format to utf-8 and its return type;

Through the @ requestmapping products attribute, modify the following code

//produces: Specifies the return type and encoding of the response body
@RequestMapping(value = "/json1",produces = "application/json;charset=utf-8")

Test again, http://localhost:8088/json1 , garbled code problem OK!

[Note: remember to deal with garbled code when using json]

Code optimization

Unified solution of garbled code

The previous method is more troublesome. If there are many requests in the project, each one should be added, which can be specified uniformly through Spring configuration, so you don't have to deal with them every time!

We can add a message StringHttpMessageConverter conversion configuration to the configuration file of spring MVC!

<mvc:annotation-driven>
   <mvc:message-converters register-defaults="true">
       <beanclass="org.springframework.http.converter.StringHttpMessageConverter">
           <constructor-arg value="UTF-8"/>
       </bean>
       <beanclass="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
           <property name="objectMapper">
               <beanclass="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                   <property name="failOnEmptyBeans" value="false"/>
               </bean>
           </property>
       </bean>
   </mvc:message-converters>
</mvc:annotation-driven>

 

Unified solution for returning json strings

Use @ RestController directly on the class. In this way, all the methods inside will only return json strings. There is no need to add @ ResponseBody to each one! We generally use @ RestController in front and back-end separation development, which is very convenient!

@RestController
public class UserController {
​
   //produces: Specifies the return type and encoding of the response body
   @RequestMapping(value = "/json1")
   public String json1() throws JsonProcessingException {
       //Create an object mapper of jackson to parse the data
       ObjectMapper mapper = new ObjectMapper();
       //Create an object
       User user = new User("Qinjiang 1", 3, "male");
       //Parse our object into json format
       String str = mapper.writeValueAsString(user);
       //Due to the @ ResponseBody annotation, str will be converted into json format and returned here; Very convenient
       return str;
  }
​
}

Start the tomcat test, and the results are output normally!

 

Test set output

Add a new method

@RequestMapping("/json2")
public String json2() throws JsonProcessingException {
​
   //Create an object mapper of jackson to parse the data
   ObjectMapper mapper = new ObjectMapper();
   //Create an object
   User user1 = new User("Qinjiang 1", 3, "male");
   User user2 = new User("Qinjiang 2", 3, "male");
   User user3 = new User("Qinjiang 3", 3, "male");
   User user4 = new User("Qinjiang 4", 3, "male");
   List<User> list = new ArrayList<User>();
   list.add(user1);
   list.add(user2);
   list.add(user3);
   list.add(user4);
​
   //Parse our object into json format
   String str = mapper.writeValueAsString(list);
   return str;
}

Running result: perfect, no problem!

Output time object

Add a new method

@RequestMapping("/json3")
public String json3() throws JsonProcessingException {
​
   ObjectMapper mapper = new ObjectMapper();
​
   //Create a time object, Java util. Date
   Date date = new Date();
   //Parse our object into json format
   String str = mapper.writeValueAsString(date);
   return str;
}
  • The default date format will become a number, which is the number of milliseconds from January 1, 1970 to the current date!

  • Jackson will convert the time into timestamps by default

Solution: cancel the timestamps form and customize the time format

@RequestMapping("/json4")
public String json4() throws JsonProcessingException {
​
   ObjectMapper mapper = new ObjectMapper();
​
   //Without timestamp
   mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
   //Custom date format object
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   //Specify date format
   mapper.setDateFormat(sdf);
​
   Date date = new Date();
   String str = mapper.writeValueAsString(date);
​
   return str;
}

Extract as tool class

If you want to use it frequently, it is troublesome. We can encapsulate these codes into a tool class; Let's write it

package com.dary.utils;
​
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
​
import java.text.SimpleDateFormat;
​
public class JsonUtils {
   
   public static String getJson(Object object) {
       return getJson(object,"yyyy-MM-dd HH:mm:ss");
  }
​
   public static String getJson(Object object,String dateFormat) {
       ObjectMapper mapper = new ObjectMapper();
       //Do not use time difference
       mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
       //Custom date format object
       SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
       //Specify date format
       mapper.setDateFormat(sdf);
       try {
           return mapper.writeValueAsString(object);
      } catch (JsonProcessingException e) {
           e.printStackTrace();
      }
       return null;
  }
}

When we use tool classes, the code is more concise!

@RequestMapping("/json5")
public String json5() throws JsonProcessingException {
   Date date = new Date();
   String json = JsonUtils.getJson(date);
   return json;
}

be accomplished! Perfect!

FastJson

fastjson.jar is a package specially developed by Ali for Java development. It can easily realize the conversion between json object and JavaBean object, between JavaBean object and json string, and between json object and json string. There are many conversion methods to realize json, and the final implementation results are the same.

fastjson's pom dependency!

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.60</version>
</dependency>

fastjson has three main classes:

JSONObject represents a json object

  • JSONObject implements the Map interface. I guess the underlying operation of JSONObject is implemented by Map.

  • JSONObject corresponds to the json object. You can obtain the data in the json object through various forms of get() methods. You can also use methods such as size(), isEmpty() to obtain the number of "key: value" pairs and judge whether they are empty. Its essence is accomplished by implementing the Map interface and calling the methods in the interface.

JSONArray represents an array of json objects

  • Internally, there are methods in the List interface to complete the operation.

JSON represents the conversion of JSONObject and JSONArray

  • Analysis and use of JSON class source code

  • Carefully observe these methods, mainly to realize the mutual transformation between json objects, json object arrays, javabean objects and json strings.

 

For code testing, we create a new FastJsonDemo class

package com.dary.controller;
​
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kuang.pojo.User;
​
import java.util.ArrayList;
import java.util.List;
​
public class FastJsonDemo {
   public static void main(String[] args) {
       //Create an object
       User user1 = new User("dary1 number", 3, "male");
       User user2 = new User("dary2 number", 3, "male");
       User user3 = new User("dary3 number", 3, "male");
       User user4 = new User("dary4 number", 3, "male");
       List<User> list = new ArrayList<User>();
       list.add(user1);
       list.add(user2);
       list.add(user3);
       list.add(user4);
​
       System.out.println("*******Java Object transfer JSON character string*******");
       String str1 = JSON.toJSONString(list);
       System.out.println("JSON.toJSONString(list)==>"+str1);
       String str2 = JSON.toJSONString(user1);
       System.out.println("JSON.toJSONString(user1)==>"+str2);
​
       System.out.println("\n****** JSON String conversion Java object*******");
       User jp_user1=JSON.parseObject(str2,User.class);
       System.out.println("JSON.parseObject(str2,User.class)==>"+jp_user1);
​
       System.out.println("\n****** Java Object transfer JSON object ******");
       JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
       System.out.println("(JSONObject) JSON.toJSON(user2)==>"+jsonObject1.getString("name"));
​
       System.out.println("\n****** JSON Object transfer Java object ******");
       User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
       System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+to_java_user);
  }
}

We only need to master the use of this tool class. When using it, we need to find the corresponding implementation according to the specific business. Like the previous commons IO toolkit, just use it!

7. Integrate SSM

Database environment

Create a database table for storing book data

CREATE DATABASE `ssmbuild`;
​
USE `ssmbuild`;
​
DROP TABLE IF EXISTS `books`;
​
CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT 'book id',
`bookName` VARCHAR(100) NOT NULL COMMENT 'title',
`bookCounts` INT(11) NOT NULL COMMENT 'quantity',
`detail` VARCHAR(200) NOT NULL COMMENT 'describe',
KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
​
INSERT  INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES 
(1,'Java',1,'From getting started to giving up'),
(2,'MySQL',10,'From deleting the library to running away'),
(3,'Linux',5,'From entering the door to entering the prison');

 

Basic environment construction

1. Create a new Maven project! ssmbuild, add web support

2. Import related pom dependencies!

<dependencies>
   <!--Junit-->
   <dependency>
       <groupId>junit</groupId>
       <artifactId>junit</artifactId>
       <version>4.12</version>
   </dependency>
   <!--Database driven-->
   <dependency>
       <groupId>mysql</groupId>
       <artifactId>mysql-connector-java</artifactId>
       <version>5.1.47</version>
   </dependency>
   <!-- Database connection pool -->
   <dependency>
       <groupId>com.mchange</groupId>
       <artifactId>c3p0</artifactId>
       <version>0.9.5.2</version>
   </dependency>
​
   <!--Servlet - JSP -->
   <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>servlet-api</artifactId>
       <version>2.5</version>
   </dependency>
   <dependency>
       <groupId>javax.servlet.jsp</groupId>
       <artifactId>jsp-api</artifactId>
       <version>2.2</version>
   </dependency>
   <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>jstl</artifactId>
       <version>1.2</version>
   </dependency>
​
   <!--Mybatis-->
   <dependency>
       <groupId>org.mybatis</groupId>
       <artifactId>mybatis</artifactId>
       <version>3.5.2</version>
   </dependency>
   <dependency>
       <groupId>org.mybatis</groupId>
       <artifactId>mybatis-spring</artifactId>
       <version>2.0.2</version>
   </dependency>
​
   <!--Spring-->
   <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-webmvc</artifactId>
       <version>5.1.9.RELEASE</version>
   </dependency>
   <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-jdbc</artifactId>
       <version>5.1.9.RELEASE</version>
   </dependency>
</dependencies>

3. Maven resource filtering settings

<build>
   <resources>
       <resource>
           <directory>src/main/java</directory>
           <includes>
               <include>**/*.properties</include>
               <include>**/*.xml</include>
           </includes>
           <filtering>false</filtering>
       </resource>
       <resource>
           <directory>src/main/resources</directory>
           <includes>
               <include>**/*.properties</include>
               <include>**/*.xml</include>
           </includes>
           <filtering>false</filtering>
       </resource>
   </resources>
</build>

4. Establish the basic structure and configuration framework!

  • com.dary.pojo

  • com.dary.dao

  • com.dary.service

  • com.dary.controller

  • mybatis-config.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
           PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
           "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    ​
    </configuration>
  • applicationContext.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    ​
    </beans>

 

Written by Mybatis layer

1. Database configuration file database properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

2. IDEA associated database

3. Write the core configuration file of MyBatis

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
       PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
   
   <typeAliases>
       <package name="com.kuang.pojo"/>
   </typeAliases>
   <mappers>
       <mapper resource="com/kuang/dao/BookMapper.xml"/>
   </mappers>
​
</configuration>

4. Write the entity class corresponding to the database com kuang. pojo. Books

Use the lombok plug-in!

package com.dary.pojo;
​
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
​
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
   
   private int bookID;
   private String bookName;
   private int bookCounts;
   private String detail;
   
}

5. Write Mapper interface of Dao layer!

package com.dary.dao;
​
import com.dary.pojo.Books;
import java.util.List;
​
public interface BookMapper {
​
   //Add a Book
   int addBook(Books book);
​
   //Delete a Book by id
   int deleteBookById(int id);
​
   //Update Book
   int updateBook(Books books);
​
   //According to the id query, a Book is returned
   Books queryBookById(int id);
​
   //Query all books and return the list set
   List<Books> queryAllBook();
​
}

6. Write mapper corresponding to the interface XML file. The package of MyBatis needs to be imported;

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
       PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
​
<mapper namespace="com.kuang.dao.BookMapper">
​
   <!--Add one Book-->
   <insert id="addBook" parameterType="Books">
      insert into ssmbuild.books(bookName,bookCounts,detail)
      values (#{bookName}, #{bookCounts}, #{detail})
   </insert>
​
   <!--according to id Delete one Book-->
   <delete id="deleteBookById" parameterType="int">
      delete from ssmbuild.books where bookID=#{bookID}
   </delete>
​
   <!--to update Book-->
   <update id="updateBook" parameterType="Books">
      update ssmbuild.books
      set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
      where bookID = #{bookID}
   </update>
​
   <!--according to id query,Return a Book-->
   <select id="queryBookById" resultType="Books">
      select * from ssmbuild.books
      where bookID = #{bookID}
   </select>
​
   <!--Query all Book-->
   <select id="queryAllBook" resultType="Books">
      SELECT * from ssmbuild.books
   </select>
​
</mapper>

7. Write the interface and implementation class of Service layer

Interface:

package com.dary.service;
​
import com.dary.pojo.Books;
​
import java.util.List;
​
//BookService: it needs to be implemented at the bottom and call the dao layer
public interface BookService {
   //Add a Book
   int addBook(Books book);
   //Delete a Book by id
   int deleteBookById(int id);
   //Update Book
   int updateBook(Books books);
   //According to the id query, a Book is returned
   Books queryBookById(int id);
   //Query all books and return the list set
   List<Books> queryAllBook();
}

Implementation class:

package com.dary.service;
​
import com.dary.dao.BookMapper;
import com.dary.pojo.Books;
import java.util.List;
​
public class BookServiceImpl implements BookService {
​
   //Call the operation of dao layer and set a set interface to facilitate Spring management
   private BookMapper bookMapper;
​
   public void setBookMapper(BookMapper bookMapper) {
       this.bookMapper = bookMapper;
  }
   
   public int addBook(Books book) {
       return bookMapper.addBook(book);
  }
   
   public int deleteBookById(int id) {
       return bookMapper.deleteBookById(id);
  }
   
   public int updateBook(Books books) {
       return bookMapper.updateBook(books);
  }
   
   public Books queryBookById(int id) {
       return bookMapper.queryBookById(id);
  }
   
   public List<Books> queryAllBook() {
       return bookMapper.queryAllBook();
  }
}

OK, now, the bottom requirement operation is written!

 

Spring layer

1. Configure Spring to integrate MyBatis. Here, the data source uses c3p0 connection pool;

2. Let's write the configuration files related to the integration of Mybatis with Spring; spring-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">
​
   <!-- Configuration integration mybatis -->
   <!-- 1.Associated database file -->
   <context:property-placeholder location="classpath:database.properties"/>
​
   <!-- 2.Database connection pool -->
   <!--Database connection pool
       dbcp Semi automatic operation cannot be connected automatically
       c3p0 Automatic operation (automatically load the configuration file and set it into the object)
   -->
   <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
       <!-- Configure connection pool properties -->
       <property name="driverClass" value="${jdbc.driver}"/>
       <property name="jdbcUrl" value="${jdbc.url}"/>
       <property name="user" value="${jdbc.username}"/>
       <property name="password" value="${jdbc.password}"/>
​
       <!-- c3p0 Private properties of connection pool -->
       <property name="maxPoolSize" value="30"/>
       <property name="minPoolSize" value="10"/>
       <!-- Not automatically after closing the connection commit -->
       <property name="autoCommitOnClose" value="false"/>
       <!-- Get connection timeout -->
       <property name="checkoutTimeout" value="10000"/>
       <!-- Number of retries when getting connection failed -->
       <property name="acquireRetryAttempts" value="2"/>
   </bean>
​
   <!-- 3.to configure SqlSessionFactory object -->
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
       <!-- Inject database connection pool -->
       <property name="dataSource" ref="dataSource"/>
       <!-- to configure MyBaties Global profile:mybatis-config.xml -->
       <property name="configLocation" value="classpath:mybatis-config.xml"/>
   </bean>
​
   <!-- 4.Configure scan Dao Interface package, dynamic implementation Dao Interface injection into spring In container -->
   <!--Explanation: https://www.cnblogs.com/jpfss/p/7799806.html-->
   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <!-- injection sqlSessionFactory -->
       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
       <!-- Given the need to scan Dao Interface package -->
       <property name="basePackage" value="com.dary.dao"/>
   </bean>
​
</beans>

3. Spring integration service layer

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd">
​
   <!-- scanning service dependent bean -->
   <context:component-scan base-package="com.dary.service" />
​
   <!--BookServiceImpl Inject into IOC In container-->
   <bean id="BookServiceImpl" class="com.dary.service.BookServiceImpl">
       <property name="bookMapper" ref="bookMapper"/>
   </bean>
​
   <!-- Configure transaction manager -->
   <bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       <!-- Inject database connection pool -->
       <property name="dataSource" ref="dataSource" />
   </bean>
​
</beans>

Spring layer is done! Once again, spring is a hodgepodge, a container! Right!

 

Spring MVC layer

1,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">
​
   <!--DispatcherServlet-->
   <servlet>
       <servlet-name>DispatcherServlet</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <init-param>
           <param-name>contextConfigLocation</param-name>
           <!--Be careful:What we load here is the total configuration file, which was damaged here before!-->  
           <param-value>classpath:applicationContext.xml</param-value>
       </init-param>
       <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
       <servlet-name>DispatcherServlet</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>
​
   <!--encodingFilter-->
   <filter>
       <filter-name>encodingFilter</filter-name>
       <filter-class>
          org.springframework.web.filter.CharacterEncodingFilter
       </filter-class>
       <init-param>
           <param-name>encoding</param-name>
           <param-value>utf-8</param-value>
       </init-param>
   </filter>
   <filter-mapping>
       <filter-name>encodingFilter</filter-name>
       <url-pattern>/*</url-pattern>
   </filter-mapping>
   
   <!--Session Expiration time-->
   <session-config>
       <session-timeout>15</session-timeout>
   </session-config>
   
</web-app>

2,spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/mvc
   https://www.springframework.org/schema/mvc/spring-mvc.xsd">
​
    <!-- to configure SpringMVC -->
    <!-- 1.open SpringMVC Annotation driven -->
    <mvc:annotation-driven />
    <!-- 2.Static resource default servlet to configure-->
    <mvc:default-servlet-handler/>
    <context:component-scan base-package="com.dary.controller" />
    <!-- 3.to configure jsp display ViewResolver view resolver  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass"value="org.springframework.web.servlet.view.JstlView"/>
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>
​
        <!-- 4.scanning web dependent bean -->
    
​
</beans>

3. Spring configuration integration file, ApplicationContext xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
​
   <import resource="spring-dao.xml"/>
   <import resource="spring-service.xml"/>
   <import resource="spring-mvc.xml"/>
   
</beans>

Configuration file, end temporarily! Controller and view layer writing

1. BookController class, method 1: query all books

@Controller
@RequestMapping("/book")
public class BookController {
​
   @Autowired
   @Qualifier("BookServiceImpl")
   private BookService bookService;
​
   @RequestMapping("/allBook")
   public String list(Model model) {
       List<Books> list = bookService.queryAllBook();
       model.addAttribute("list", list);
       return "allBook";
  }
}

2. Write home page index jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML>
<html>
<head>
   <title>home page</title>
   <style type="text/css">
       a {
           text-decoration: none;
           color: black;
           font-size: 18px;
      }
       h3 {
           width: 180px;
           height: 38px;
           margin: 100px auto;
           text-align: center;
           line-height: 38px;
           background: deepskyblue;
           border-radius: 4px;
      }
   </style>
</head>
<body>
​
<h3>
   <a href="${pageContext.request.contextPath}/book/allBook">Click to enter the list page</a>
</h3>
</body>
</html>

3. Book list page allbook jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>List of books</title>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <!-- introduce Bootstrap -->
   <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"rel="stylesheet">
</head>
<body>
​
<div class="container">
​
   <div class="row clearfix">
       <div class="col-md-12 column">
           <div class="page-header">
               <h1>
                   <small>Book list - displays all books</small>
               </h1>
           </div>
       </div>
   </div>
​
   <div class="row">
       <div class="col-md-4 column">
           <a class="btn btn-primary"href="${pageContext.request.contextPath}/book/toAddBook">newly added</a>
       </div>
   </div>
​
   <div class="row clearfix">
       <div class="col-md-12 column">
           <table class="table table-hover table-striped">
               <thead>
               <tr>
                   <th>Book number</th>
                   <th>Book name</th>
                   <th>Number of books</th>
                   <th>Book details</th>
                   <th>operation</th>
               </tr>
               </thead>
​
               <tbody>
               <c:forEach var="book" items="${requestScope.get('list')}">
                   <tr>
                       <td>${book.getBookID()}</td>
                       <td>${book.getBookName()}</td>
                       <td>${book.getBookCounts()}</td>
                       <td>${book.getDetail()}</td>
                       <td>
                           <ahref="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">change</a> |
                           <ahref="${pageContext.request.contextPath}/book/del/${book.getBookID()}">delete</a>
                       </td>
                   </tr>
               </c:forEach>
               </tbody>
           </table>
       </div>
   </div>
</div>

4. BookController class, method 2: add books

@RequestMapping("/toAddBook")
public String toAddPaper() {
   return "addBook";
}
​
@RequestMapping("/addBook")
public String addPaper(Books books) {
   System.out.println(books);
   bookService.addBook(books);
   return "redirect:/book/allBook";
}

5. Add book page: addbook jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
​
<html>
<head>
   <title>New books</title>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <!-- introduce Bootstrap -->
   <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"rel="stylesheet">
</head>
<body>
<div class="container">
​
   <div class="row clearfix">
       <div class="col-md-12 column">
           <div class="page-header">
               <h1>
                   <small>New books</small>
               </h1>
           </div>
       </div>
   </div>
   <form action="${pageContext.request.contextPath}/book/addBook"method="post">
      Book Name:<input type="text" name="bookName"><br><br><br>
      Number of books:<input type="text" name="bookCounts"><br><br><br>
      Book details:<input type="text" name="detail"><br><br><br>
       <input type="submit" value="add to">
   </form>
​
</div>

6. BookController class, method 3: modify books

@RequestMapping("/toUpdateBook")
public String toUpdateBook(Model model, int id) {
   Books books = bookService.queryBookById(id);
   System.out.println(books);
   model.addAttribute("book",books );
   return "updateBook";
}
​
@RequestMapping("/updateBook")
public String updateBook(Model model, Books book) {
   System.out.println(book);
   bookService.updateBook(book);
   Books books = bookService.queryBookById(book.getBookID());
   model.addAttribute("books", books);
   return "redirect:/book/allBook";
}

7. Modify the book page updatebook jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Modify information</title>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <!-- introduce Bootstrap -->
   <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"rel="stylesheet">
</head>
<body>
<div class="container">
​
   <div class="row clearfix">
       <div class="col-md-12 column">
           <div class="page-header">
               <h1>
                   <small>Modify information</small>
               </h1>
           </div>
       </div>
   </div>
​
   <form action="${pageContext.request.contextPath}/book/updateBook"method="post">
       <input type="hidden" name="bookID" value="${book.getBookID()}"/>
      Book Name:<input type="text" name="bookName"value="${book.getBookName()}"/>
      Number of books:<input type="text" name="bookCounts"value="${book.getBookCounts()}"/>
      Book details:<input type="text" name="detail" value="${book.getDetail() }"/>
       <input type="submit" value="Submit"/>
   </form>
​
</div>

8. BookController class, method 4: delete books

@RequestMapping("/del/{bookId}")
public String deleteBook(@PathVariable("bookId") int id) {
   bookService.deleteBookById(id);
   return "redirect:/book/allBook";
}

Configure Tomcat and run it!

So far, the integration of this SSM project has been completely OK and can be run directly for testing! This exercise is very important. You need to ensure that you can realize it completely without looking at anything!

Project structure diagram

 

8. Ajax technology

8.1 introduction

  • AJAX = Asynchronous JavaScript and XML.

  • AJAX is a technology that can update some web pages without reloading the whole web page.

  • Ajax is not a new programming language, but a technology for creating better, faster and more interactive Web applications.

  • In 2005, Google made AJAX popular through its Google suggest. Google Suggest can automatically help you search for words.

  • Google Suggest uses AJAX to create a highly dynamic web interface: when you enter keywords in Google's search box, JavaScript will send these characters to the server, and then the server will return a list of search suggestions.

  • Just like the domestic Baidu search box!

  • Traditional web pages (that is, web pages without ajax Technology) need to reload the whole web page if they want to update the content or submit a form.

  • Web pages using ajax technology can realize asynchronous local update through a small amount of data exchange in the background server.

  • Using Ajax, users can create a direct, highly available, richer and more dynamic Web user interface close to local desktop applications.

8.2 fake Ajax

We can use a tag on the front end to fake an ajax look. iframe tag

1. Create a new module: sspring mvc-06-ajax and import web support!

2. Write an Ajax frame HTML use iframe test to feel the effect

<!DOCTYPE html>
<html>
<head lang="en">
   <meta charset="UTF-8">
   <title>dary</title>
</head>
<body>
​
<script type="text/javascript">
   window.onload = function(){
       var myDate = new Date();
       document.getElementById('currentTime').innerText = myDate.getTime();
  };
​
   function LoadPage(){
       var targetUrl =  document.getElementById('url').value;
       console.log(targetUrl);
       document.getElementById("iframePosition").src = targetUrl;
  }
​
</script>
​
<div>
   <p>Please enter the address to load:<span id="currentTime"></span></p>
   <p>
       <input id="url" type="text" value="https://www.baidu.com/"/>
       <input type="button" value="Submit" onclick="LoadPage()">
   </p>
</div>
​
<div>
   <h3>Load page location:</h3>
   <iframe id="iframePosition" style="width: 100%;height: 500px;"></iframe>
</div>
​
</body>
</html>

3. Use IDEA to open the browser to test!

AJAX can be used to:

  • When registering, enter the user name to automatically detect whether the user already exists.

  • When logging in, you will be prompted with the wrong user name and password

  • When deleting a data row, the row ID is sent to the background, and the background deletes it in the database. After the database is deleted successfully, the data row is also deleted in the page DOM.

  • .... wait

8.3 jQuery.ajax

We will not explain the pure JS native implementation of Ajax here. We will directly use the one provided by jquery to facilitate learning and use and avoid repeated wheel building. Interested students can learn about JS native XMLHttpRequest!

The core of Ajax is the XMLHttpRequest object (XHR). XHR provides an interface for sending requests to the server and parsing server responses. It can obtain new data from the server asynchronously.

jQuery provides several AJAX related methods.

Through the jQuery AJAX method, you can use HTTP Get and HTTP Post to request text, HTML, XML or JSON from a remote server - and you can load these external data directly into the selected elements of the web page.

jQuery is not a producer, but a nature porter.

The essence of jQuery Ajax is XMLHttpRequest, which is encapsulated and easy to call!

jQuery.ajax(...)
      Some parameters:
            url: Request address
            type: Request method, GET,POST(1.9.0 Later use method)
        headers: Request header
            data: Data to send
    contentType: The content encoding type of the message to be sent to the server(default: "application/x-www-form-urlencoded; charset=UTF-8")
          async: Asynchronous
        timeout: Set request timeout (MS)
      beforeSend: Function executed before sending the request(overall situation)
        complete: Callback function executed after completion(overall situation)
        success: Callback function executed after success(overall situation)
          error: Callback function executed after failure(overall situation)
        accepts: Send the request to the server and tell the server the data type acceptable to the current client
        dataType: Converts the data returned by the server to the specified type
          "xml": Convert the content returned by the server into xml format
          "text": Convert the content returned by the server into normal text format
          "html": Convert the content returned by the server into normal text format and insert DOM If it contains JavaScript Tag, it will try to execute.
        "script": Try to treat the return value as JavaScript To execute, and then convert the content returned by the server into normal text format
          "json": Convert the content returned by the server into the corresponding JavaScript object
        "jsonp": JSONP Format usage JSONP When calling a function in the form, such as "myurl?callback=?" jQuery Will automatically replace ? Enter the correct function name to execute the callback function

Let's do a simple test, using the most primitive HttpServletResponse processing The simplest and most versatile

1. Configure web XML and spring MVC configuration files, just copy the above case [remember static resource filtering and annotation driven configuration]

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:mvc="http://www.springframework.org/schema/mvc"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">
​
   <!-- Automatically scan the specified package and submit all the following annotation classes to IOC Container management -->
   <context:component-scan base-package="com.dary.controller"/>
   <mvc:default-servlet-handler />
   <mvc:annotation-driven />
​
   <!-- view resolver  -->
   <beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"
         id="internalResourceViewResolver">
       <!-- prefix -->
       <property name="prefix" value="/WEB-INF/jsp/" />
       <!-- suffix -->
       <property name="suffix" value=".jsp" />
   </bean>
​
</beans>

2. Write an Ajax controller

@Controller
public class AjaxController {
​
   @RequestMapping("/a1")
   public void ajax1(String name , HttpServletResponse response) throws IOException{
       if ("admin".equals(name)){
           response.getWriter().print("true");
      }else{
           response.getWriter().print("false");
      }
  }
​
}

3. To import jquery, you can use the online CDN or download the import

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>

4. Write index JSP test

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
 <head>
   <title>$Title$</title>
  <%--<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>--%>
   <script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>
   <script>
       function a1(){
           $.post({
               url:"${pageContext.request.contextPath}/a1",
               data:{'name':$("#txtName").val()},
               success:function (data,status) {
                   alert(data);
                   alert(status);
              }
          });
      }
   </script>
 </head>
 <body>
​
<%--onblur: Event triggered by loss of focus--%>
user name:<input type="text" id="txtName" onblur="a1()"/>
​
 </body>
</html>

5. Start tomcat test! Open the browser console. When we leave the input box with the mouse, we can see that an ajax request has been issued! It is the result returned to us by the background! Test successful!

Spring MVC implementation

Entity class user

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
​
   private String name;
   private int age;
   private String sex;
​
}

Let's get a collection object and show it to the front page

@RequestMapping("/a2")
public List<User> ajax2(){
   List<User> list = new ArrayList<User>();
   list.add(new User("Qinjiang 1",3,"male"));
   list.add(new User("Qinjiang 2",3,"male"));
   list.add(new User("Qinjiang 3",3,"male"));
   return list; //Due to the @ RestController annotation, convert the list to json format and return
}

Front page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Title</title>
</head>
<body>
<input type="button" id="btn" value="get data"/>
<table width="80%" align="center">
   <tr>
       <td>full name</td>
       <td>Age</td>
       <td>Gender</td>
   </tr>
   <tbody id="content">
   </tbody>
</table>
​
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>
<script>
​
   $(function () {
       $("#btn").click(function () {
           $.post("${pageContext.request.contextPath}/a2",function (data) {
               console.log(data)
               var html="";
               for (var i = 0; i <data.length ; i++) {
                   html+= "<tr>" +
                       "<td>" + data[i].name + "</td>" +
                       "<td>" + data[i].age + "</td>" +
                       "<td>" + data[i].sex + "</td>" +
                       "</tr>"
              }
               $("#content").html(html);
          });
      })
  })
</script>
</body>
</html>

Successfully realized the data echo! You can experience the benefits of Ajax!

 

8.5 registration prompt effect

Let's test a small Demo and think about how to do the real-time prompt behind the input box when we usually register; How to optimize

Let's write a Controller

@RequestMapping("/a3")
public String ajax3(String name,String pwd){
   String msg = "";
   //There is data in the simulation database
   if (name!=null){
       if ("admin".equals(name)){
           msg = "OK";
      }else {
           msg = "User name input error";
      }
  }
   if (pwd!=null){
       if ("123456".equals(pwd)){
           msg = "OK";
      }else {
           msg = "Incorrect password input";
      }
  }
   return msg; //Due to the @ RestController annotation, msg is converted into json format and returned
}

Front page login jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>ajax</title>
   <script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>
   <script>
​
       function a1(){
           $.post({
               url:"${pageContext.request.contextPath}/a3",
               data:{'name':$("#name").val()},
               success:function (data) {
                   if (data.toString()=='OK'){
                       $("#userInfo").css("color","green");
                  }else {
                       $("#userInfo").css("color","red");
                  }
                   $("#userInfo").html(data);
              }
          });
      }
       function a2(){
           $.post({
               url:"${pageContext.request.contextPath}/a3",
               data:{'pwd':$("#pwd").val()},
               success:function (data) {
                   if (data.toString()=='OK'){
                       $("#pwdInfo").css("color","green");
                  }else {
                       $("#pwdInfo").css("color","red");
                  }
                   $("#pwdInfo").html(data);
              }
          });
      }
​
   </script>
</head>
<body>
<p>
  user name:<input type="text" id="name" onblur="a1()"/>
   <span id="userInfo"></span>
</p>
<p>
  password:<input type="text" id="pwd" onblur="a2()"/>
   <span id="pwdInfo"></span>
</p>
</body>
</html>

[remember to deal with json garbled code]

Test the effect, dynamic request response, local refresh, that's it!

Get baidu interface Demo

<!DOCTYPE HTML>
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>JSONP Baidu search</title>
   <style>
       #q{
           width: 500px;
           height: 30px;
           border:1px solid #ddd;
           line-height: 30px;
           display: block;
           margin: 0 auto;
           padding: 0 10px;
           font-size: 14px;
      }
       #ul{
           width: 520px;
           list-style: none;
           margin: 0 auto;
           padding: 0;
           border:1px solid #ddd;
           margin-top: -1px;
           display: none;
      }
       #ul li{
           line-height: 30px;
           padding: 0 10px;
      }
       #ul li:hover{
           background-color: #f60;
           color: #fff;
      }
   </style>
   <script>
​
       // 2. Step 2
       // Define demo function (analysis interface, data)
       function demo(data){
           var Ul = document.getElementById('ul');
           var html = '';
           // If the search data exists, add the content
           if (data.s.length) {
               // The hidden ul is displayed
               Ul.style.display = 'block';
               // The searched data is circularly appended to li
               for(var i = 0;i<data.s.length;i++){
                   html += '<li>'+data.s[i]+'</li>';
              }
               // Cyclic li write ul
               Ul.innerHTML = html;
          }
      }
​
       // 1. Step 1
       window.onload = function(){
           // Get input box and ul
           var Q = document.getElementById('q');
           var Ul = document.getElementById('ul');
​
           // When the event mouse is raised
           Q.onkeyup = function(){
               // If the input box is not equal to empty
               if (this.value != '') {
                   // ☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆ JSONPz key ☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆
                   // create label
                   var script = document.createElement('script');
                   //Given the address to cross domain, assign it to src
                   //Here is the cross domain address to be requested. I wrote the cross domain address of Baidu search
                   script.src ='https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+this.value+'&cb=demo';
                   // Append the combined script tag with src to the body
                   document.body.appendChild(script);
              }
          }
      }
   </script>
</head>
​
<body>
<input type="text" id="q" />
<ul id="ul">
​
</ul>
</body>
</html>

9. Interceptor

summary

The processor interceptor of spring MVC is similar to the Filter in Servlet development, which is used to preprocess and post process the processor. Developers can define some interceptors to implement specific functions.

The difference between filter and Interceptor: interceptor is the specific application of AOP idea.

filter

  • Part of the servlet specification that can be used by any java web project

  • After / * is configured in URL pattern, all resources to be accessed can be intercepted

Interceptor

  • The interceptor is the spring MVC framework's own. It can only be used by projects that use the spring MVC framework

  • The interceptor will only intercept the accessed controller methods. If the accessed is jsp/html/css/image/js, it will not intercept

 

custom interceptor

How to implement the interceptor?

To customize the interceptor, you must implement the HandlerInterceptor interface.

1. Create a new Moudule, springmvc-07-Interceptor, and add web support

2. Configure web XML and springmvc servlet XML file

3. Write an interceptor

package com.dary.interceptor;
​
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
​
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
​
public class MyInterceptor implements HandlerInterceptor {
​
   //Execute before the method of request processing
   //If true is returned, execute the next interceptor
   //If false is returned, the next interceptor will not be executed
   public boolean preHandle(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse, Object o) throws Exception {
       System.out.println("------------Before treatment------------");
       return true;
  }
​
   //Executed after the request processing method is executed
   public void postHandle(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)throws Exception {
       System.out.println("------------After treatment------------");
  }
​
   //After the dispatcher servlet is processed, it is executed and cleaned up
   public void afterCompletion(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
       System.out.println("------------clear------------");
  }
}

4. Configure the interceptor in the configuration file of spring MVC

<!--About interceptor configuration-->
<mvc:interceptors>
   <mvc:interceptor>
       <!--/** Include paths and their sub paths-->
       <!--/admin/* Intercepting is/admin/add Wait, this , /admin/add/user Will not be intercepted-->
       <!--/admin/** Intercepting is/admin/All under-->
       <mvc:mapping path="/**"/>
       <!--bean Interceptors are configured-->
       <bean class="com.dary.interceptor.MyInterceptor"/>
   </mvc:interceptor>
</mvc:interceptors>

5. Write a Controller to receive requests

package com.dary.controller;
​
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
​
//Test interceptor controller
@Controller
public class InterceptorController {
​
   @RequestMapping("/interceptor")
   @ResponseBody
   public String testFunction() {
       System.out.println("The method in the controller is implemented");
       return "hello";
  }
}

6. Front end index jsp

<a href="${pageContext.request.contextPath}/interceptor">Interceptor test</a>

7. Start tomcat test!

Verify whether the user is logged in (authenticated user)

Realization idea

1. There is a login page. You need to write a controller access page.

2. The login page has an action to submit a form. It needs to be processed in the controller. Determine whether the user name and password are correct. If correct, write the user information to the session. Return to login success.

3. Intercept the user's request and judge whether the user logs in. If the user has logged in. Release. If the user does not log in, jump to the login page

Test:

1. Write a login page login jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Title</title>
</head>
​
<h1>Login page</h1>
<hr>
​
<body>
<form action="${pageContext.request.contextPath}/user/login">
  user name:<input type="text" name="username"> <br>
  password:<input type="password" name="pwd"> <br>
   <input type="submit" value="Submit">
</form>
</body>
</html>

2. Write a Controller to process the request

package com.dary.controller;
​
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
​
import javax.servlet.http.HttpSession;
​
@Controller
@RequestMapping("/user")
public class UserController {
​
   //Jump to landing page
   @RequestMapping("/jumplogin")
   public String jumpLogin() throws Exception {
       return "login";
  }
​
   //Jump to success page
   @RequestMapping("/jumpSuccess")
   public String jumpSuccess() throws Exception {
       return "success";
  }
​
   //Login submission
   @RequestMapping("/login")
   public String login(HttpSession session, String username, String pwd) throwsException {
       // Record user identity information to session
       System.out.println("Receiving front end==="+username);
       session.setAttribute("user", username);
       return "success";
  }
​
   //Exit login
   @RequestMapping("logout")
   public String logout(HttpSession session) throws Exception {
       // session expired
       session.invalidate();
       return "login";
  }
}

3. Write a successful login page success jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Title</title>
</head>
<body>
​
<h1>Successful login page</h1>
<hr>
​
${user}
<a href="${pageContext.request.contextPath}/user/logout">cancellation</a>
</body>
</html>

4. Test jump on the index page! Start Tomcat test, and you can enter the home page without logging in!

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
 <head>
   <title>$Title$</title>
 </head>
 <body>
 <h1>home page</h1>
 <hr>
<%--Sign in--%>
 <a href="${pageContext.request.contextPath}/user/jumplogin">Sign in</a>
 <a href="${pageContext.request.contextPath}/user/jumpSuccess">Success page</a>
 </body>
</html>

5. Write user login interceptor

package com.dary.interceptor;
​
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
​
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
​
public class LoginInterceptor implements HandlerInterceptor {
​
   public boolean preHandle(HttpServletRequest request, HttpServletResponseresponse, Object handler) throws ServletException, IOException {
       // If it is a landing page, release it
       System.out.println("uri: " + request.getRequestURI());
       if (request.getRequestURI().contains("login")) {
           return true;
      }
​
       HttpSession session = request.getSession();
​
       // If the user has logged in, it can also be released
       if(session.getAttribute("user") != null) {
           return true;
      }
​
       // The user does not log in and jumps to the login page
       request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
       return false;
  }
​
   public void postHandle(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)throws Exception {
​
  }
   
   public void afterCompletion(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
​
  }
}

6. Register the interceptor in the configuration file of spring MVC

<!--About interceptor configuration-->
<mvc:interceptors>
   <mvc:interceptor>
       <mvc:mapping path="/**"/>
       <bean id="loginInterceptor" class="com.dary.interceptor.LoginInterceptor"/>
   </mvc:interceptor>
</mvc:interceptors>

7. Restart Tomcat test again!

OK, test the login interception function

File upload and download

preparation

File upload is one of the most common functions in project development. Spring MVC can well support file upload, but MultipartResolver is not installed in the context of spring MVC by default, so it cannot handle file upload by default. If you want to use spring's file upload function, you need to configure MultipartResolver in the context.

Front end form requirements: in order to upload files, the method of the form must be set to POST and the enctype must be set to multipart / form data. Only in this case, the browser will send the file selected by the user to the server as binary data;

Give a detailed description of the enctype attribute in the form:

  • Application / x-www = form urlencoded: by default, only the value attribute value in the form field is processed. Forms with this encoding method will process the value in the form field into URL encoding method.

  • Multipart / form data: this encoding method will process form data in the form of binary stream. This encoding method will also encapsulate the contents of the file specified in the file field into the request parameters, and will not encode characters.

  • text/plain: except for converting spaces into "+" signs, other characters are not encoded. This method is applicable to sending mail directly through forms.

<form action="" enctype="multipart/form-data" method="post">
   <input type="file" name="file"/>
   <input type="submit">
</form>

Once the enctype is set to multipart / form data, the browser will process the form data in the form of binary stream, and the processing of file upload involves parsing the original HTTP response on the server side. In 2003, the Apache Software Foundation released the open source Commons FileUpload component, which soon became the best choice for Servlet/JSP programmers to upload files.

  • Servlet3. The 0 specification has provided a method to handle file upload, but this upload needs to be completed in the servlet.

  • Spring MVC provides a simpler encapsulation.

  • Spring MVC provides direct support for file upload, which is implemented with the plug and play MultipartResolver.

  • Spring MVC implements a MultipartResolver implementation class using Apache Commons FileUpload Technology:

  • CommonsMultipartResolver. Therefore, the file upload of spring MVC also needs to rely on the component of Apache Commons FileUpload.

 

File upload

1. Import the jar package uploaded by the file, commons fileUpload, Maven will automatically help us import his dependent package commons IO package;

<!--File upload-->
<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.3</version>
</dependency>
<!--servlet-api Import a higher version of-->
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>4.0.1</version>
</dependency>

2. Configuration bean: multipartResolver

[note!!! The id of this bena must be: multipartResolver, or 400 error will be reported when uploading the file! I've planted a pit here, and I'll teach you a lesson!]

<!--File upload configuration-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <!-- The encoding format of the request must be the same as jSP of pageEncoding Properties are consistent so that the contents of the form can be read correctly. The default is ISO-8859-1 -->
   <property name="defaultEncoding" value="utf-8"/>
   <!-- Upper limit of uploaded file size, in bytes (10485760)=10M) -->
   <property name="maxUploadSize" value="10485760"/>
   <property name="maxInMemorySize" value="40960"/>
</bean>

Common methods of CommonsMultipartFile:

  • Get the original name of the uploaded file getstringfilename():

  • InputStream getInputStream(): get file stream

  • void transferTo(File dest): save the uploaded file to a directory file

Let's actually test it

3. Write front page

<form action="/upload" enctype="multipart/form-data" method="post">
 <input type="file" name="file"/>
 <input type="submit" value="upload">
</form>

4,Controller

package com.dary.controller;
​
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
​
import javax.servlet.http.HttpServletRequest;
import java.io.*;
​
@Controller
public class FileController {
   //@RequestParam("file") encapsulates the file obtained by the name=file control into a CommonsMultipartFile object
   //If you upload CommonsMultipartFile in batch, it can be an array
   @RequestMapping("/upload")
   public String fileUpload(@RequestParam("file") CommonsMultipartFile file ,HttpServletRequest request) throws IOException {
​
       //Get file name: file getOriginalFilename();
       String uploadFileName = file.getOriginalFilename();
​
       //If the file name is empty, go back to the home page directly!
       if ("".equals(uploadFileName)){
           return "redirect:/index.jsp";
      }
       System.out.println("Upload file name : "+uploadFileName);
​
       //Upload path save settings
       String path = request.getServletContext().getRealPath("/upload");
       //If the path does not exist, create one
       File realPath = new File(path);
       if (!realPath.exists()){
           realPath.mkdir();
      }
       System.out.println("Upload file storage address:"+realPath);
​
       InputStream is = file.getInputStream(); //File input stream
       OutputStream os = new FileOutputStream(new File(realPath,uploadFileName));//File output stream
​
       //Read write
       int len=0;
       byte[] buffer = new byte[1024];
       while ((len=is.read(buffer))!=-1){
           os.write(buffer,0,len);
           os.flush();
      }
       os.close();
       is.close();
       return "redirect:/index.jsp";
  }
}

5. Test upload file, OK!

Use file To save the uploaded file

1. Write Controller

/*
* Use file To save the uploaded file
*/
@RequestMapping("/upload2")
public String  fileUpload2(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException {
​
   //Upload path save settings
   String path = request.getServletContext().getRealPath("/upload");
   File realPath = new File(path);
   if (!realPath.exists()){
       realPath.mkdir();
  }
   //Upload file address
   System.out.println("Upload file storage address:"+realPath);
​
   //Write the file directly through the CommonsMultipartFile method (note this time)
   file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
​
   return "redirect:/index.jsp";
}

2. Front end form submission address modification

3. Visit submit test, OK!

File download

File download steps:

1. Set response header

2. Read file -- InputStream

3. Write out file -- OutputStream

4. Perform operations

5. Close flow (first on then off)

Code implementation:

@RequestMapping(value="/download")
public String downloads(HttpServletResponse response ,HttpServletRequest request)throws Exception{
   //Address of the picture to download
   String  path = request.getServletContext().getRealPath("/upload");
   String  fileName = "Basic grammar.jpg";
​
   //1. Set response header
   response.reset(); //Set the page not to be cached, and empty the buffer
   response.setCharacterEncoding("UTF-8"); //Character encoding
   response.setContentType("multipart/form-data"); //Binary transmission data
   //Set response header
   response.setHeader("Content-Disposition",
           "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
​
   File file = new File(path,fileName);
   //2. Read file -- input stream
   InputStream input=new FileInputStream(file);
   //3. Write out file -- output stream
   OutputStream out = response.getOutputStream();
​
   byte[] buff =new byte[1024];
   int index=0;
   //4. Perform write out operation
   while((index= input.read(buff))!= -1){
       out.write(buff, 0, index);
       out.flush();
  }
   out.close();
   input.close();
   return null;
}

front end

< a href = "/ download" > click download</a>

Keywords: Java Spring MVC SSM

Added by Deltran on Sat, 19 Feb 2022 06:57:49 +0200