Personal java learning route - spring MVC

1, Spring MVC

introduce

  1. Review MVC
    M:model (dao,service)
    5: View view (jsp)
    C:controller (Servlet)

  2. MVVM
    M:model (dao,service)
    5: View view (jsp)
    VM:ViewModel: bidirectional binding (front and back end separated core)

  3. Spring
    We can register all the bean s to be used in Spring MVC with Spring!

  4. SpringMVC

  • Spring MVC is a part of the Spring Framework. It is a lightweight Web framework based on Java to implement MVC
  • Spring's web framework is designed around the dispatcher servlet, which is used to distribute requests to different processors.
  • Like many other MVC frameworks, the Spring MVC framework is request driven and provides requests and other functions around a central Servlet. The dispatcher Servlet is an actual Servlet (inherited from HttpServlet)
  • Spring MVC must be configured with three major components:
    Processor mapper, processor adapter, view parser

rely on

<dependency>
	<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
	<version>5.3.9</version>
</dependency>

2, First spring MVC

After using spring MVC, we can simplify a lot when dealing with page and background interaction.

1. First look at the need to 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.9</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>

Don't forget to add the output configuration when using idea

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

2. Define dispatcher Servlet

ps:springmvc-servlet.xml needs to be created

<?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>
        <!--Associate a springmvc Profile for:[ 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>
    <!--    / Match all requests: (excluding).jsp)-->
    <!--    /* Match all requests:(include.jsp)-->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

3. Create Spring MVC configuration file (custom 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">

    <!--Add process mapper-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
    <!--Add processor adapter-->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
    <!--
        Add view parser: DispatcherServlet Give it to him ModelAndView
        1.Got it ModelAndView Data
        2.Resolved ModelAndView View name for
        3.Splice the view name and find the corresponding view hello
    -->
    <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>

4. Create Controller

Create your own package / com/person/controller under the java of src, and then create the file FirstController

public class FirstController implements Controller {

    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        //ModelAndView models and views
        ModelAndView mv=new ModelAndView();

        //Encapsulate the object and put it 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;
    }
}

At this point, remember to go back to springmvc-servlet.xml and add the configuration

    <!--Handler-->
    <bean id="/hello" class="com.person.controller.FirstController"/>

At this point, the complete springmvc-servlet.xml should be (anti forgetting)

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

    <!--Add process mapper-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
    <!--Add processor adapter-->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
    <!--
        Add view parser: DispatcherServlet Give it to him ModelAndView
        1.Got it ModelAndView Data
        2.Resolved ModelAndView View name for
        3.Splice the view name and find the corresponding view hello
    -->
    <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>

    <!--Handler-->
    <bean id="/hello" class="com.person.controller.FirstController"/>
</beans>

5. Create View

Create / jsp/hello.jsp under "WEB-INF"

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

6. Deployment view

Add / hello to the automatically opened page after deployment

3, controller annotation

The controller class uses annotations

Not required when using annotations

    <!--Handler-->
    <bean id="/hello" class="com.person.controller.FirstController"/>

Change the class of the controller package to

@Controller
@RequestMapping("/hello")
public class HelloController v{
    @RequestMapping("/h1")
    public String hello(Model model){
        //  Encapsulate data
        model.addAttribute("msg","AnnotationTest information");
        return "hello";//Will be processed by the view parser
    }
}

Just.
The corresponding springmvc-servlet.xml can be modified to

<?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
                           http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--Automatically scan the package to make the comments under the specified package effective, and IOC Unified container management-->
    <context:component-scan base-package="com.person.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
            You must register with the 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">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

Web page access hello method
The URL is: http://localhost:3306/ Project address / hello/h1

@Controller annotation

  • @The Controller annotation type is used to declare that the instance of the Spring class is a Controller (three other annotations were learned during IOC: @ Component,@Service,@Repository)

      @Component      assembly
      @Service        service
      @Controller     controller
      @Repository     dao
    

4, Controller controller

  • The complex controller provides the behavior of accessing the application program, which is usually implemented 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

Configuration method of Controller: the first method

There is no need to configure the automatic scanning package and do not process the mapping file, mvc Annotation driven(Processor adapter): 
   <context:component-scan base-package="com.person.controller" />
   <mvc:default-servlet-handler />
   <mvc:annotation-driven />
  • The complete code is as follows:
    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:spring-servlet.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>

spring-servlet.xml -- spring MVC configuration file

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

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

    <bean name="/t1" class="com.person.controller.ControllerTest1"/>

</beans>

Controller class:

//As long as the class implements the Controller interface, it means that this is a Controller
public class ControllerTest1 implements Controller {
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView mv = new ModelAndView();
         mv.addObject("msg","ControllerTest1");
         mv.setViewName("test");
        return mv;
    }
}

View:

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

Post deployment web search: prefix / T1 (see bean of spring-servlet.xml)

Configuration method of Controller: the second method

Use the @ Controller annotation on the class

@Controller//It means that this class will be taken over by Spring. All methods in the annotated class will be parsed by the view parser if the return value is String and there are specific classes that can jump
public class ControllerTest2 {
    @RequestMapping("/t2")
    public String test1(Model model){
        model.addAttribute("msg","ControllerTest2");
        return "test";//This means that you will find the / WEB-INF/jsp/test.jsp file
    }

    @RequestMapping("/t3")
    public String test2(Model model){
        model.addAttribute("msg","test3");
        return "test";//This means that you will find the / WEB-INF/jsp/test.jsp file
    }
}

Then just add the scan package to 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"
       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">
                           
     <!--Automatically scan the package to make the comments under the specified package effective, and IOC Unified container management-->                      
    <context:component-scan base-package="com.person.controller" />

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

Post deployment web search:
http://localhost:3306/ Project address / t2
http://localhost:3306/ Project address / t3
It can be seen that multiple requests can point to the same view, but the results of page output are different. It can be seen from here that the view is reused, and there is a weak coupling relationship between the controller and the view

The second method is extended

Using the second method, you can see that multiple methods can be written in ControllerTest2
You can also further operate on the url

@Controller
@RequestMapping("/c3")
public class ControllerTest3 {
    @RequestMapping("/t1")
    public String test3(Model model){
        model.addAttribute("msg","Test three");
        return "test";
    }
}

Search on the web page after redeployment:
http://localhost:3306/ Project address / c3/t1

5, RestFul style

Concept:
Restful is a style of resource positioning and resource operation, not a standard / protocol, but a style

For example:
Original URL: http://localhost:3306?item=xxx&id=sss
After using this style: http://localhost:3306/item/xxx/id/sss

Operate resources in the traditional way: achieve different effects through different parameters! The method is single, post and get
RESTFul operation resources: different effects can be achieved through different request methods. (the request addresses are the same, but the functions can be different) (GET POST PUT DELETE)

Comparative test

1. Before

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

Web page input: http://localhost:9527/add?a=1&b=2
The output is 3
2. Now RestFul

Use the @ PathVariable annotation in Spring to bind the value of the method parameter to a URL template variable

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

URL: http://localhost:9527/add/1/2
The output is 3

RestFul request method

In RestFul style, if the front-end web form submission method is inconsistent with the back-end, an exception will occur

 @RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.DELETE)

ps: here, value can be replaced by path (name cannot be used, name is the name of mapping, and value and path are aliases to each other)

You can also request the corresponding label:

@RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.GET)
@RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.DELETE)
@DeleteMapping("/add/{a}/{b}")
@GetMapping("/add/{a}/{b}")
@Controller
public class RestFulController {
//    @RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.GET)
//    @RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.DELETE)
//    @GetMapping("/add/{a}/{b}")
//    @DeleteMapping("/add/{a}/{b}")
    @PostMapping("/add/{a}/{b}")
    public String test(@PathVariable int a,@PathVariable int b, Model model){
        model.addAttribute("msg","POST Method request result is"+(a+b));
        return "test";
    }

    @GetMapping("/add/{a}/{b}")
    public String test2(@PathVariable int a,@PathVariable int b, Model model){
        model.addAttribute("msg","GET Method returns the result"+(a+b));
        return "test";
    }
}

6, Jump

After setting ModelAndView object

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

ServletAPI

By setting up the servlet API, we don't need a view parser

  • 1. Output through HttpServletResponse
  • 2. Redirect through HttpServletResponse
  • 3. Forward through HttpServletResponse

Servlet redirection

Use the second method of "IV. Controller" above to create a template

@Controller
public class ModelTest1 {
    @RequestMapping("/m1/t1")
    public String test(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        System.out.println(session.getId());
        return "test";
    }
}

You can use jump redirection in HttpServlet (requires view parser)

Forwarding and redirection with spring MVC - no view parser required

Remove the view parser from 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"
       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">


    <context:component-scan base-package="com.person.controller" />
</beans>

Test example:

@Controller
public class ModelTest1 {

    @RequestMapping("/m1/t1")
    public String test(HttpServletRequest request, HttpServletResponse response){

        HttpSession session = request.getSession();
        System.out.println(session.getId());

        return "test";
    }

    @RequestMapping("/m2/t1")
    public String test1(){
        //Jump
        return "/jumpTest.jsp";
    }

    @RequestMapping("/m2/t2")
    public String test2(){
        //Jump
        return "forward:/WEB-INF/jsp/test.jsp";
    }

    @RequestMapping("/m2/t3")
    public String test3(){
        //redirect
        return "redirect:/WEB-INF/jsp/test.jsp";
    }
}

7, Process submitted data

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

Submit data: http://localhost:9527/t1?name=lisi

public class ModelTest1 {
    @RequestMapping("/t1")
    public String test1(String name, Model model){
        //1. Accept front-end parameters
        System.out.println("The parameters received from the front end are:"+name);
        //2. Pass the returned result to the front end
        model.addAttribute("msg",name);
        return "test";
    }
}

Background output: lisi

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

Annotate method parameters with @ RequestParam("username") annotation
Submit data: http://localhost:9527/t2?username=lisi

@Controller
public class ModelTest1 {
    @RequestMapping("/t2")
    public String test2(@RequestParam("username") String name, Model model){
        //1. Accept front-end parameters
        System.out.println("The parameters received from the front end are:"+name);
        //2. Pass the returned result to the front end
        model.addAttribute("msg",name);
        return "test";
    }
}

Background output: lisi

3. What is submitted is an object

Submit data: http://localhost:9527/t3? id=1&name=lisi&age=18

@Controller
public class ModelTest1 {
    //The front end receives an object
    /*
     1.Accept the parameters passed by the front-end user, judge the name of the parameter, and assume that the name is directly on the method and can be used directly
     2.Suppose a User object is passed, which matches the field names in the User object. If the names are the same, it is OK. Otherwise, it cannot be matched
     */
    @RequestMapping("/t3")
    public String test3(User user){
        System.out.println(user);
        return "test";
    }
}

Background output: User(id=1, name=lisi, age=18)

If the parameter name submitted by the front end does not match the property name of the class
front end: http://localhost:9527/t3? id=1&username=lisi&age=18
Back end output: User(id=1, name=null, age=18)

8, Data display to front end

First: through ModelAndView

Initial approach

public class HelloController implements Controller {
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg","SecondHello");
        mv.setViewName("testJsp");
        return mv;
    }
}

The second is through ModelMap

It inherits LinkedMap. Model is a simplified version of ModelMap and mainly uses model. At present, ModelMap is no different from model

Third: through Model

Example of the second method above:

@Controller
public class ModelTest1 {
    @RequestMapping("/t2")
    public String test2(@RequestParam("username") String name, Model model){
        //1. Accept front-end parameters
        System.out.println("The parameters received from the front end are:"+name);
        //2. Pass the returned result to the front end
        model.addAttribute("msg",name);
        return "test";
    }
}

Comparison of the three

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

9, Garbled code

example

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>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-servlet.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>
    
</web-app>

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


    <context:component-scan base-package="com.person.controller" />

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

controller:

@Controller
public class ModelTest1 {

    @PostMapping("/t1")
    public String test1(String name, Model model){
        System.out.println(name);
        model.addAttribute("msg",name);
        return "test";
    }
}

Front end page (same level as index.jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/t1" method="post">
    <input type="text" name="name">
    <input type="submit" value="Submit button">
</form>
</body>
</html>

Front end page test.jsp (under / WEB-INF/jsp /)

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

test

Test description

Enter "invincible" in the form of jsp page“

After submitting to Controller

Console output:???

Echo to web page - • Œ “

It can be seen that when java obtains the page submission data, it has been garbled

Solution 1 - write your own filter

Create the EncodingFilter class under the com.person.filter package

public class EncodingFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        chain.doFilter(request,response);
    }

    public void destroy() {

    }
}

Then go to web.xml to configure the filter

    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>com.person.filter.EncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Test again

Note: < URL pattern > / * < / url pattern >, to filter all pages, including JSPS, use / * instead of/

Solution 2 - use spring MVC's garbled filter

Just configure it directly

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

Universal solution

Solve the problem of transferring data from web pages to java Universal solution to garbled Code:
Because web pages transmit data ISO-8859-1,Just translate this into Chinese
byte[] bytes=name.getBytes("ISO-8859-1");
name=new String(bytes,"UTF-8");

10, JSON

  • This is the era of front and back separation

The backend deploys the backend, provides interfaces, and provides data:

The front end is deployed independently and is responsible for rendering the data of the back end:

The most commonly used JSON data format for front and back end data transmission

Generating json objects in Java

Maven imports JSON processor jar package

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

Processing with jar package

public class A{
 @RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
    @ResponseBody//If you annotate this annotation, you will not go to the view parser and will directly return a string
    public String json1(){

        //jackson. ObjectMapper
        ObjectMapper mapper=new ObjectMapper();

        //create object
        User user=new User(1,"WangTwo ",18);
        String str=null;
        try {
            str=mapper.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return str;
    }
}

@RestController is used on the class. If the annotation is marked, it will not go to the view parser and will directly return a string instead of @ control

@ResponseBody is used on the method. If the annotation is marked, it will not go to the view parser and will directly return a string for use with @ control

Products is used to deal with the problem of garbled code

Microsoft AppLocale

The encoding can be specified uniformly through spring configuration
Add a message StringHttpMessageConverter transformation configuration in spring MVC

<!--Solve the problem of garbled code-->
<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>

FastJson.jar

fastjson.jar is a package developed by Ali for Java development. It can easily convert json objects into JavaBean objects,
Realize the transformation of JavaBean object and json string, and realize the transformation of json object and json string.

fastjson has three main classes:

  • JSONObject represents a json object
  • JSONArray represents an array of json objects
  • JSON represents the conversion of JSONObject and JSONArray

Guide Package

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.75</version>
</dependency>

11, Spring MVC interceptor

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

Brief introduction to interceptor

We can implement the HandlerInterceptor interface to write our own interceptors

public class MyInterceptor implements HandlerInterceptor {
    //return true; execute the next interceptor and release
    //return false; do not execute the next interceptor
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("=======Before treatment======");
        return true;
    }

    //The latter two are similar to logs
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //System.out.println("=========== after processing ======");
    }

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

Then configure the interceptor in applicationContext.xml

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

12, File upload and download

Introduction to core process

1. Configure jar

<dependencies>
    <!--File upload-->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.3</version>
    </dependency>
    <!--Higher version servlet-api-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
</dependencies>

2. Front end html

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

3.applicationContext.xml configuration

<!--File upload configuration-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--Request encoding format, must be and jsp of pageEncoding Property is consistent so that the contents of the form can be read correctly. The default is ISO-8859-1-->
    <property name="defaultEncoding" value="utf-8"/>
    <!--Maximum upload file size,In bytes-->
    <property name="maxUploadSize" value="10485760"/>
    <property name="maxInMemorySize" value="40960"/>
</bean>

4. Write fileController.java

Complete instance

pom.xml import dependency

    <dependencies>
        <!--File upload-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
        <!--Higher version servlet-api-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>
    </dependencies>

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>

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

    <context:component-scan base-package="com.person.controller"/>
    <mvc:default-servlet-handler /><!--Static resource filtering, similar to jQuery Such static resource import must be used-->
    <mvc:annotation-driven/>

    <!--solve JSON Garbled problem 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>

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

    <!--File upload configuration-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--Request encoding format, must be and jsp of pageEncoding Property is consistent so that the contents of the form can be read correctly. The default is ISO-8859-1-->
        <property name="defaultEncoding" value="utf-8"/>
        <!--Maximum upload file size,In bytes-->
        <property name="maxUploadSize" value="10485760"/>
        <property name="maxInMemorySize" value="40960"/>
    </bean>
</beans>

Create the FileController class under the java.com.person.controller package

@RestController
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, return to the first page
        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";
   }

   /*
        Use file.Transto to save the uploaded file
    */
   @RequestMapping("/upload2")
   public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
       //Upload path save configuration
       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";
   }



    @RequestMapping("/download")
    public String downloads(HttpServletResponse response,HttpServletRequest request) throws IOException {
       //Address of the picture to download
        String path=request.getServletContext().getRealPath("/upload");
        String fileName="1.png";

        //1. Set the response header
        response.reset();//Set the page not to be cached, and clear the buffer
        request.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 -- input stream
        OutputStream out=response.getOutputStream();

        byte[] buffer=new byte[1024];
        int index=0;
        while ((index=input.read(buffer))!=-1){
            out.write(buffer,0,index);
            out.flush();
        }
        out.close();
        input.close();
        return null;
    }
}

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <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>
</html>

Here's the test
After this code is deployed, the uploaded file on the home page can be seen in the out output
The download must also be an out/upload/1.png file before you can use / download to download

After creating the project, the web page can't be opened. Look at this first!!

idea needs to create lib package manually (dependency)


Just apply. Note:
After that, you must repeat the above steps every time you add a new dependency, otherwise the dependency will not take effect

Tags: Java Spring MVC

Posted on Sat, 30 Oct 2021 15:34:54 -0400 by TehManz