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接受参数,这个注解是作用在参数上.下面通过实例说明,场景如下: 在页面输入两个参数,控制器通过注解接受,并将接受到的数据渲 ...
随机推荐
- js出错总结
1 没有</script> src="js" "./js" "../js"2 dom对象与jquery对象(jquery对象其 ...
- php try catch throw 用法
1.try catch 捕捉不到fatal error致命错误 2.只有抛出异常才能被截获,如果异常抛出了却没有被捕捉到,就会产生一个fatal error. 3.父类可以捕获抛出的子类异常,Exce ...
- LeetCode Find All Numbers Disappeared in an Array
原题链接在这里:https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ 题目: Given an array o ...
- hive 搭建
Hive hive是简历再hadoop上的数据库仓库基础架构,它提供了一系列的工具,可以用来进行数据提取转化加载(ETL),这是一种可以存储,查询和分析存储再hadoop种的大规模数据机制,hive定 ...
- 2.C语言中的关键字
1.auto 修饰局部变量,编译器默认所有局部变量都是用auto来修饰的,所以在程序中很少见到. 2.static 它作用可大了,除了可以修饰变量,还可以修饰函数,修饰变量,改变其作用域和生命周期,修 ...
- VIP
高可用性HA(High Availability)指的是通过尽量缩短因日常维护操作(计划)和突发的系统崩溃(非计划)所导致的停机时间,以提高系统和应用的可用性.HA系统是目前企业防止核心计算机系统因故 ...
- JSON.stringify////////////////////////////////zzzzzzzzzzzzzz
JSON.stringify 语法实例讲解 可能有些人对系列化这个词过敏,我的理解很简单.就是说把原来是对象的类型转换成字符串类型(或者更确切的说是json类型的).就这么简单.打个比方说,你有一个类 ...
- 利用wireshark抓包获取cookie信息
以下是一些过滤规则: 1. 百度的cookie: http.cookie matches "BDUSS" 2. 博客园的cookie: http.cookie matches &q ...
- Centos Samba 服务器 iptables 和 SElinux 设置
1.安装samba服务器 # yum install samba 2.配置 # vi /etc/samba/smb.conf security = user (100行左右) 在Share Defin ...
- Web 播放声音 — AMR(Audio) 篇
本文主要介绍 AMR(Aduio) 播放 AMR 格式 Base64码 音频. 1.必备资料 github AMR 开源库 :https://github.com/jpemartins/amr.js用 ...