Spring MVC控制器
Spring MVC中控制器用于解析用户请求并且转换为模型以提供访问应用程序的行为,通常用注解方式实现.
org.springframework.stereotype.Controller注解用于声明Spring类的实例为一个控制器, 可以通过在配置文件中声明扫描路径,找到应用程序中所有基于注解的控制器类:
<!-- 自动扫描包路径,实现支持注解的IOC -->
<context:component-scan base-package="cn.luan.controller" />
一个简单的控制器:
@Controller
public class BarController {
//映射访问路径
@RequestMapping("/index")
public String index(Model model){
//Spring MVC会自动实例化一个Model对象用于向视图中传值
model.addAttribute("message", "这是通过注解定义的一个控制器中的Action");
//返回视图位置
return "foo/index";
}
}
@RequestMapping注解用于映射url到控制器类或方法,该注解共有8个属性:
public @interface RequestMapping {
java.lang.String name() default "";
@org.springframework.core.annotation.AliasFor("path")
java.lang.String[] value() default {};
@org.springframework.core.annotation.AliasFor("value")
java.lang.String[] path() default {};
org.springframework.web.bind.annotation.RequestMethod[] method() default {};
java.lang.String[] params() default {};
java.lang.String[] headers() default {};
java.lang.String[] consumes() default {};
java.lang.String[] produces() default {};
}
value和path属性功能相同, 用来指定映射路径或URL模板,数组类型故可以写成@RequestMapping(value={"/path1","/path2"})。
name属性指定映射器名称,一般情况下不指定
method属性指定请求方式,可以为GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE,用来过滤请求范围,不符合的请求将返回405错误,即Method Not Allowed
params属性指定映射参数规则
consumes属性指定请求的内容类型,如application/json, text/html
produces属性指定返回的内容类型,如application/json; charset=UTF-8
headers属性指定映射请求头部,如Host,Content-Type等
一个例子:
@Controller
@RequestMapping("/appointments")
public class AppointmentsController {
private final AppointmentBook appointmentBook; @Autowired
public AppointmentsController(AppointmentBook appointmentBook) {
this.appointmentBook = appointmentBook;
} @RequestMapping(method = RequestMethod.GET)
public Map<String, Appointment> get() {
return appointmentBook.getAppointmentsForToday();
} @RequestMapping(value = "/{day}", method = RequestMethod.GET)
public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso = ISO.DATE) Date day, Model model) {
return appointmentBook.getAppointmentsForDay(day);
} @RequestMapping(value = "/new", method = RequestMethod.GET)
public AppointmentForm getNewForm() {
return new AppointmentForm();
} @RequestMapping(method = RequestMethod.POST)
public String add(@Valid AppointmentForm appointment, BindingResult result) {
if (result.hasErrors()) {
return "appointments/new";
}
appointmentBook.addAppointment(appointment);
return "redirect:/appointments";
}
}
@RequestMapping只注解方法:
@Controller
public class myController {
@RequestMapping("/act")
public String act(){
return "jsp/index";
}
}
访问路径:http://localhost:8080/springmvctest/act
@RequestMapping同时注解类和方法,访问路径为类上的value组合函数上的value:
@Controller
@RequestMapping("/my")
public class MyController {
@RequestMapping("/act")
public String act(){
return "jsp/index";
}
}
访问路径:http://localhost:8080/springmvctest/my/act
@RequestMapping中value属性默认为空,当只写@RequestMapping时, 表示该类或方法为默认控制器,默认方法:
@Controller
@RequestMapping
//默认控制器
public class myController {
@RequestMapping
//默认action
public String action(Model model){
model.addAttribute("message", "action2");
return "jsp/index";
}
}
访问路径为:http://localhost:8080/springmvctest/
可以使用@PathVariable注释将方法参数的值绑定到一个URL模板变量:
@RequestMapping("/action/{p1}/{p2}")
public String action(@PathVariable int p1,@PathVariable int p2,Model model){
model.addAttribute("message", p1+" "+p2);
return "jsp/index"; }
访问路径:http://localhost:8080/springmvctest/action/1/2, 参数的类型必须符合,否则404错误
@RequestMapping支持正则表达式:
@RequestMapping(value="/action/{id:\\d{4}}-{name:[a-z]{4}}")
public String action(@PathVariable int id,@PathVariable String name,Model model){
model.addAttribute("message", "id:"+id+" name:"+name);
return "jsp/index";
}
访问路径:http://localhost:8080/springmvctest/action/1234-abcd

也支持通配符:
@RequestMapping(value = "/action/*.do")
public String action(Model model){
model.addAttribute("message","123");
return "jsp/index";
}
访问路径:http://localhost:8080/springmvctest/action/test234-rrt.do
过滤提交的内容类型
@Controller
@RequestMapping("/my")
public class MyController {
// 请求内容类型必须为text/html,浏览器默认没有指定Content-type
@RequestMapping(value = "/action",consumes="text/html")
public String action(Model model) {
model.addAttribute("message", "请求的提交内容类型是text/html");
return "jsp/index";
}
}
指定返回的内容类型
@RequestMapping(value = "/action",produces="application/json; charset=UTF-8")
public String action(Model model) {
model.addAttribute("message", "application/json; charset=UTF-8");
return "jsp/index";
}
过滤映射请求的参数,限制客户端发送到服务器的请求参数为某些特定值或不为某些值:
@RequestMapping(value = "/action",params={"id!=0","name=root"})
public String action(Model model) {
model.addAttribute("message", "");
return "jsp/index";
}
访问路径:http://localhost:8080/springdemo/show/action?id=10&name=root
过滤映射请求头部,约束客户端发送的请求头部信息中必须包含某个特定的值或不包含某个值,作用范围大于consumes 和 produces
@RequestMapping(value = "/action",headers={"Host=localhost:8088",Content-Type="application/*"})
public String action(Model model) {
model.addAttribute("message", "");
return "jsp/index";
}
end
Spring MVC控制器的更多相关文章
- Spring入门(十四):Spring MVC控制器的2种测试方法
作为一名研发人员,不管你愿不愿意对自己的代码进行测试,都得承认测试对于研发质量保证的重要性,这也就是为什么每个公司的技术部都需要质量控制部的原因,因为越早的发现代码的bug,成本越低,比如说,Dev环 ...
- spring mvc 控制器方法传递一些经验对象的数组
由于该项目必须提交一个表单,其中多个对象,更好的方法是直接通过在控制器方法参数的数组. 因为Spring mvc框架在反射生成控制方法的參数对象的时候会调用这个类的getDeclaredConstru ...
- Spring MVC:控制器类名称处理映射
控制器类名称处理映射的好好处是: 如果项目是hello,WelcomeController是控制器,那么访问地址是: http://localhost:8080/hello/welcome http: ...
- Spring MVC控制器方法参数类型
HttpServletRequest Spring会自动将 Servlet API 作为参数传过来 HttpServletResponse InputStream 相当于request.getInpu ...
- Spring MVC控制器用@ResponseBody声明返回json数据报406的问题
本打算今天早点下班,结果下午测试调试程序发现一个问题纠结到晚上才解决,现在写一篇博客来总结下. 是这样的,本人在Spring mvc控制层用到了@ResponseBody标注,以便返回的数据为json ...
- 转转转!!Spring MVC控制器用@ResponseBody声明返回json数据报406的问题
本打算今天早点下班,结果下午测试调试程序发现一个问题纠结到晚上才解决,现在写一篇博客来总结下. 是这样的,本人在Spring mvc控制层用到了@ResponseBody标注,以便返回的数据为json ...
- Spring MVC控制器类名称处理映射
以下示例显示如何使用Spring Web MVC框架使用控制器类名称处理程序映射. ControllerClassNameHandlerMapping类是基于约定的处理程序映射类,它将URL请求映射到 ...
- 关于一些Spring MVC控制器的参数注解总结
昨天同事问我控制器参数的注解的问题,我好久没那样写过,把参数和url一起设置,不过,今天我看了一些文章,查了一些资料,我尽可能的用我自己的理解方式来解释它吧! 1.@RequestParam绑定单个请 ...
- Spring MVC(五)--控制器通过注解@RequestParam接受参数
上一篇中提到,当前后端命名规则不一致时,需要通过注解@RequestParam接受参数,这个注解是作用在参数上.下面通过实例说明,场景如下: 在页面输入两个参数,控制器通过注解接受,并将接受到的数据渲 ...
随机推荐
- MVC 关于easyui-datebox 赋值问题
view <script type="text/javascript"> $(function () { var date = '@ViewData["end ...
- 在eclipse中使用正则表达式进行搜素
- zookeeper+jstorm的集群搭建
zookeeper的配置: zookeeper有三种配置方式:单机式/伪分布式/集群式 其中伪分布式是在一台电脑上通过不同的端口来模拟分布式情形,需要N份配置文件和启动程序,而集群式是多个zookee ...
- 解决点击cell时,UILabel的背景颜色消失的问题
-(void)setSelected:(BOOL)selected animated:(BOOL)animated{ [super setSelected:selected animated:anim ...
- Centos minimal安装
Q:为什么要安装minimal版本?而不是完整版 A:因为它资源小啊 @ @ 怎么安装就不说了,网上资源大把,Centos7好像变化挺大,mysql都装不上,还是装6吧~ 1.安装完是不能联网的,解决 ...
- iOS duplicate symbol 变量 in 类名 报错
该错误信息是我在一个.h文件里申明了公共变量,然后在其他类里重复使用. Build Settings ->No Common Blocks默认为YES,编译器就报错了,需要修改Build Set ...
- FTP客户端连接时中文乱码问题处理
1.问题场景: 使用FileZilla连接FTP时发现中文字符有乱码,如题: 2. 分析问题: 主要是字符问题引起的:FileZilla是自动检测字符集的,会导致部分中文字符集显示异常: 3.解决方法 ...
- 区间重叠计算及IntervalTree初识
最近被人问到这样一个问题的解决方案:在一个餐馆的预定系统中,接受用户在未来任意一段时间内的预订用餐,用户在预订的时候需要提供用餐的开始时间和结束,餐馆的餐桌是用限的,问题是,系统要在最快的时间段计算出 ...
- .html(),.text()和.val()的差异总结:
.html(),.text()和.val()的差异总结: 1.html(),.text(),.val()三种方法都是用来读取选定元素的内容:只不过.html()是用来读取元素的html内容(包括htm ...
- 解决Windows下网络原因Composer安装失败问题
由于Composer镜像都在国外,所以直接在官网下载Windows Installer后安装很多情况下是无法成功安装的. 解决办法: 1,将php添加到系统环境变量,并开启openssl扩展. 2,点 ...