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 , 需要先指定类的路径再指定方法的路径;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值