Study notes of spring MVC

Introduction to spring MVC

Official documents: https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc

First try spring MVC

Three major components that must be configured to use spring MVC:

Process mapper, process adapter, view parser

schematic diagram

Operation steps

  1. Import Java Web and Spring dependencies

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.15</version>
        </dependency>
    
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
    </dependencies>
    <!--stay build Medium configuration resources,To prevent the failure of resource export-->
        <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. Create spring MVC servlet under the resources package XML spring 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">
    
        <!--    Processor mapper-->
        <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
        <!--    Processor adapter-->
        <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
    
    <!--    View interpreter: DispatcherServlet Give it to him ModelAndView
    	1.Got it ModelAndView Data
        2.analysis ModeAndView View name
        3.Splice view name/WEB-INF/jsp/hello.jsp
        4.Render the data to this view
    -->
        <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!--        prefix-->
            <property name="prefix" value="/WEB-INF/jsp/"/>
    <!--        suffix-->
            <property name="suffix" value=".jsp"/>
        </bean>
    
    <!--    Hander-->
    
  3. Configure web XML, register DispatcherServlet

    <!--    1.register DispatcherServlet-->
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--        Association should 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: (including.jsp)-->
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
  4. Create HelloController class

    public class HelloController implements Controller {
        @Override
        public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    //        ModelAndView models and views
            ModelAndView mv = new ModelAndView();
    //        Encapsulate the object and put it in ModelAndView. Model
            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;
        }
    }
    
  5. In spring MVC servlet Inject HelloController class into XML

    <bean id="/hello" class="com.lzj.controller.HelloController"/>
    
  6. Create a jsp package under the WEB-INF package and create hello jsp file

    ${requestScope.msg}
    
  7. Run TomCat

Possible problems

If 404 occurs during the visit:

  1. Check the console output to see if there is any missing jar package.

  2. If the jar package exists and the display cannot be output, add lib dependency in the project release of IDEA!

  3. Restart Tomcat to solve the problem!

Developing spring MVC with annotations

Operation steps

Code steps

  1. Create a new web project

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.15</version>
        </dependency>
    
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
    </dependencies>
    <!--stay build Medium configuration resources,To prevent the failure of resource export-->
        <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. Import related dependencies and jar packages

  3. Create spring MVC servlet under the resources package XML spring configuration file * * (always available)**

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--    Automatically scan the package to make the comments under the specified package effective, and IOC Unified container management-->
        <context:component-scan base-package="com.lzj.controller"/>
    <!--    Give Way SpringMVC Do not process static resources-->
        <mvc:default-servlet-handler/>
    <!--    Automatic completion BeanNameUrlHandlerMapping and SimpleControllerHandlerAdapter Instance injection-->
        <mvc:annotation-driven/>
    
    <!--    view resolver -->
        <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!--        prefix-->
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <!--        suffix-->
            <property name="suffix" value=".jsp"/>
        </bean>
    </beans>
    
  4. Write web XML, register DispatcherServlet

    <!--    1.register DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--        Association should 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: (including.jsp)-->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
  5. Create the corresponding control class, controller

    @Controller: load this class into Spring's Bean factory as a controller and let the SpringIOC container automatically scan it when initializing

    @RequestMapping: mapping the request address and the real access address

    @Controller
    //If you use @ RequestMapping("h1") to the method, the access path is / WEB-INF / JSP / H1 / Hello jsp
    //@RequestMapping("h1")
    public class HelloController {
        //Real access address
        @RequestMapping("/hello")
        public String hello(Model model){//Method is declared to bring the data in the Action to the view
            //Encapsulate data and add attribute msg and value to the model, which can be taken out and rendered in jsp page
            model.addAttribute("msg","Hello,SpringMVCAnnotation");
            return "hello";//Will be processed by the view parser: / WEB-INF / JSP / Hello jsp
        }
    }
    
  6. Create a jsp package under the WEB-INF package and create hello jsp file

    ${msg}
    
  7. Run TomCat for testing

RestFull style

  • security

  • All values are transmitted via /

  • Different results are achieved through different methods (POST, DELETE, PUT, GET)

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

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

Original writing

Pass? Value transmission

@Controller
public class RestFullController {
    //customary: http://localhost:8080/add?a=1&b=2
    @RequestMapping("/add")
    public String test1(int a, int b, Model model){
        int res=a+b;
        model.addAttribute("msg","The result is"+res);
        return "test";
    }
}

Test:

Recommended writing method

Common writing

Pass / transfer value

The annotation @ PathVariable needs to be added

@Controller
public class RestFullController {
    //customary: http://localhost:8080/add?a=1&b=2
    //RestFul:http://localhost:8080/add/a/b
    @RequestMapping("/add/{a}/{b}")
    public String test1(@PathVariable int a,@PathVariable int b, Model model){
        int res=a+b;
        model.addAttribute("msg","The result is"+res);
        return "test";
    }
}

Test:

Annotation writing method (this method is recommended)

@GetMapping: indicates @ RequestMapping(method = RequestMethod.GET)

@PostMapping

@DeleteMapping

@PutMapping

@PatchMapping

@Controller
public class RestFullController {

    //Using the @ RequestMapping annotation, you can select parameters in parentheses to select the method
    //@The RequestMapping annotation defaults to GET
    @RequestMapping(value="/add/{a}/{b}",method = RequestMethod.GET)
    public String test1(@PathVariable int a,@PathVariable int b, Model model){
        int res=a+b;
        model.addAttribute("msg","The result is"+res);
        return "test";
    }

    //Using @ PostMapping annotation, you can directly use the post method
    @PostMapping("/add/{a}/{b}")
    public String test2(@PathVariable int a,@PathVariable int b, Model model){
        int res=a+b;
        model.addAttribute("msg","The result is"+res);
        return "test";
    }
}

Request forwarding and redirection

Possible problems in redirection: files in the WEB-INF directory will be protected and inaccessible

@Controller
public class ModelTest1 {
    @RequestMapping("/t14")
    public String test3(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        System.out.println(session.getId());
        return "test";
    }
    
    //You can turn off or turn on view resolution. The path in the return statement should be written completely. Even if view resolution is turned on, it will not be added automatically
    
    //redirect
    //The address will change
    @RequestMapping("/t12")
    public String test1(Model model){
        model.addAttribute("msg","ModelTest1");
        return "redirect:/WEB-INF/jsp/test.jsp";
    }
    //forward
    //The address bar will not change. The default is forwarding
    @RequestMapping("/t13")
    public String test2(Model model){
        model.addAttribute("msg","ModelTest1");
        return "forward:/WEB-INF/jsp/test.jsp";
    }
}

Request receiving parameters and data echo

Receive parameters

Submitted is a value

//localhost:8080/user/t1?username=xxx;
@GetMapping("/t1")
//After using @ RequestParam annotation, the front end will only receive the value when the name is username, otherwise an error will be reported
//If this annotation is not added, null will be passed if the name is not uername
public  String test1(@RequestParam("username") String name , Model model){
    //Receive front-end parameters
    System.out.println("The parameters received from the front end are"+name);
    //Pass the returned result to the front end
    model.addAttribute("msg",name);
    //View jump
    return "test";
}

Submitted is an object

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

Entity class

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private int age;

}

Submit data

http://localhost:8080/ mvc04/user?name= kuangshen&id=1&age= 15

processing method

//The front end receives an object: id, name, age
/**
 * 1.Receive 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
 * **/
@GetMapping("/t2")
public String test2(User user,Model model){
    System.out.println(user);
    model.addAttribute("msg",user);
    return "test";
}

test

Data echo

ModelAndView

While storing data, you can set the returned logical view and control the jump of the display layer.

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

    ModelAndView mv = new ModelAndView();
    mv.addObject("msg","ControllerTest01");
    mv.setViewName("test");
    return mv;
}

Model

Compact version (in most cases, we use Model directly)

Only a few methods are suitable for storing data, which simplifies the novice's operation and understanding of Model objects:

@RequestMapping("/t14")
public String test3(HttpServletRequest request, HttpServletResponse response){
    HttpSession session = request.getSession();
    System.out.println(session.getId());
    return "test";
}

ModelMap

It inherits LinkedMap. In addition to implementing some of its own methods, it also inherits the methods and features of LinkedMap:

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

Garbled code problem solving

jsp test file

<form action="${pageContext.request.contextPath}/e/t11" method="post">
    <input type="text" name="name">
    <input type="submit" name="Submit">
</form>

On the web Import the built-in filter in XML

<!-- Chinese garbled code filter -->
<filter>
    <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Possible problems

  1. The origin server did not find a current representation for the target resource or is not will to close that one exists

    • Here, because I didn't / jump to / e/t1 when Tomcat configured the Application context, I always reported an error and couldn't find the resource. This problem has been bothered for a long time
    • Add ${pageContext.request.contextPath} to the path of the form
  2. Invalid filter

    <url-pattern>/*</url-pattern>
    /There must be something in the back*number
    

JSON

  • JSON (JavaScript object notation) is a lightweight data exchange format, which is widely used at present.
  • Data is stored and represented in a text format completely independent of the programming language.
  • The concise and clear hierarchy makes JSON an ideal data exchange language.
  • It is easy for people to read and write, but also easy for machine analysis and generation, and effectively improves the network transmission efficiency.
<script type="text/javascript">
    //Write a JavaScript object
    var user={
        name:"lzj",
        age:"18",
        sex:"male"
    };
    //Convert js object to json object
    var json=JSON.stringify(user);
    console.log(json);
    //Convert json objects to JavaScript objects
    var obj =JSON.parse(json);
    console.log(obj)
</script>

JackSon

  1. Import dependency

    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.13.1</version>
    </dependency>
    
  2. Entity class

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
        private String name;
        private int age;
        private String sex;
    }
    
  3. springmvc-servlet. Add json garbled configuration in XML configuration

    <!--solve json Garbled 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>
    
  4. Controller test

    //@Controller
    @RestController//This class does not take the view parser
    public class UserController {
        @RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")//If you do not configure anti json garbled code in spring, you need to add products to prevent garbled code
    //    @ResponseBody / / instead of using the view parser, it will directly return a string
        public String json1() throws JsonProcessingException {
            //jackson,ObjectMapper
            ObjectMapper mapper = new ObjectMapper();
            //Create an object
            User user = new User("lzj", 18, "male");
            String str = mapper.writeValueAsString(user);
            return str;//new ObjectMapper().writeValueAsString(user)
        }
        
            @RequestMapping("/j2")
        public String json2() throws JsonProcessingException {
            //jackson,ObjectMapper
            ObjectMapper mapper = new ObjectMapper();
            Date date = new Date();
            //Custom date format
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(date);
            //ObjectMapper, the default format after time parsing is: Timestamp, Timestamp
            String str = mapper.writeValueAsString(format);
            return str;//new ObjectMapper().writeValueAsString(user)
        }
        
         @RequestMapping("/j3")
        public String json3() throws JsonProcessingException {
            //jackson,ObjectMapper
            ObjectMapper mapper = new ObjectMapper();
            //Without timestamp
            mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
            //Custom date format
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mapper.setDateFormat(simpleDateFormat);
    
            Date date = new Date();
            String str = mapper.writeValueAsString(date);
            return str;//new ObjectMapper().writeValueAsString(user)
        }
    }
    

Draw as tool class

public class JsonUtils {
    public static String getJson(Object object){
        return getJson(object,"yyyy-MM-dd HH:mm:ss");
    }

    public static String getJson(Object object,String deteFormat){
        ObjectMapper mapper = new ObjectMapper();
        //Without timestamp
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
        //Custom date format
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mapper.setDateFormat(simpleDateFormat);
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

FastSon

  1. Import dependency

    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.79</version>
    </dependency>
    
  2. Write controller

    @RequestMapping("/j4")
        public String json4() throws JsonProcessingException {
            ArrayList<User> list = new ArrayList<>();
            User user1 = new User("lzj",18,"male");
            User user2 = new User("lzj2",18,"male");
            User user3 = new User("lzj3",18,"male");
            list.add(user1);
            list.add(user2);
            list.add(user3);
    
    //        System.out.println("*******Jay object to JSON character ******");
    //        String str1 = JSON. toJSONString(list);
    //        System.out.println( "ISON. toJSoNString(list)==>"+str1);
    //        String str2 = JSON.toJSONString(user1);
    //        System.out.println( "ISON toJSoNString(user1)==>"+str2);
    //        System.out.println("****** JSON string to Java object *****");
    //        User jp_user1=JSON. parseObject(str2,User . class);
    //        System.out.println( "JSON. parse0bject(str2,User .class)=>"+jp_user1);
    //        System. out. Println ("***** Java object to JSON object *****");
    //        JSONObject jsonobject1 = (JSONObject) JSON. toJSON(user2);
    //        System.out.println(" (JSONObject) JSON. toJSON(user2)==>"+jsonobject1.getString( "name"));
    //        System. out. Println ("* * * * * JSON object to Java object * * * *");
    //        User to_java_user = JSON.toJavaObject(jsonobject1, User.class);
    //        System.out.println( "ISON. toJavaobject(json0bject1, User .class)==>"+to_java_user);
    
            String s = JSON.toJSONString(list);
            return s;
        }
    

Interceptor

The difference between interceptor and filter

Interceptor is the concrete application of AOP idea

Filter

  • Part of the servlet specification that can be used by any java webI program
  • After / * is configured in URL pattern, all resources to be accessed can be intercepted

Interceptor

  • The interceptor is the Spring MVC framework's own. It can only be used by projects that use the Spring MVC framework
  • The interceptor will only intercept the accessed controller methods. If the accessed is jsp/html/css/image/js, it will not intercept

custom interceptor

The HandlerInterceptor interface must be implemented

  1. New Moudel

  2. Configure web XML and ApplicationContext xml

    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: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>
    
    </web-app>
    

    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 https://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.lzj.controller"/>
        <!--    Give Way SpringMVC Do not process static resources-->
        <mvc:default-servlet-handler/>
        <!--    Automatic completion BeanNameUrlHandlerMapping and SimpleControllerHandlerAdapter Instance injection-->
        <mvc:annotation-driven/>
    
        <!--solve json Garbled 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>
    
        <!--    view resolver -->
        <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!--        prefix-->
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <!--        suffix-->
            <property name="suffix" value=".jsp"/>
        </bean>
        
    </beans>
    
  3. Write controller class

    @RestController
    public class TestController {
        @RequestMapping("/t1")
        public String test(){
            System.out.println("TestController=>It's on");
            return "ok";
        }
    }
    
  4. Writing interceptor classes

    public class MyInterceptor implements HandlerInterceptor {
        //return true: execute the next interceptor first and release it
        //return false: do not execute the next interceptor
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            System.out.println("====Before treatment=====");
            return true;
        }
        //The following two methods can be used to write the interception log
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            System.out.println("====After treatment=====");
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            System.out.println("====clear=====");
        }
    }
    
  5. Configure the interceptor in the configuration file of spring MVC

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

Login judgment verification [actual combat]

Requirements: judge whether the user logs in. If he logs in, he can enter the home page (main.jsp), otherwise he can only enter the login page

Implementation: after the user logs in, add a session, and judge whether there is a session to intercept through the interceptor

  1. Configure web XML and ApplicationContext xml

  2. Write controller class

    @Controller
    @RequestMapping("/user")
    public class LoginController {
        @RequestMapping("/login")
        public String login(HttpSession session,String username, String password,Model model){
            //Store the user's information in the session
            session.setAttribute("username",username);
            model.addAttribute("username",username);
            return "main";
        }
        @RequestMapping("/goLogin")
        public String login(){
    
            return "login";
        }
        @RequestMapping("/main")
        public String main(){
    
            return "main";
        }
    
        @RequestMapping("/goOut")
        public String login(HttpSession session){
            //Store the user's information in the session
            session.removeAttribute("username");
            return "redirect:/index.jsp";
        }
    }
    
  3. Writing interceptor classes

    public class LoginInterceptor implements HandlerInterceptor {
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            HttpSession session = request.getSession();
            //Release: determine the conditions for login
            //The login page is also released
            //If the url of the access page contains login, it will be released
            if(request.getRequestURI().contains("login")){
                return true;
            }else if(session.getAttribute("username")!=null){
                return true;
            }
    
            //Determine under what conditions you are not logged in
            request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
            return false;
        }
    }
    
  4. Configure the interceptor in the configuration file of spring MVC

    <!--    Interceptor configuration-->
        <mvc:interceptors>
            <mvc:interceptor>
                <!--            Include all requests below this request-->
                <mvc:mapping path="/user/**"/>
                <bean class="com.lzj.config.LoginInterceptor"/>
            </mvc:interceptor>
        </mvc:interceptors>
    
  5. Write a jsp file and create a jsp folder under the WEB-INF folder

    index.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <title>$Title$</title>
      </head>
      <body>
      <h1><a href="/user/goLogin">Login page</a></h1>
      <h1><a href="/user/main">home page</a></h1>
      </body>
    </html>
    

    main.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    <h1>home page</h1>
    <span>${username}</span>
    
    <p>
        <a href="${pageContext.request.contextPath}/user/goOut">cancellation</a>
    </p>
    </body>
    </html>
    

    login.jsp

    <%--
      Created by IntelliJ IDEA.
      User: 86158
      Date: 2022/2/24
      Time: 22:52
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Login page</title>
    </head>
    <body>
    <%--stay WEB-INF All pages or resources under can only be accessed through controller,perhaps servlet Visit--%>
    
    <h1>Landing 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>
    
  6. Project structure

  1. test

Keywords: Java Spring Spring MVC

Added by simona_85 on Fri, 25 Feb 2022 18:58:30 +0200