SpringMVC-Controller

Controller控制器

  • 控制器提供访问应用程序的行为,有接口实现和注解实现两种方法。
  • 控制器负责解析用户的请求并将其转换为一个模型。
  • 在Spring MVC中一个控制器类可以包含多个方法
  • 在Spring MVC中,对于Controller的配置方式有很多种

接口实现
1.创建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;
    }
}

2.创建springmvc-config.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">

    <!-- 视图解析器 -->
    <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.kuang.controller.ControllerTest1"/>
</beans>

3.写前端界面

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

4.执行
在这里插入图片描述
说明:接口实现Controller是一个较老的方法,不推荐!!
缺点:一个控制器中只能有一个方法,如果要多个方法需要定义多个Controller。

注解实现
见上一篇:SpringMVC-annotation

@RequestMapping

  • @RequestMapping注解用于映射url到控制器类或一个特定的处理程序方法,可用于类上或方法上。

1.用于方法上

@Controller
public class HelloController {
    
    

    @RequestMapping("/h1")
    public String test(Model model){
    
    
        //传递数据
        model.addAttribute("msg","hello HelloController");
        //跳转页面
        return "hello";
    }
}

访问路径:http://localhost:8080 / 项目名 / h1

2.用于类上和方法上

@Controller
@RequestMapping("hhh")
public class HelloController {
    
    

    @RequestMapping("/h1")
    public String test(Model model){
    
    
        //传递数据
        model.addAttribute("msg","hello HelloController");
        //跳转页面
        return "hello";
    }
}

访问路径:http://localhost:8080 / 项目名/ hhh/h1 , 需要先指定类的路径再指定方法的路径;

猜你喜欢

转载自blog.csdn.net/qq_42665745/article/details/112852361
今日推荐