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控制器的更多相关文章

  1. Spring入门(十四):Spring MVC控制器的2种测试方法

    作为一名研发人员,不管你愿不愿意对自己的代码进行测试,都得承认测试对于研发质量保证的重要性,这也就是为什么每个公司的技术部都需要质量控制部的原因,因为越早的发现代码的bug,成本越低,比如说,Dev环 ...

  2. spring mvc 控制器方法传递一些经验对象的数组

    由于该项目必须提交一个表单,其中多个对象,更好的方法是直接通过在控制器方法参数的数组. 因为Spring mvc框架在反射生成控制方法的參数对象的时候会调用这个类的getDeclaredConstru ...

  3. Spring MVC:控制器类名称处理映射

    控制器类名称处理映射的好好处是: 如果项目是hello,WelcomeController是控制器,那么访问地址是: http://localhost:8080/hello/welcome http: ...

  4. Spring MVC控制器方法参数类型

    HttpServletRequest Spring会自动将 Servlet API 作为参数传过来 HttpServletResponse InputStream 相当于request.getInpu ...

  5. Spring MVC控制器用@ResponseBody声明返回json数据报406的问题

    本打算今天早点下班,结果下午测试调试程序发现一个问题纠结到晚上才解决,现在写一篇博客来总结下. 是这样的,本人在Spring mvc控制层用到了@ResponseBody标注,以便返回的数据为json ...

  6. 转转转!!Spring MVC控制器用@ResponseBody声明返回json数据报406的问题

    本打算今天早点下班,结果下午测试调试程序发现一个问题纠结到晚上才解决,现在写一篇博客来总结下. 是这样的,本人在Spring mvc控制层用到了@ResponseBody标注,以便返回的数据为json ...

  7. Spring MVC控制器类名称处理映射

    以下示例显示如何使用Spring Web MVC框架使用控制器类名称处理程序映射. ControllerClassNameHandlerMapping类是基于约定的处理程序映射类,它将URL请求映射到 ...

  8. 关于一些Spring MVC控制器的参数注解总结

    昨天同事问我控制器参数的注解的问题,我好久没那样写过,把参数和url一起设置,不过,今天我看了一些文章,查了一些资料,我尽可能的用我自己的理解方式来解释它吧! 1.@RequestParam绑定单个请 ...

  9. Spring MVC(五)--控制器通过注解@RequestParam接受参数

    上一篇中提到,当前后端命名规则不一致时,需要通过注解@RequestParam接受参数,这个注解是作用在参数上.下面通过实例说明,场景如下: 在页面输入两个参数,控制器通过注解接受,并将接受到的数据渲 ...

随机推荐

  1. SQLSERVER2012 Audit (审核)功能

    数据库表结构和数据有时会被无意或者恶意,或者需要追踪最近的数据结构变更记录,以往必须通过日志查询,SQL Server2008开始提供了 审核(Audit )功能,SQL2012有所升级,利用它可以实 ...

  2. java常见的开发工具

    http://www.csdn.net/article/1970-01-01/2824723 http://zhidao.baidu.com/link?url=D8FdJxeFd-z-LV1OfZuZ ...

  3. EntityFramework优缺点

    高层视图: 改变在现有系统使用EntityFramework的优势是什么? • All -in-1框架的类映射表,需要编写映射代码, 并且是很难维护的. • 可维护性,易于理解的代码,无需创造大的数据 ...

  4. Oracle merge into

    Oracle中Merge into用法总结 文件来源:(http://blog.csdn.net/yuzhic/article/details/1896878) 有一个表T,有两个字段a.b,我们想在 ...

  5. mac终端显示和隐藏隐藏文件的命令

    defaults write com.apple.finder AppleShowAllFiles -bool true; killall Finder //显示隐藏文件 defaults write ...

  6. 第四篇:白话tornado源码之褪去模板外衣的前戏

    加班程序员最辛苦,来张图醒醒脑吧! ... ... ... 好了,醒醒吧,回归现实看代码了!! 执行字符串表示的函数,并为该函数提供全局变量 本篇的内容从题目中就可以看出来,就是为之后剖析tornad ...

  7. telnet输入乱码的解决

    1.Win+R --- 运行窗口  输入cmd回车 2.输入telnet 主机 端口 3.连接主机发现无法输入 4.这里什么也不要输入,按下 ctrl+] 键 5.按下回车键,然后会弹出新的窗口,就可 ...

  8. Oracle之nclob类型

    此类型会严重影响查询效率,请少用: nclob字段在查询结果中显示为<NCLOB>,查看nclob类型的值方法有两种 a.可点开...查看具体数据 b.选择所有数据,右击复制到Excel, ...

  9. SQL优化----百万数据查询优化

    百万数据查询优化 1.合理使用索引 索引是数据库中重要的数据结构,它的根本目的就是为了提高查询效率.现在大多数的数据库产品都采用IBM最先提出的ISAM索引结构.索引的使用要恰到好处,其使用原则如下: ...

  10. margin属性

    可以设置position:absolute/relative/fixed,通过调节top/bottom/left/right实现元素的定位,这样很好,但是有时候想通过margin来实现. 下面是mar ...