Once you and I couldn't stand it. Now I just want to annotate and configure

🏇 Small wood come Yes \textcolor{Orange} {here comes Koki} Here comes Koki
🍣 Yes solution Yes one lower S p r i n g M V C of primary reason , that Do you Just go deep enter see one lower \textcolor{green} {after understanding the principle of spring MVC, let's take a deep look} After understanding the principle of spring MVC, let's take a closer look 🍣
🍣 this day of order mark yes notes solution open hair and as What send use @ C o n t r o l l e r \textcolor{green} {today's goal is to annotate development and how to use @ Controller} Today's goal is to annotate development and how to use @ Controller 🍣
🙏 Bo main also stay learn Learn rank paragraph , as if hair present ask topic , please Tell know , wrong often sense thank \textcolor{Orange} {blogger is also in the learning stage. If you find any problems, please let me know. Thank you very much} Bloggers are also in the learning stage. If you find any problems, please let us know. Thank you very much 💗

The code used can be found here

3, Annotation annotation development

1. Steps

− − > \textcolor{orange}{-->} − − > create Module,

− − > \textcolor{orange}{-->} − − > Add web support,

− − > \textcolor{orange}{-->} − − > Import dependencies (mainly Spring framework core library, Spring MVC, servlet, JSTL, etc.),

− − > \textcolor{orange}{-->} − − > configure web.xml: note that the version of web.xml should be the latest version 4.0; Add the lib directory of artifacts; Register dispatcher servlet; The configuration file associated with spring MVC; The startup level is 1; Mapping path is/

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--1.register servlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--DispatcherServlet To bind Spring Configuration file for-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--classpath*: Will find the configuration files of all paths, and classpath: Will find the configuration file under the current path-->
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!--Startup level: 1 means that the server starts as soon as it starts-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!--All requests will be rejected springmvc intercept
    -->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

− − > \textcolor{orange}{-->} − − > create 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"
       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.hxl.controller"/>
    <!--Give Way SpringMVC Do not process static resources .css .js .html wait-->
    <mvc:default-servlet-handler/>
    <!--
    support MVC Annotation driven
        stay spring Generally used in@RequestMapping 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 parser: template engine Thymeleaf Freemarker-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <!--Prefix, suffix-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

− − > \textcolor{orange}{-->} − − > note: in the view parser, we put all views in the / WEB-INF / directory, which can ensure the security of the view, because the files in this directory cannot be accessed directly by the client

− − > \textcolor{orange}{-->} − − > create Controller

package com.hxl.controller;

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

@Controller
@RequestMapping("/HelloController")
public class HelloController {
    //Real access address: project name / HelloController/hello
    @RequestMapping("/hello")
    public String hello(Model model){
        //Encapsulate the data, add attributes msg and values to the model, and take them out and render them in the jsp page
        model.addAttribute("msg","Hello,SpringMVCAnnotation. Old fellow iron");
        // WEB-INF/jsp/hello.jsp
        return "hello"; //Will be processed by the view parser
    }
}
  • @The Controller is used to automatically scan the Spring IOC container when it is initialized
  • @RequestMapping is to map the request path. Here, because there are mappings on classes and methods, the access should be / HelloController/hello
  • Method is declared to bring the data in the Action to the view
  • The structure returned by the method is the name of the view Hello, plus the prefix in the configuration file, and becomes, / WEB-INF/jsp/hello.jsp

− − > \textcolor{orange}{-->} − − > create view layer

− − > \textcolor{orange}{-->} − − > create hello.jsp in the WEB-INF/jsp directory. The view can take out and display the information brought back from the Controller; You can retrieve the value (object) stored in the Model through EL

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

− − > \textcolor{orange}{-->} − − > configure Tomcat access
I won't repeat it here. You can check the previous blog if necessary

2. Summary

  1. Create a new web project
  2. Import jar package
  3. Write web.xml and register DispatcherServlet
  4. Writing spring MVC configuration files
  5. Create the corresponding control class controller
  6. Improve the correspondence between the front-end view and the controller
  7. test run

Using spring MVC, three cores must be configured: processor mapper, processor adapter and view parser

In our development, we only need to manually configure the view parser, while the processor mapper and processor adapter only need to turn on the annotation driver.

4, Controller configuration summary

Controller controller

  • The behavior of controller complex system accessing application program is usually realized by interface definition or annotation definition.
  • The controller is responsible for parsing the user's request and transforming it into a model
  • In spring MVC, a controller class can contain multiple methods
  • In spring MVC, there are many ways to configure the Controller

Implement Controller interface

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

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

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

− − > \textcolor{orange}{-->} − − > register bean s in spring mvc-servlet.xml, spring configuration file; name corresponds to the request i path, and class corresponds to the class that handles the request

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

    <!--View parser: template engine Thymeleaf Freemarker-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <!--Prefix, suffix-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

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

</beans>

− − > \textcolor{orange}{-->} − − > there are disadvantages in implementing the controller interface here: there is only one method in a controller. If you want multiple methods, you need to define multiple controllers; The way of definition is troublesome;

Develop @ Controller using annotations

  • @The controller annotation type is used to declare that the instance of the Spring class is a controller (@ Component (Component), @ Service (servie), @ controller (controller), @ repository (dao))

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

    <?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.hxl.controller"/>
    
        <!--View parser: template engine Thymeleaf Freemarker-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
            <!--Prefix, suffix-->
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    
     
    </beans>
    

− − > \textcolor{orange}{-->} −−>ControllerTest2

package com.hxl.controller;

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

//It means that this class will be taken over by spring. All methods of this annotated class will be parsed by the view parser if the return value is String and there is a specific page to jump to
@Controller 
public class ControllerTest2 {
  @RequestMapping("/t2")
  public String test(Model model){
      model.addAttribute("msg", "ControllerTest2");
      return "test";
  }
}

Tips:

  • Just change the java code and reload it
  • As long as you change the configuration file, you need to restart tomcat
  • If you only change the front page, refresh it

Note: both requests can point to a view, but the results of the page results 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.

Bi said: click on a multiple selection (with addition and modification), there are many different pages, but there may not be so many jsp pages. Just change a template and exchange the data inside. If you have relevant development experience, you will

Tags: Java Back-end Spring MVC SSM

Posted on Tue, 30 Nov 2021 22:07:45 -0500 by landung