[4] Controller

4. Controller

4.1, Controller

  • The controller complex provides the behavior of accessing the application program, which is usually implemented through two methods: interface definition or annotation definition.
  • The controller is responsible for parsing the user's request and transforming it into a model.
  • A controller class can contain multiple methods in Spring MVC
  • In Spring MVC, there are many ways to configure Controller

4.2, implement the Controller interface

Controller is an interface, under the org.springframework.web.servlet.mvc package, there is only one method in the interface;

//实现该接口的类获得控制器功能
public interface Controller {
    
    
   //处理请求且返回一个模型与视图对象
   ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception;
}

test

  1. Create a new Moudle, springmvc-04-controller. Copy the 03 just now, and we will proceed!

    • Delete HelloController
    • The configuration file of mvc only leaves the view parser!
    <!--视图解析器:模板引擎 Thymeleaf Freemarker-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>
    
  2. Write a Controller class, ControllerTest

    public class ControllerTest implements Controller {
          
          
        @Override
        public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
          
          
    
            ModelAndView mv = new ModelAndView();
    
            mv.addObject("msg","Controller测试");
    
            /*跳转页面的名字,在ViewResolver中拼接成字符串视图页面名称*/
            mv.setViewName("controller1");
            return mv;
        }
    }
    
  3. After writing, go to the Spring configuration file to register the requested bean; name corresponds to the request path, and class corresponds to the request processing class

    <!--BeanNameUrlHandlerMapping将实现类注册成bean,bean的id就是url-pattern-->
    <bean id="/c1" class="com.kuber.controller.ControllerTest"/>
    
  4. Write the front-end controller1.jsp, pay attention to writing in the WEB-INF/jsp directory, corresponding to our view parser

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>controller1</title>
    </head>
    <body>
        ${msg}
    </body>
    </html>
    
  5. Configure Tomcat to run the test. I don’t have a project release name and configure a /, so the request does not need to add the project name, OK!

    Insert picture description here

Description:

  • Implementing the interface Controller to define the controller is the older way
  • The disadvantage is: there is only one method in a controller, if you want multiple methods, you need to define multiple Controllers; the definition method is more troublesome;

4.3, use annotation @Controller

  • The @Controller annotation type is used to declare that the instance of the Spring class is a controller (3 other annotations are mentioned when talking about IOC);

  • Spring can use the scanning mechanism to find all annotation-based controller classes in the application. To ensure that Spring can find your controller, you need to declare component scanning in the configuration file. No need to register bean tags at this time

        <context:component-scan base-package="com.kuber.controller"/>
        <mvc:default-servlet-handler/>
        <mvc:annotation-driven/>
        <!--视图解析器:模板引擎 Thymeleaf Freemarker-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
            <!--前缀-->
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <!--后缀-->
            <property name="suffix" value=".jsp"/>
        </bean>
    
  • Add a ControllerTest2 class and implement it with annotations;

    @Controller/*代表这个类会被spring接管,
                   标有这个注解的类的所有方法如果其返回值为string,
                   并且返回值为相应的跳转界面的名称,那么就会被视图解析器解析*/
    public class ControllerTest2 {
          
          
    
        @RequestMapping("c2")
        public String test1(Model model){
          
          
            //Spring MVC会自动实例化一个Model对象用于向视图中传值
            model.addAttribute("msg","Controller测试2");
    		//返回视图位置
            return "controller1";
        }
    }
    
  • Run tomcat test

    Insert picture description here

It can be found that both of our requests can point to a view, but the results of the page results are different. From this we can see that the view is reused, and there is a weak coupling relationship between the controller and the view.

Annotation method is the most commonly used method!

4.4、RequestMapping

@RequestMapping

  • The @RequestMapping annotation is used to map the URL to a controller class or a specific handler method. Can be used on classes or methods. Used on classes, it means that all methods in the class that respond to requests use this address as the parent path.

  • In order to test the conclusions more accurately, we can add a project name to test myweb

  • Annotate only the method

    @Controller
    public class TestController {
          
          
       @RequestMapping("/h1")
       public String test(){
          
          
           return "test";
      }
    }
    

    Access path: http://localhost:8080/project name/h1

  • Annotate classes and methods at the same time

    @Controller
    @RequestMapping("/admin")
    public class TestController {
          
          
       @RequestMapping("/h1")
       public String test(){
          
          
           return "test";
      }
    }
    

    Access path: http://localhost:8080 / project name/ admin /h1, you need to specify the path of the class and then the path of the method;

Guess you like

Origin blog.csdn.net/weixin_43215322/article/details/111242999