SpringMVC

For SpringMVC:

  • Controller: controller
    • Get form data
    • Invoking business logic
    • Redirect to the specified page
  • Model: model
    • The business logic
    • Save the state of the data
  • View: view
    • Display the page

For SpringMVC advantages:

  • Lightweight and easy to learn
  • Efficient, response-based MVC framework
  • Good compatibility with Spring, seamless integration
  • Convention over Configuration
  • Powerful function: restful, data verification, formatting and so on
  • Separate business logic, data and display, reduce coupling between modules,

First, the SpringMVC

Spring’s Web framework is designed around DispatcherServlet dispatch servlets.

HelloSpringMVC project construction, pom. XML import Spring-WebMVC, servlet-API, JSTL-API, JSTL JAR package

web.xml

	 <! - registered DispatcherServlet -- -- >
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <! -- Associated with a SpringMVC configuration file -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <! -- Boot level -->
        <load-on-startup>1</load-on-startup>

    </servlet>

    <! -- / Match all requests (excluding.jsp) -->
    <! -- /* Match all requests (including.jsp) -->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Copy the code

springmvc-servlet.xml


      
<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">

    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

    <! -- View parser, DispatcherServlet to its ModelAndView-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <! -- prefix -- -- >
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <! - the suffix - >
        <property name="suffix" value=".jsp"/>
    </bean>

    <! --Handler-->
    <bean id="/hello" class="com.zr.controller.HelloController"/>
    
</beans>
Copy the code

HelloController

/ / note: import org. Springframework. Web. Servlet. MVC. Controller;
public class HelloController implements Controller {
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // Model and view
        ModelAndView mv = new ModelAndView();

        // Encapsulate the object and place it in ModelAndView
        mv.addObject("msg"."HelloSpringMVC!");
        // Encapsulate the view to jump to
        mv.setViewName("hello");  ///WEB-INF/jsp/hello.jsp
        returnmv; }}Copy the code

hello.jsp

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

    ${msg}
    
</body>
</html>
Copy the code

Note: If accesshttp://localhost:8080/hello in 404

Select your project name, create a new lib folder under WEB-INF, click the + sign, add the project’s dependencies to lib, restart the project!!

SpringMVC executes the process

  1. The DispatcherServlet represents the front controller and is the center of the whole SpringMVC control. Users send requests, DispatcherServlet receives them and intercepts them.
  2. HandlerMapping is a processor mapper that searches for handlers based on the url requested by the processor and is invoked by a DispatcherServlet.
  3. HandlerExecution represents a specific Handler whose primary purpose is to find a controller based on a URL.
  4. HandlerExecution passes parsed information to the DispatcherServlet, such as parsed controller mappings.
  5. HandlerAdapter represents a processor adapter that executes handlers according to specific rules.
  6. Handler lets specific controllers execute.
  7. The Controller returns the execution information to the HandlerAdapter, such as ModelAndView.
  8. The HandlerAdapter passes the view logical name or model to the DispatcherServlet.
  9. The DispatcherServlet calls the ViewResolver to resolve the logical view name passed by the HandlerAdapter.
  10. The view parser passes the parsed logical view name to the DispatcherServlet.
  11. The view is rendered to the user.

Use annotations to develop SpringMVC

Controller is the Controller

  • The controller is responsible for providing the behavior to access the application, usually through interface definitions or annotation definitions.

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

  • A controller class can contain multiple methods in SpringMVC.

web.xml

<! This is the heart of SpringMVC, request dispatcher, front-end controller -->
<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <! -- Bind the spring configuration file -->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc-servlet.xml</param-value>
    </init-param>
    <! -- Boot level -->
    <load-on-startup>1</load-on-startup>
</servlet>

<! -- In SpringMVC: / : matches all requests. Do not match JSP pages /* : Match all requests. Match JSP page -->
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
Copy the code

springmvc-servlet.xml


      
<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 https://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, make the annotations under the package valid, unified management by IOC container -->
    <context:component-scan base-package="com.zr.controller"/>
    <! Let SpringMVC not handle static resources -->
    <mvc:default-servlet-handler/>

    <! -- Annotation-driven spring uses the @requestMapping annotation to complete the mapping. Must be registered DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter this two instances in class level and treatment level of the annotation - driven to help us to complete the above two instances of injection -->
    <mvc:annotation-driven/>

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

</beans>
Copy the code

HelloController

@Controller
public class HelloController {

    @RequestMapping("/h1")
    public String hello(Model model){
        // Encapsulate data
        model.addAttribute("msg"."HelloSpringMVCAnnotation");

        return "hello"; // View resolver processing}}Copy the code

hello.jsp

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

RestFul style

Concept: RestFul is a style for locating and operating resources. It is not a standard or a protocol, but a style. Software designed based on this style can be more concise, more hierarchical, and easier to implement caching mechanisms.

The URL definition

Resource: All things on the Internet can be abstracted as resources. Resource operations: Use POST, DELETE, PUT, and GET to operate resources in different ways. Corresponding to add, delete, modify, query.

The traditional way to manipulate resources

http://127.0.0.1/item/saveUser.action http://127.0.0.1/item/queryUser.action?id=1 query, GET new POST http://127.0.0.1/item/updateUser.action update, delete the POST http://127.0.0.1/item/deleteUser.action?id=1 GET or POST

Use RestFul operation resources: You can achieve different effects through different requests!

[http://127.0.0.1/item/zr query, GET [http://127.0.0.1/item/ added, POST [http://127.0.0.1/item/ updates, the PUT [http://127.0.0.1/item/zr DELETE, DELETE

Learn to test

  1. Create a new test class, RestFulController, and annotate the method parameter with the @pathVariable annotation so that the value of the method parameter is bound to a URL template variable.

    @Controller
    public class RestFulController {
        @RequestMapping("/add/{a}/{b}")
        public String test(@PathVariable int a, @PathVariable int b, Model model){
            int res = a + b;
            model.addAttribute("msg"."The result is"+res);
            return "test";  //test.jsp}}Copy the code

Request the same address, get different results

http://localhost:8080/add/3/4

http://localhost:8080/a.jsp

//@RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.DELETE)
//@RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.GET)
@GetMapping("/add/{a}/{b}")
public String test(@PathVariable int a, @PathVariable int b, Model model){
    int res = a + b;
    model.addAttribute("msg"."Result 1 is"+res);
    return "test";
}

@PostMapping("/add/{a}/{b}")
public String test2(@PathVariable int a, @PathVariable int b, Model model){
    int res = a + b;
    model.addAttribute("msg"."Result 2 is+res);
    return "test";
}
Copy the code

A. sp under the web

<form action="/add/3/4" method="post">

    <input type="submit">
</form>
Copy the code

web/WEB-INF/jsp/test.jsp

<body>
${msg}
</body>
Copy the code

Redirection and forwarding

ModelAndView: Jumps to the specified page based on the name of the view and the view parser.

Use SpringMVC for forwarding and redirection —– ignore the graph parser

@Controller
public class ModelTest1 {

    @RequestMapping("/m1/t1")
    public String test(Model model){
        model.addAttribute("msg"."ModelTest1");
        // return "/WEB-INF/jsp/test.jsp";
        / / forwarding
        // return "forward:/index.jsp";
        / / redirection
           return "redirect:/index.jsp";
    }
Copy the code

Use SpringMVC to implement forwarding and redirection —– there is a view parser

@Controller
public class HelloController {

    @RequestMapping("/h1")
    public String hello(Model model){
        // Encapsulate data
        model.addAttribute("msg"."HelloSpringMVCAnnotation");

        return "hello"; // View resolver processing}}Copy the code

The data processing

The User entity class

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private int age;
}
Copy the code

The UserController class accepts arguments using @requestParam (“***”)

@Controller
@RequestMapping("/user")
public class UserController {

    //localhost:8080/user/t1? name=***
    @RequestMapping("/t1")
    public String test1(@RequestParam("name") String name, Model model){
        // Receive front-end parameters
        System.out.println("The parameters received from the front end are+name);
        // Pass the result to the front end
        model.addAttribute("msg",name);
        // Jump view
        return "test";
    }

    /* 1. Check the name of the parameter. If the name is in the method, you can use 2. Suppose you pass an object User that matches the field name */ of the User object

    //http://localhost:8080/user/t2? id=1&name=zzzrrr&age=20
    // The front-end accepts an object: id,name,age
    @RequestMapping("/t2")
    public String test2(User user){
        System.out.println(user);
        return "test";
    }
Copy the code

Garbage processing

In development, we often encounter garbled characters, and in the Servlet phase we use authoring filters to filter. Now SpringMVC also gives us a filter to configure in XML and then restart the server.

Under the web form. The JSP

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

</form>
</body>
Copy the code

EncodingController

@Controller public class EncodingController { @PostMapping("/e/t1") public String test1(String name, Model model){ model.addAttribute("msg",name); System.out.println(name); return "test"; }}Copy the code

Coding filter

<! -- Configure garble filtering for SpringMVC
<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>
Copy the code

JSON

What is JSON?

  • JSON (JavaScript Object Notation) is a lightweight data interchange format
  • Data is stored and represented in a text format that is completely independent of the programming language
  • Easy to read and write, but also easy to machine parsing and generation, and effectively improve the network transmission rate
  • Objects are represented as key-value pairs, with data separated by commas
  • Curly braces save objects
  • Square brackets hold arrays
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        // Write a javascript object
        var user = {
            name:"Week".age:"20".sex:"South"
        };
        // Convert js objects to JSON objects
        var json = JSON.stringify(user);
        console.log(json);

        // Json is converted to javascript objects
        var js = JSON.parse(json);
        console.log(js)

        console.log(user);
    </script>
</head>
<body>

</body>
</html>
Copy the code

The use of the Jackson

Jackson is the most widely used Java open source framework for serializing and deserializing JSON. Jackson is one of the most popular JSON parsers.

Jackson’s most commonly used API is the ObjectMapper based on “object binding”.

Add dependencies using pre-pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>xml
    <version>2.10.0</version>
</dependency>
Copy the code

web.xml

<! This is the heart of SpringMVC, request dispatcher, front-end controller -->
<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <! -- Bind the spring configuration file -->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc-servlet.xml</param-value>
    </init-param>
    <! -- Boot level -->
    <load-on-startup>1</load-on-startup>
</servlet>

<! -- In SpringMVC: / : matches all requests. Do not match JSP pages /* : Match all requests. Match JSP page -->
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<! -- Configure garble filtering for SpringMVC
<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>
Copy the code

springmvc-servlet.xml


      
<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 https://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, make the annotations under the package valid, unified management by IOC container -->
    <context:component-scan base-package="com.zr.controller"/>

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

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

</beans>
Copy the code

The User class

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private String name;
    private int age;
    private String sex;

}
Copy the code

UserController

@RestController    // Can't go to the view parser,
public class UserController {
    It is recommended to resolve json garbled characters in XML
    // @RequestMapping(value = "/j1",produces = "application/json; charset=utf-8")
    @RequestMapping("/j1")
    // @responseBody // will not go to the view parser, will return a string directly
    public String json1(a) throws JsonProcessingException {
        //jackson ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        // Create an object
        User user = new User("Week".20."South");

        String s = mapper.writeValueAsString(user);
        returns; }}Copy the code

Return a JSON array that returns the formatting time (method added to the UserController class)

@RequestMapping("/j2")
public String json2(a) throws JsonProcessingException {

    ObjectMapper mapper = new ObjectMapper();

    List<User> list = new ArrayList<User>();

    User user1 = new User("Week 1".20."South");
    User user2 = new User("Week 2".20."South");
    User user3 = new User("Week 3".20."South");
    User user4 = new User("Week week 4".20."South");

    list.add(user1);
    list.add(user2);
    list.add(user3);
    list.add(user4);
    String s = mapper.writeValueAsString(list);
    return s;
}

@RequestMapping("/j3")
public String json3(a) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();

    // Customize the format of the date
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = new Date();
    //return mapper.writeValueAsString(date);
    return mapper.writeValueAsString(sdf.format(date));
}

@RequestMapping("/j4")
public String json4(a) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    // Use ObjectMapper to format output
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    mapper.setDateFormat(sdf);
    Date date = new Date();
    return mapper.writeValueAsString(date);
}
Copy the code

Packaging ideas

Utility class

public class JsonUtil {
    
    public static String getMapper(Object object,String dateFormat){
        ObjectMapper mapper = new ObjectMapper();
        // Use ObjectMapper to format output
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        mapper.setDateFormat(sdf);
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String getMapper(Object object){
        return getMapper(object,"yyyy-MM-dd HH:mm:ss"); }}Copy the code

Test utility class (methods added to the UserController class)

@RequestMapping("/j5")
public String json5(a) {
    Date date = new Date();
    return JsonUtil.getMapper(date,"yyyy-MM-dd HH:mm:ss");
}

@RequestMapping("/j6")
public String json6(a) {
    List<User> list = new ArrayList<User>();

    User user1 = new User("Week 1".20."South");
    User user2 = new User("Week 2".20."South");
    User user3 = new User("Week 3".20."South");
    User user4 = new User("Week week 4".20."South");

    list.add(user1);
    list.add(user2);
    list.add(user3);
    list.add(user4);
    return JsonUtil.getMapper(list);
}
Copy the code

FastJson

FastJson is a special package developed by Alibaba for Java development, which can easily realize the conversion between JSON objects and JavaBean objects, JavaBean objects and JSON strings, and realize the conversion between JSON objects and JSON strings.

Guide package

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.74</version>
</dependency>
Copy the code

FastJson has three main classes

  • JSONObject represents a JSON object. JSONObject implements the Map interface
  • JSONArray stands for JSON array objects, which are internally manipulated by methods in the List interface
  • JSON represents the transformation of JSONObject and JSONArray
@RequestMapping("/j7")
public String json7(a) {
    List<User> list = new ArrayList<User>();

    User user1 = new User("Week 1".20."South");
    User user2 = new User("Week 2".20."South");
    User user3 = new User("Week 3".20."South");
    User user4 = new User("Week week 4".20."South");

    list.add(user1);
    list.add(user2);
    list.add(user3);
    list.add(user4);

      // Java object to JSON string
        String s = JSON.toJSONString(list);
        System.out.println(s);
        String s1 = JSON.toJSONString(user1);
        System.out.println("s1: "+s1);

        // Json string to Java object
        User s2 = JSON.parseObject(s1,User.class);
        System.out.println("s2: "+s2.toString());

        // Java object to JSON object
        JSONObject s3 = (JSONObject) JSON.toJSON(user2);
        System.out.println("s3: "+s3.toJSONString());

        // Json object to Java object
        User s4 = JSON.toJavaObject(s3, User.class);
        System.out.println("s4: "+s4);
        return "hello"; }}Copy the code

Integration of the SSM

Create a new Maven project, ssmBuild

Environment configuration:

Import the following dependencies in pom.xml and allow static resource exports

<! - import dependence on junit, database driver, connection pool, Servlet, JSP, mybatis, mybatis - spring, spring, lembok, spring - JDBC, JSTL, standard, etc. -- -- >
<dependencies>.</dependencies>
<! -- Static resource export -->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
Copy the code

database.properties

jdbc.driver=com.mysql.jdbc.Driver
If you are using MySQL 8.0+, add a time zone configuration
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild? useSSL=false&useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
Copy the code

mybatis-config.xml


      
<! DOCTYPEconfiguration
        PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<! -- Core Configuration file -->
<configuration>
    <! Configure the data source and leave it to Spring.
    <typeAliases>
        <package name="com.zr.pojo"/>
    </typeAliases>

    <mappers>
        <mapper class="com.zr.dao.BookMapper"/>
    </mappers>
</configuration>
Copy the code

spring-dao.xml


      
<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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <! -- Associate database configuration file -->
    <context:property-placeholder location="classpath:database.properties"/>

    <! C3p0: automatic operation, can automatically load configuration files, and can automatically set to objects durid hikari -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <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 property -->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <! -->
        <property name="autoCommitOnClose" value="false"/>
        <! -- Connection timeout time -->
        <property name="checkoutTimeout" value="10000"/>
        <! -- Failed connection, automatic reconnection times -->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>

    <! --sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    <! -- Bind mybatis profile -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <! -- Configure dao interface scanning package, dynamically implement DAO interface injection into spring container -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <! - injection sqlSessionFactory -- -- >
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <! -- dao package to scan -->
        <property name="basePackage" value="com.zr.dao"/>
    </bean>
</beans>
Copy the code

spring-service.xml


      
<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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

<! Service -->
    <context:component-scan base-package="com.zr.service"/>

    <! Inject all business classes into Spring, either through annotations or configuration.
    <bean id="BookServiceImpl" class="com.zr.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>

    <! Declarative transaction configuration -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <! Inject data source -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>
Copy the code

applicationContext.xml


      
<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 https://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>

</beans>
Copy the code

BookMapper.xml


      
<! DOCTYPEmapper
        PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

    <mapper namespace="com.zr.dao.BookMapper">
    
    <insert id="addBook" parameterType="Books">
        insert into books (bookName,bookCounts,detail) 
        values (#{bookName},#{bookCounts},#{detail});
    </insert>
    
    <delete id="deleteBookById" parameterType="int">
        delete from books where bookID=#{id};
    </delete>
    
    <update id="updateBook" parameterType="Books">
        update books set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
         where bookID=#{bookID};
    </update>

    <select id="selectBookById" resultType="Books">
        select * from books where bookID=#{id};
    </select>

    <select id="selectAllBook" resultType="Books">
        select * from books;
    </select>
</mapper>
Copy the code

Web.xml [classpath: applicationContext. XML] bean created to applicationContext. XML

<! --DispatcherServlet-->
<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>


<! -- Garbled filter -->
<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>

<! --session-->
<session-config>
    <session-timeout>15</session-timeout>
</session-config>
Copy the code

Entity class

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
}
Copy the code

BookMapper

public interface BookMapper {
    // Add a book
    int addBook(Books books);
    // Delete a book
    int deleteBookById(@Param("id") int id);
    // Modify a book
    int updateBook(Books books);
    // Query a book
    Books selectBookById(@Param("id") int id);
    // query all
    List<Books> selectAllBook(a);
}
Copy the code

BookService

public interface BookService {
    // Add a book
    int addBook(Books books);
    // Delete a book
    int deleteBookById(@Param("id") int id);
    // Modify a book
    int updateBook(Books books);
    // Query a book
    Books selectBookById(@Param("id") int id);
    // query all
    List<Books> selectAllBook(a);
}
Copy the code

BookServiceImpl

public class BookServiceImpl implements BookService{
    // Service invokes THE DAO layer: combines the DAO layer
    private BookMapper bookMapper;
    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

    public int addBook(Books books) {
        return bookMapper.addBook(books);
    }

    public int deleteBookById(int id) {
        return bookMapper.deleteBookById(id);
    }

    public int updateBook(Books books) {
        return bookMapper.updateBook(books);
    }

    public Books selectBookById(int id) {
        return bookMapper.selectBookById(id);
    }

    public List<Books> selectAllBook(a) {
        returnbookMapper.selectAllBook(); }}Copy the code

Ajax

Ajax: Asynchronous, the ability to update parts of a web page without loading the entire page.

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

Web.xml configures DispatcherServlet and encoding, spring-mVC.xml configures view parser, scanning package, annotation-driven support, static resource support

Open the window

test.html

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>The iframe test experience page is not refreshed</title>
    <script>
        function go() {
            var url = document.getElementById("url").value;
            document.getElementById("iframe1").src=url;
        }
    </script>
</head>
<body>
<div>
    <p>Please enter address:</p>
    <p>
        <input type="text" id="url" value="https://www.cnblogs.com/zhou-zr/">
        <input type="button" value="Submit" onclick="go()">
    </p>
 </div>

<div>
    <iframe id="iframe1" style="width: 100%; height: 500px">

    </iframe>
</div>

</body>
</html>
Copy the code

At the heart of Ajax is XMLHttpRequest.

Ajax loads data asynchronously

package com.zr.pojo;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private intid; javaprivate String name;
    private String sex;
}
Copy the code

AjaxController

package com.zr.controller;
@RestController
public class AjaxController {
    @RequestMapping("/t1")
    public String test(a){
        return "hello";
    }

    @RequestMapping("/a")
    public void a1(String name, HttpServletResponse response) throws IOException {
        System.err.println("name--->>"+name);
        if ("zr".equals(name)){
            response.getWriter().println("true");
        }else {
            response.getWriter().println("false"); }}}Copy the code

index.jsp

<head>
    <title>$Title$</title>
      <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<%--      <script src="${pageContext. Request. ContextPath} / static/js/jquery - 3.5.1 track of js." "></script>--%>
    <script>
      function a(a){
        $.ajax({
         url:"${pageContext.request.contextPath}/a",
            data:{"name": $("#username").val()}, success:function (data) { alert(data); </script> </head> <body> <%-- send a request to the background when losing focus --%> user name: <input type="text" id="username" onblur="a()">
  </body>
Copy the code

test2.jsp

<html>
<head>
    <title>Title</title>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>
        $(function () {
            $("#btn").click(function () {
                console.log("111");
                $.post("${pageContext.request.contextPath}/a2",function (data) {
                    // console.log(data);
                    var html="";
                    for (let i = 0; i < data.length; i++) {
                        html += "<tr>"+
                            "<td>"+ data[i].id+"</td>"+
                            "<td>"+ data[i].name+"</td>"+
                            "<td>"+ data[i].sex+"</td>"+
                            "</tr>"
                    }
                    $("#context").html(html) }); })}); </script> </head> <body> <input type="button" value="Load data" id="btn"> < table > < tr > < td > id < / td > < td > name < / td > < td > gender < / td > < / tr > < tbody id ="context"</tbody> </table> </body> </ HTML >Copy the code

AjaxController

@RequestMapping("/a2")
public List<User> a2(a){
    List<User> userList = new ArrayList<User>();
    // Add data
    userList.add(new User(1."Zhou ZRR"."South"));
    userList.add(new User(2."Week"."South"));
    userList.add(new User(3."Week by week"."South"));
    return userList;
}
Copy the code

Ajax validates the user name

login.jsp

<html>
<head>
    <title>Title</title>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<%--    <script src="${pageContext. Request. ContextPath} / static/js/jquery - 3.5.1 track of js." "></script>--%>
    <script>
        function a1(a) {
            $.ajax({
                url:"${pageContext.request.contextPath}/a3",
              data: {"name": $("#name").val()},
              success:function (data) {
                   // alert(data);
                  // console.log(data);
                  if (data.toString()==='ok'){
                      $("#userinfo").css("color"."green");
                  }else{$("#userinfo").css("color"."red");
                  }
                  $("#userinfo").html(data); }})}function a2(a) {
            $.ajax({
                url:"${pageContext.request.contextPath}/a3",
                data:{"pwd": $("#pwd").val()},
                success:function (data) {
                    //alert(data);
                    // console.log(data);
                    if (data.toString()==='ok'){
                        $("#pwdinfo").css("color"."green");
                    }else{$("#pwdinfo").css("color"."red");
                    }
                    $("#pwdinfo").html(data); }})} < / script > < / head > < body > < p > username: < input type ="text" id="name" onblur="a1()">
    <span id="userinfo"</span> </p> <p> Password: <input type="password" id="pwd" onblur="a2()">
    <span id="pwdinfo"></span>
</p>
</body>
</html>
Copy the code

AjaxController

@RequestMapping("/a3")
public String a3(String name,String pwd){
    String msg="";
    if(name! =null) {// These data should be checked from the database
        if ("admin".equals(name)){
            msg = "ok";
        }else {
            msg = "User name entered incorrectly"; }}if(pwd! =null) {if ("123456".equals(pwd)){
            msg = "ok";
        }else {
            msg = "Incorrect password"; }}return msg;
}
Copy the code

The interceptor

Interceptors in SpringMVC are similar to filters in servlets for pre-processing and post-processing of processors, and developers can define interceptors to implement specific functions.

The difference between filters and interceptors: Interceptors are concrete applications of Aop ideas.

The 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 requested can be intercepted

The interceptor

  • Interceptors are the SpringMVC framework’s own and can only be used if the framework is used
  • Interceptors only intercept methods that access controllers, not static resources

Building environment test

application.xml

<! -- Automatically scan the package, make the annotations under the package valid, unified management by IOC container -->
<context:component-scan base-package="com.zr.controller"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>


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

web.xml

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<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>
Copy the code

Under the web index. The JSP

<body>
<h1>
  <a href="${pageContext.request.contextPath}/user/gologin"</a></h1> <a href="${pageContext.request.contextPath}/user/main"></ a></h1> </body>Copy the code

WEB-INF/jsp/login.jsp

<body>
<form action="${pageContext.request.contextPath}/user/login" method="post"> User name: <input type="text" name="username"> Password: <input type="password" name="password">
    <input type="submit" value="Submit">
</form>
</body>
Copy the code

WEB-INF/jsp/main.jsp

The < body > < % - all of the interface under WEB_INF, only through the servlet or controller access - % > < h1 > home page < / h1 > ${username} ${pageContext. Request. GetSession ("userinfo").getValue(username)}
<p>
    <a href="${pageContext.request.contextPath}/user/goOut"</a> </p> </body>Copy the code

LoginController

package com.zr.controller;

@Controller
@RequestMapping("/user")
public class LoginController {
    @RequestMapping("/main")
    public String main(a){
        return "main";
    }

    @RequestMapping("/gologin")
    public String login(a){
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username, String password, HttpSession session, Model model){
        // Store user information in Session
        session.setAttribute("userInfo",username);
        model.addAttribute("username",username);
        System.out.println(model.getAttribute("username"));
        return "main";
    }

    @RequestMapping("/goOut")
    public String goOut(HttpSession session){
        // Delete user information
        session.removeAttribute("userinfo");
        return "main"; }}Copy the code

Configure the LoginIntercepter

public class LoginIntercepter implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("Login interceptor ==========");
        HttpSession session = request.getSession();
        // The release judgment
        // The login page to pass contains login, namely gologin and login
        if (request.getRequestURI().contains("login")) {return true;
        }

        if (session.getAttribute("userinfo")! =null) {return true;
        }

        // Determine when login is not available
        System.out.println("Return to login page ==========");
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
        return false; }}Copy the code

Configure to application.xml

<! Interceptor configuration -->
<mvc:interceptors>
    <mvc:interceptor>
        <! -- All requests under this request -->
        <mvc:mapping path="/user/**"/>
        <bean class="com.zr.config.LoginIntercepter"/>
    </mvc:interceptor>
</mvc:interceptors>
Copy the code

File upload

CommonsMultipartResolver is configured in SpringMVC.

Set the front-end form method to POST and encType to multipart/form-data.

Description of the encType attribute in the form:

  • Application/X-www =form-urlencoded: Default, only value attribute values in form fields are processed. Forms that use this encoding method will process the values in form fields as URL-coded.
  • Multipart /form-data: This encodings the form data as a binary stream. This encodings the contents of the file specified by the file field as well as the request parameters, without encoding the characters.
  • Text /plain: No letters are encoded except for Spaces that are converted to “+” numbers. This method is suitable for sending files directly from the form.

Add commons-fileupload, commons-io to the poM file of the above project.

index.jsp

<body>

<form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
  <input type="file" name="file">
  <input type="submit" value="upload">
</form>
</body>
Copy the code

Added file upload configuration to application.xml

<! -- File upload configuration -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <! The request encoding must match the pageEncoding property of the JSP in order to read the form correctly. Default isO-8859-1
    <property name="defaultEncoding" value="utf-8"/>
    <! -- Upload file size limit, in bytes,10485760=10M
    <property name="maxUploadSize" value="10485760"/>
    <property name="maxInMemorySize" value="40960"/>
</bean>
Copy the code

controller

package com.zr.controller;

@RestController
public class FileController {
    // @requestParam ("file") encapsulates a file with the name=file attribute into a CommonsMultipartResolver object
    // Upload CommonsMultipartFile
    @RequestMapping("/upload")
    public String Fileupload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        // Get the file name
        String uploadFileName = file.getOriginalFilename();

        // If the file name is empty, go straight back to the home page
        if ("".equals(uploadFileName)){
            return "redirect:/index.jsp";
        }
        System.out.println("Upload file name:"+uploadFileName);

        // Upload path save Settings
        String path = request.getSession().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 save address is:"+realPath);

        InputStream is = file.getInputStream();
        OutputStream os = new FileOutputStream(new File(realPath,uploadFileName));

        // 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"; }}Copy the code

Upload Mode 2

@RequestMapping("/upload2")
    public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        // Upload path Settings
        String path = request.getSession().getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if(! realPath.exists()){ realPath.mkdir(); }// Upload file address
        System.out.println("Upload file save address is:"+realPath);
        // Write the file directly through the method (note)
        file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));
        return "redirect:/index.jsp";
    }
Copy the code

The download file

@RequestMapping("/downLoad")
public String downLoad(HttpServletResponse response,HttpServletRequest request) throws IOException {
    // The address of the image to download
    String path = request.getSession().getServletContext().getRealPath("/upload");
    String fileName = "1.jpg";

    // Set the respons response header
    response.reset();// Set the page to no cache, clear buffer
    response.setCharacterEncoding("utf-8");// Character encoding
    response.setContentType("multipart/form-data");// Binary create data
    // Set the response header
    response.setHeader("Content-Disposition"."attachment; fileName=" + URLEncoder.encode(fileName, "UTF-8"));

    File file = new File(path, fileName);
    InputStream in = new FileInputStream(file);
    ServletOutputStream out = response.getOutputStream();
    //
    int len = 0;
    byte[] buffer = new byte[1024];
    while((len = in.read(buffer)) ! = -1) {
        out.write(buffer, 0, len);
        out.flush();
    }
    out.close();
    in.close();
    return null;
}
Copy the code