What is SpringMVC?

Spring MVC is part of the Spring Framework, a lightweight Web Framework that implements MVC based on Java.

Look at the official document: docs. Spring. IO/spring/docs…

Spring MVC features:

  1. Lightweight and easy to learn
  2. Efficient, request-response-based MVC framework
  3. Good compatibility with Spring, seamless combination
  4. Convention over Configuration
  5. Powerful functions: RESTful, data validation, formatting, localization, theme, etc
  6. Concise and flexible

Spring’s Web framework is designed around the DispatcherServlet [Scheduling Servlet].

The role of the DispatcherServlet is to distribute requests to different processors. Starting with Spring 2.5, users of Java 5 and above can use annotation-based development, which is very simple;

DispatcherServlet

The role of the DispatcherServlet is to distribute requests to different processors. Starting with Spring 2.5, users of Java 5 and above can adopt an annotation-based controller declaration.

The DispatcherServlet is an actual Servlet (it inherits from the HttpServlet base class).

The principle of SpringMVC:

Blocked by front controller when a request to the request, according to the request parameters generated proxy, find request corresponding actual controller, the controller processes the request, create the data model, database access, the model response to the center controller, the controller using the model and the view render view as a result, the results back to the center controller, and then return the results to the requester.

A complete flow chart of SpringMVC:

Solid lines represent technologies provided by the SpringMVC framework that do not need to be implemented by the developer, and dotted lines indicate that they do.

Brief analysis of the execution process:1.The DispatcherServlet represents the front controller and is the control center of the entire SpringMVC. The user makes the request, the DispatcherServlet receives the request and intercepts it. Let's assume the requested URL is: HTTP://localhost:8080/SpringMVC/helloThe url above is broken into three parts: HTTP://localhost:8080 ------> Domain name of the serverSpringMVC ------> Web site deployed on the server Hello ------> indicates that the controller is analyzed, as shown in the url above: The request is located at the server localhost:8080SpringMVC site on the Hello controller.2.HandlerMapping maps processors. DispatcherServlet call HandlerMapping HandlerMapping, according to the request url search Handler.3.HandlerExecution refers to a specific Handler whose main function is to look for a controller based on the URL, as shown in the preceding example: Hello.4.HandlerExecution passes the parsed information to the DispatcherServlet, such as resolving controller mappings.5.A HandlerAdapter represents a processor adapter that executes handlers according to specific rules.6.The Handler lets the specific Controller execute.7.The Controller returns the detailed execution information to the HandlerAdapter, such as ModelAndView.8.The HandlerAdapter passes the logical name or model of the view 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 resolved logical view name to the DispatcherServlet.11.The DispatcherServlet invokes the specific view based on the result of the view resolved by the view parser.12.The final view is presented to the user.Copy the code

The first MVC program

Configure version

Make sure you import SpringMVC dependencies!

Configure web.xml and register the DispatcherServlet

<? 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 DispatcherServlet--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! -- Relate aspringmvcConfiguration file: [servlet-name] -servlet.xml-->
       <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:springmvc-servlet.xml</param-value>
       </init-param> <! -- Start level -1--> <load-on-startup< / a > 1load-on-startup>
   </servlet> <! --/ match all requests; (Not included.jsp) -- -- > <! --/* Match all requests; (including.jsp) - > <servlet-mapping>
       <servlet-name>springmvc</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>

</web-app>

Copy the code

Write the SpringMVC configuration file


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

Copy the code

Add processing mapper (omitted)

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

Copy the code

Add processor adapter (omitted)

<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
Copy the code

Add a view parser

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


Copy the code

To write that we want to manipulate the business Controller, either implement the Controller interface or add annotations; You need to return a ModelAndView, load the data, and seal the view;

package zwt.controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Note: Here we import the Controller interface first
public class HelloController implements Controller {

   public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
       //ModelAndView ModelAndView
       ModelAndView mv = new ModelAndView();

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

Give your class to the SpringIOC container and register the bean

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

ok

Maven may have resource filtering issues

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


Copy the code

Annotated edition

Configure web. XML


      
<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. The registration servlet -- -- >
   <servlet>
       <servlet-name>SpringMVC</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <! The SpringMVC configuration file is initialized by specifying the location of the SpringMVC configuration file -->
       <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:springmvc-servlet.xml</param-value>
       </init-param>
       <! -- Startup sequence, the smaller the number, the earlier the startup -->
       <load-on-startup>1</load-on-startup>
   </servlet>

   <! -- All requests are intercepted by SpringMVC -->
   <servlet-mapping>
       <servlet-name>SpringMVC</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>

</web-app>


Copy the code

Add the Spring MVC configuration file


      
<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 packages to validate the annotations under the specified package, managed by the IOC container -->
   <context:component-scan base-package="nuc.ss.controller"/>
   <! -- Let Spring MVC not handle static resources -->
   <mvc:default-servlet-handler />
   <! - support the MVC annotation driven @ RequestMapping commonly used in spring annotations to complete the mapping relationship To make the @ RequestMapping annotations to take effect Must be registered DefaultAnnotationHandlerMapping with the context And a AnnotationMethodHandlerAdapter instance this two instances in class level and treatment level. The annotation driven configuration helps us automate the injection of both instances. -->
   <mvc:annotation-driven />

   <! -- View parser -->
   <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>

</beans>


Copy the code

Create a Controller

package zwt.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

// @controller is for the Spring IOC container initialization automatically scan;
// @requestMapping is to map the request path. In this case, it should be /HelloController/hello;
@Controller
@RequestMapping("/HelloController")
public class HelloController {

   // Real access address: project name /HelloController/hello
   @RequestMapping("/hello")
   public String sayHello(Model model){
       // Add the property MSG and value to the model, which can be fetched and rendered in the JSP page
       model.addAttribute("msg"."hello,SpringMVC");
       //web-inf/jsp/hello.jsp
       return "hello"; }}Copy the code

RestFul and Controller

Implementing the Controller interface

Controller is an interface in the org. Springframework. Web. Servlet. MVC package, the interface is only one way;

// The class that implements this interface gets the controller functionality
public interface Controller {
   // Processes the request and returns a model and view object
   ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception;
}
Copy the code

Description:

  • Implementing the interface Controller is an older way to define a Controller
  • Disadvantages: there is only one method in a Controller. If you want more than one method, you need to define more than one Controller. It’s a tricky way to define it;

Use the annotation @controller

<! <context:component-scan base- <context:component-scan base-package="zwt.controller"/>

//@Controller annotated classes are automatically added to the Spring context
@Controller
public class ControllerTest2{

   // Map the access path
   @RequestMapping("/t2")
   public String index(Model model){
       //Spring MVC will automatically instantiate a Model object for passing values to the view
       model.addAttribute("msg"."ControllerTest2");
       // Return to the view position
       return "test"; }}Copy the code

RequestMapping

The @requestMapping annotation is used to map urls to a controller class or a specific handler method. Can be used on a class or method. On a class, all methods in the class that respond to requests have that address as the parent path.

RestFul style

Restful is a style for locating and manipulating resources. It’s not a standard or a protocol, just a style. Software designed based on this style can be more concise, more hierarchical, and easier to implement mechanisms such as caching.

Contrast:

Traditional way to operate resources: through different parameters to achieve different effects! Methods a single, post and get http://127.0.0.1/item/queryItem.action? Id = 1 query, GET new http://127.0.0.1/item/saveItem.action, POST updated http://127.0.0.1/item/updateItem.action, POST http://127.0.0.1/item/deleteItem.action? Id =1 Delete,GET or POST Use RESTful operation resources: different request methods can be used to achieve different effects! 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 added,POST http://127.0.0.1/item updated,PUT http://127.0.0.1/item/1 DELETE, DELETECopy the code
// Map the access path
@RequestMapping("/add/{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 for passing values to the view
   model.addAttribute("msg"."Result:"+result);
   // Return to the view position
   return "test";

}
Copy the code

Result jump mode

ModelAndView

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

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

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

public class ControllerTest1 implements Controller {

   public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
       // Return a model view object
       ModelAndView mv = new ModelAndView();
       mv.addObject("msg"."ControllerTest1");
       mv.setViewName("test");
       returnmv; }}Copy the code

ServletAPI

By setting the ServletAPI, no view resolver is required:

  1. Output via HttpServletResponse
  2. Redirection via HttpServletResponse
  3. The forwarding is implemented through HttpServletResponse
@Controller
public class ResultGo {

   @RequestMapping("/result/t1")
   public void test1(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
       rsp.getWriter().println("Hello,Spring BY servlet API");
  }

   @RequestMapping("/result/t2")
   public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
       rsp.sendRedirect("/index.jsp");
  }

   @RequestMapping("/result/t3")
   public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception {
       / / forwarding
       req.setAttribute("msg"."/result/t3");
       req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp); }}Copy the code

SpringMVC

Forward and redirect via SpringMVC – no view resolver required;

@Controller
public class ResultSpringMVC2 {
   @RequestMapping("/rsm2/t1")
   public String test1(a){
       / / forwarding
       return "test";
  }

   @RequestMapping("/rsm2/t2")
   public String test2(a){
       / / redirection
       return "redirect:/index.jsp";
       //return "redirect:hello.do"; // Hello. Do for another request /}}Copy the code

The data processing

Processing submitted data

1. The submitted domain name is the same as the parameter name of the processing method

Submit data: http://localhost:8080/hello? name=zwt

Treatment method:

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

Copy the code

Background output: ZWT

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

Submit data: http://localhost:8080/hello? username=zwt

Treatment method:

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


Copy the code

Background output: ZWT

3. Submit an object

The submitted form field is required to be the same as the property name of the object

  1. Entity class

    public class User {
       private int id;
       private String name;
       private int age;
       / / structure
       //get/set
       //tostring()
    }
    
    
    Copy the code
  2. Submit data: http://localhost:8080/mvc04/user? name=zwt&id=1&age=15

  3. Treatment method:

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

User {id=1, name= ‘ZWT’, age=15}

Note: If an object is used, the front end must pass the same parameter name as the object name, otherwise null.

Data is displayed to the front end

First: through ModelAndView

public class ControllerTest1 implements Controller {

   public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
       // Return a model view object
       ModelAndView mv = new ModelAndView();
       mv.addObject("msg"."ControllerTest1");
       mv.setViewName("test");
       returnmv; }}Copy the code

Second: through ModelMap

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

Third: by Model

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

contrast

For starters, the simple difference is:

Model has only a few methods that are only suitable for storing data, which simplifies novice users' operation and understanding of Model objects. ModelMap inherits LinkedMap. In addition to implementing some methods of its own, ModelMap also inherits the methods and features of LinkedMap. ModelAndView can store data and set the returned logical view to control the jump of the presentation layer.Copy the code

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

Json interactive processing

{"name": "zwt"}
{"age": "2"}
{"sex": "Male"}
Copy the code

Test this: partial steps

// We use Jackson. To use Jackson, 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.98.</version>
</dependency>

/ / for springmvc configuration files to add a message StringHttpMessageConverter transformation configuration
<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>


@RestController
public class UserController {
   @RequestMapping(value = "/j1")
   public String json1(a) throws JsonProcessingException {
       // Create an object mapper for Jackson to parse the data
       ObjectMapper mapper = new ObjectMapper();
       // Create an object
       User user = new User(1."zwt".2);
       // Parse our object into JSON format
       String str = mapper.writeValueAsString(user);
       returnstr; }}Copy the code

Ajax

  • AJAX = Asynchronous JavaScript and XML.
  • AJAX is a technology that allows you to update parts of a web page without having to reload the entire page.
  • Ajax is not a new programming language, but rather a technology for creating better, faster, and more interactive Web applications.

You can do this with AJAX:

  • When registering, enter the user name to automatically check whether the user already exists.
  • The user name or password is incorrect during login
  • When deleting a data row, the row ID is sent to the background, and the background is deleted in the database. After the database is successfully deleted, the data row is also deleted in the DOM of the page.
  • … , etc.

The Baidu interface Demo is obtained

<! DOCTYPEHTML>
<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>

       // step 2
       // Define demo functions (analyze interface, data)
       function demo(data){
           var Ul = document.getElementById('ul');
           var html = ' ';
           // Add the content if the search data exists
           if (data.s.length) {
               // The hidden ul is displayed
               Ul.style.display = 'block';
               // Append the searched data loop to li
               for(var i = 0; i<data.s.length; i++){ html +='<li>'+data.s[i]+'</li>';
              }
               // write the loop's li to ulUl.innerHTML = html; }}// 1. Step 1
       window.onload = function(){
           // Get the input box and ul
           var Q = document.getElementById('q');
           var Ul = document.getElementById('ul');

           // Event when the mouse is raised
           Q.onkeyup = function(){
               // If the input box is not equal to empty
               if (this.value ! =' ') {
                   * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
                   // Create a label
                   var script = document.createElement('script');
                   // Give SRC the address to cross the domain
                   // Here is the cross-domain address to request I write is baidu search cross-domain address
                   script.src = 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+this.value+'&cb=demo';
                   // Append the composed 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>


Copy the code

The interceptor

An overview of the

  • SpringMVC’s processor interceptor is similar to the Filter in Servlet development for pre – and post-processing of the processor.
  • Developers can define their own interceptors to implement specific functions.

The difference between filters and interceptors: Interceptors are a concrete application of AOP ideas.

The filter

  • Part of the servlet specification, which can be used by any javaweb project
  • After /* is configured in url-pattern, all resources to be accessed can be intercepted

The interceptor

  • The interceptors are the SpringMVC framework’s own and can only be used by projects that use the Framework
  • The interceptor will only intercept the controller methods accessed, not JSP/HTML/CSS /image/js

Custom interceptors

Write an interceptor (you must implement the HandlerInterceptor interface)

package zwt.config;

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 {
    //return true; Execute the next interceptor, release
    //return false; Do not execute the next interceptor, intercept
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("=========== before processing ===========");
        return true;
    }
    / / log
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("=========== after treatment ===========");

    }
    / / log
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("= = = = = = = = = = = clear = = = = = = = = = = ="); }}Copy the code

Configure interceptors in the SpringMVC configuration file

<! -- Interceptor Configuration -->
<mvc:interceptors>
    <mvc:interceptor>
        <! -- Include all requests below this request -->
        <mvc:mapping path="/ * *"/>
        <bean class="zwt.config.MyInterceptor"/>
    </mvc:interceptor>

</mvc:interceptors>
Copy the code

Write a Controller that receives requests

package zwt.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @GetMapping("/t1")
    public String test(a) {
        System.out.println("TestController.test");
        return "ok"; }}Copy the code

Authenticate user login (authenticate user)

Implementation approach

  1. You have a login page, and you need to write a controller access page.

  2. The login page has a submit form action. It needs to be handled in controller. Check whether the user name and password are correct. If correct, write the user information to the session. Log in successfully.

  3. Intercept the user request and determine whether the user is logged in. If the user is logged in. If the user does not log in, the login page is displayed

  4. Write a login page login. JSP

    <%@ page contentType="text/html; charset=UTF-8" language="java" %><html>
    <head>
        <title>The login</title>
    </head>
    <body><%-- All pages or resources under web-INF are accessible only through the controller or Servlet --%><h1>The login page</h1>
    
    <form action="${pageContext.request.contextPath}/user/login" method="post">User name:<input type="text" name="username">Password:<input type="text" name="password">
        <input type="submit" value="Submit">
    </form>
    </body>
    </html>
    
    
    123456789101112131415161718
    Copy the code
  5. Write a Controller to handle requests

    @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(HttpSession session, String username, String password, Model model) {
    
            // Store user information in session
            session.setAttribute("userLoginInfo",username);
            model.addAttribute("password",password);
            model.addAttribute("username",username);
            return "main";
        }
    
        @RequestMapping("/goOut")
        public String goOut(HttpSession sessionl) {
            sessionl.removeAttribute("userLoginInfo");
            return "login"; }}Copy the code
  6. Write a successful login page, main.jsp

    <%@ page contentType="text/html; charset=UTF-8" language="java" %><html>
    <head>
        <title>Home page</title>
    </head>
    <body>
    <h1>Home page</h1>
    <span>${password}</span>
    <span>${username}</span>
    
    <p>
        <a href="${pageContext.request.contextPath}/user/goOut">The cancellation</a>
    </p>
    
    </body>
    </html>
    
    Copy the code
  7. Test the jump on the index page! Start Tomcat test, you can enter the home page without login!

    <%@ page contentType="text/html; charset=UTF-8" language="java" %><html>
    <head>
      <title>index</title>
    </head>
    <body>
    <h1><a href="${pageContext.request.contextPath}/user/goLogin">The login page</a></h1>
    <h1><a href="${pageContext.request.contextPath}/user/main">Home page</a></h1>
    
    </body>
    </html>
    
    Copy the code
  8. Write a user login interceptor

    package zwt.config;
    
    import org.springframework.web.servlet.HandlerInterceptor;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    public class LoginInterceptor implements HandlerInterceptor {
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            HttpSession session = request.getSession();
            // Release: Determine when to log in
    
            // The login page is also allowed
            if (request.getRequestURI().contains("goLogin")) {
                return true;
            }
            if (request.getRequestURI().contains("login")) {
                return true;
            }
            if (session.getAttribute("userLoginInfo") != null) {
                return true;
            }
            // Determine when there is no login
            request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
            return false; }}Copy the code
  9. Register the interceptors in the Springmvc configuration file

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

File upload and download

The preparatory work

  • The SpringMVC context is not equipped with MultipartResolver by default, so it cannot handle file uploadings by default. If you want to use Spring’s file upload capabilities, you need to configure MultipartResolver in context.
  • Front-end form requirements: In order to upload files, the form method must be set to POST and encType must be set to Multipart /form-data. Only in this case will the browser send the selected file to the server as binary data;

A more detailed description of the encType attribute in the form:

  • Application /x-www=form-urlencoded: Default mode, processing only the value attribute values in the form field. Forms using this encoding mode will process the values in the form field into URL encoding mode.
  • Multipart /form-data: This encoding processes the form data as a binary stream. This encoding encapsulates the contents of the file specified by the file field into the request parameters, and does not encode characters.
  • Text /plain: No characters are encoded except for Spaces to be converted to “+” numbers, which is suitable for sending messages directly through the form.
<form action="" enctype="multipart/form-data" method="post">
   <input type="file" name="file"/>
   <input type="submit">
</form>
Copy the code

File upload

  1. Maven will automatically import its dependency package, Commons -fileupload.

    <! -- File upload -->
    <dependency>
       <groupId>commons-fileupload</groupId>
       <artifactId>commons-fileupload</artifactId>
       <version>1.3.3</version>
    </dependency>
    <! --servlet-api import higher version -->
    <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>javax.servlet-api</artifactId>
       <version>4.0.1</version>
    </dependency>
    Copy the code
  2. Configure bean: multipartResolver

    Bena must have id: multipartResolver, otherwise it will report error 400!

    <! -- File upload configuration -->
    <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
       <! -- The encoding of the request, which must be consistent with the pageEncoding attribute of the jSP in order to read the content of the form correctly, defaults to ISO-8859-1 -->
       <property name="defaultEncoding" value="utf-8"/>
       <! -- Maximum size of a file to be uploaded, in bytes (10485760=10M) -->
       <property name="maxUploadSize" value="10485760"/>
       <property name="maxInMemorySize" value="40960"/>
    </bean>
    Copy the code

    CommonsMultipartFile:

    • String getOriginalFilename() : obtains the original name of the uploaded file
    • InputStream getInputStream() : Obtains a file stream
    • Void transferTo(File dest) : saves the uploaded File to a directory File
  3. Write the front page

    <form action="/upload" enctype="multipart/form-data" method="post">
     <input type="file" name="file"/>
     <input type="submit" value="upload">
    </form>
    Copy the code
  4. Controller

    package zwt.controller;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.commons.CommonsMultipartFile;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.net.URLEncoder;
    
    @RestController
    public class FileController {
    
        // @requestparam ("file") wraps the name=file control into a CommonsMultipartFile object
        // Upload CommonsMultipartFile as an array
        @RequestMapping("/upload")
        public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {
    
            // Get the file name: file.getoriginalFilename ();
            String uploadFileName = file.getOriginalFilename();
    
            // If the file name is empty, go straight to the home page!
            if ("".equals(uploadFileName)){
                return "redirect:/index.jsp";
            }
            System.out.println("Upload filename:"+uploadFileName);
    
            // Upload path To save the 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 save address:"+realPath);
    
            InputStream is = file.getInputStream(); // File input stream
            OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); // File output stream
    
            // Read and 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

Use file.Transto to save the uploaded file

  1. Writing the Controller

    /* * Use file.Transto to save the uploaded file */
    @RequestMapping("/upload2")
    public String  fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
    
       // Upload path To save the 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 save address:"+realPath);
    
       // Write directly to the file using the CommonsMultipartFile method.
       file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
    
       return "redirect:/index.jsp";
    }
    
    
    Copy the code

File download

File download steps:

  1. Set the Response response header
  2. Read a file – InputStream
  3. Write a file – OutputStream
  4. Perform operations
  5. Close flow (on and off first)

Code implementation:

@RequestMapping(value="/download")
public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
   // The location of the image to download
   String  path = request.getServletContext().getRealPath("/upload");
   String  fileName = "Basic syntax.jpg";

   //1. Set response header
   response.reset(); // Set the page not to be cached and clear the buffer
   response.setCharacterEncoding("UTF-8"); // Character encoding
   response.setContentType("multipart/form-data"); // Binary transfer data
   // Set the 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 file -- output stream
   OutputStream out = response.getOutputStream();

   byte[] buff =new byte[1024];
   int index=0;
   //4. Perform the write operation
   while((index= input.read(buff))! = -1){
       out.write(buff, 0, index);
       out.flush();
  }
   out.close();
   input.close();
   return null;
}
Copy the code

The front end

<a href="/download">Click on the download</a>
Copy the code