Controller和RequestMapping

1.Controller

1.实现Controller接口,这是一种比较老的方法,一个控制器中只有一个方法,如果要多个方法则需要定义多个Controller;定义的方式比较麻烦

//定义控制器
//注意点:不要导错包,实现Controller接口,重写方法;
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest
httpServletRequest, HttpServletResponse httpServletResponse) throws
Exception {
//返回一个模型视图对象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","Test1Controller");
mv.setViewName("test");
return mv;
}
}

2, 编写完毕后,去Spring配置文件中注册请求的bean;name对应请求路径,class对应处理请求的类

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

还有一种就是使用@Controller注解
将@Controller标注再类上,这时候不能说它就是springmvc的控制器,因为Spring容器还不认识它,需要在配置中声明,把这个控制器交给spring容器,让spring容器来管理。声明的方式有两种

第一种可以在配置中声明组件扫描器

<!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
<context:component-scan base-package="com.kuang.controller"/>

第二种

<!--基于注解的装配-->
<bean class="com.HelloWorld"/>

一般都使用第一种来装配

2.RequestMapping

配置声明之后,@Controller只是定义了一个控制器类,而使用@RequestMapping注解的方法才是处理请求的处理器

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

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

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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值