SpringMVC 常用注解
本文参考了博客,具体请见:http://www.cnblogs.com/leskang/p/5445698.html
Spring MVC的常用注解
1.@Controller
@Controller用于标记在一个类上,使用它标记的类就是一个SpringMVCController对象。分发处理器将会扫描使用了该注解的类的
方法,并检测该方法是否使用了@RequestMapping
注解。@Controller只是定义了一个控制器类,而使用@RequestMapping注解的方法才是真正处理请求的处理器。单单使用
@Controller标记在一个类上还不能真正意义上的说它就是SpringMVC的一个控制器类,因为这个时候Spring还不认识它。那么要如何做
Spring才能认识它呢?这个时候就需要我们把这个控制器类交给Spring来管理。有两种方式:
(1)在SpringMVC 的配置文件中定义MyController 的bean 对象。
(2)在SpringMVC 的配置文件中告诉Spring 该到哪里去找标记为@Controller 的Controller 控制器。
<!--方式一-->
<bean class="com.host.app.web.controller.MyController"/>
<!--方式二-->
< context:component-scan base-package = "com.host.app.web" />
2、@RequestMapping
RequestMapping注解有六个属性,下面我们把它分成三类进行说明
(1)value,method
value:指定请求的实际地址,指定的地址可以是URI Template模式;
method:指定请求的method类型, GET、POST、PUT、DELETE等;
value的uri值可以为以下三类:普通的具体值;含有某变量的一类值;含有正则表达式的一类值;
@RequestMapping(value="/new", method = RequestMethod.GET)
public AppointmentForm getNewForm() {
return new AppointmentForm();
}
@RequestMapping(value="/owners/{ownerId}", method={RequestMethod.GET , RequestMethod.DELETE })
public String findOwner(@PathVariable String ownerId, Model model) {
Owner owner = ownerService.findOwner(ownerId);
model.addAttribute("owner", owner);
return "displayOwner";
}
@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\d\.\d\.\d}.{extension:\.[a-z]}")
public void handle(@PathVariable String version, @PathVariable String extension) {
// ...
}
}
(2)consumes,produces
consumes:指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {
// implementation omitted
}
@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {
// implementation omitted
}
(3)params,headers
params:指定request中必须包含某些参数值时,才让该方法处理。
headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。
@RequestMapping (value= "testParams" , params={ "param1=value1" , "param2" , "!param3" })
public String testParams() {
System. out .println( "test Params..........." );
return "testParams" ;
}
用@RequestMapping的params属性指定了三个参数,这些参数都是针对请求参数而言的,它们分别表示参数param1的值必须等于 value1,参数param2必须存在,值无所谓,参数param3必须不存在,只有当请求/testParams.do并且满足指定的三个参数条件的 时候才能访问到该方法。所以当请求/testParams.do?param1=value1¶m2=value2的时候能够正确访问到 该testParams方法,当请求/testParams.do?param1=value1¶m2=value2& param3=value3的时候就不能够正常的访问到该方法
@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController { @RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
// implementation omitted
}
}
仅处理request的header中包含了指定“Refer”请求头和对应值为“http://www.ifeng.com/”的请求;
3.@Resource和@Autowired
@Resource和@Autowired都是做bean的注入时使用,其实@Resource并不是Spring的注解,它的包是javax.annotation.Resource,需要导入,但是Spring支持该注解的注入。
(1)共同点
两者都可以写在字段和setter方法上。两者如果都写在字段上,那么就不需要再写setter方法。
(2)不同点
@Autowired
@Autowired为Spring提供的注解,需要导入包org.springframework.beans.factory.annotation.Autowired;只按照byType注入。
public class TestServiceImpl {
// 下面两种@Autowired只要使用一种即可
@Autowired
private UserDao userDao; // 用于字段上
@Autowired
public void setUserDao(UserDao userDao) { // 用于属性的方法上
this.userDao = userDao;
}
}
@Autowired注解是按照类型(byType)装配依赖对象,默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它的 required属性为false。如果我们想使用按照名称(byName)来装配,可以结合@Qualifier注解一起使用。如下:
public class TestServiceImpl {
@Autowired
@Qualifier("userDao")
private UserDao userDao;
}
@Resource
@Resource默认按照ByName自动注入,由J2EE提供,需要导入包javax.annotation.Resource。@Resource
有两个重要的属性:name和type,而Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的
类型。所以,如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不制定name也不
制定type属性,这时将通过反射机制使用byName自动注入策略。
public class TestServiceImpl {
// 下面两种@Resource只要使用一种即可
@Resource(name="userDao")
private UserDao userDao; // 用于字段上
@Resource(name="userDao")
public void setUserDao(UserDao userDao) { // 用于属性的setter方法上
this.userDao = userDao;
}
}
注:最好是将@Resource放在setter方法上,因为这样更符合面向对象的思想,通过set、get去操作属性,而不是直接去操作属性。
4.@PathVariable
用于将请求URL中的模板变量映射到功能处理方法的参数上,即取出uri模板中的变量作为参数。
@Controller
public class TestController {
@RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET)
public String getLogin(@PathVariable("userId") String userId,
@PathVariable("roleId") String roleId){
System.out.println("User Id : " + userId);
System.out.println("Role Id : " + roleId);
return "hello";
}
@RequestMapping(value="/product/{productId}",method = RequestMethod.GET)
public String getProduct(@PathVariable("productId") String productId){
System.out.println("Product Id : " + productId);
return "hello";
}
@RequestMapping(value="/javabeat/{regexp1:[a-z-]+}",
method = RequestMethod.GET)
public String getRegExp(@PathVariable("regexp1") String regexp1){
System.out.println("URI Part 1 : " + regexp1);
return "hello";
}
}
5.@ResponseBody
作用: 该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。
使用时机:返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用
@Controller
@RequestMapping ( "/test/{variable1}" )
public class MyController { @RequestMapping ( "/showView/{variable2}" )
public ModelAndView showView( @PathVariable String variable1, @PathVariable ( "variable2" ) int variable2) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName( "viewName" );
modelAndView.addObject( " 需要放到 model 中的属性名称 " , " 对应的属性值,它是一个对象 " );
return modelAndView;
}
}
在上面的代码中我们可以看到在标记variable1 为path 变量的时候我们使用的是@PathVariable ,而在标记variable2 的时候使用的是@PathVariable(“variable2”) 。这两者有什么区别呢?第一种情况就默认去URI 模板中找跟参数名相同的变量,但是这种情况只有在使用debug 模式进行编译的时候才可以,而第二种情况是明确规定使用的就是URI 模板中的variable2 变量。当不是使用debug 模式进行编译,或者是所需要使用的变量名跟参数名不相同的时候,就要使用第二种方式明确指出使用的是URI 模板中的哪个变量。
6.@RestController
我们经常见到一些控制器实现了REST的API,只为服务于JSON,XML或其它自定义的类型内
容,@RestController用来创建REST类型的控制器,与@Controller类型。@RestController就是这样一种类型,它
避免了你重复的写@RequestMapping与@ResponseBody。
@RestController
public class FavRestfulController { @RequestMapping(value="/getUserName",method=RequestMethod.POST)
public String getUserName(@RequestParam(value="name") String name){
return name;
}
}
SpringMVC 常用注解的更多相关文章
- SpringMVC常用注解實例詳解3:@ResponseBody
我的開發環境框架: springmvc+spring+freemarker開發工具: springsource-tool-suite-2.9.0JDK版本: 1.6.0_29tomcat ...
- SpringMVC常用注解實例詳解2:@ModelAttribute
我的開發環境框架: springmvc+spring+freemarker開發工具: springsource-tool-suite-2.9.0JDK版本: 1.6.0_29tomcat ...
- springmvc常用注解与类型转换
springmvc常用注解与类型转换 一:前置 spring -servlet.xml 注入 <!-- 启用spring mvc 注解 --> <context:annotation ...
- SpringMVC常用注解@Controller,@Service,@repository,@Component
SpringMVC常用注解@Controller,@Service,@repository,@Component controller层使用@controller注解 @Controller 用于标记 ...
- 一 : springmvc常用注解
springmvc常用注解详解1.@Controller在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层 ...
- 转:springmvc常用注解标签详解
Spring5:@Autowired注解.@Resource注解和@Service注解 - IT·达人 - 博客园--这篇顺序渐进,讲得超级好--此人博客很不错http://www.cnblogs.c ...
- SpringMVC 常用注解 详解
SpringMVC 常用注解 详解 SpringMVC 常用注解 1.@RequestMapping 路径映射 2.@Requ ...
- Spring 和 SpringMVC 常用注解和配置(@Autowired、@Resource、@Component、@Repository、@Service、@Controller的区别)
Spring 常用注解 总结内容 一.Spring部分 1.声明bean的注解 2.注入bean的注解 3.java配置类相关注解 4.切面(AOP)相关注解 5.事务注解 6.@Bean的属性支持 ...
- SpringMVC常用注解,返回方式,路径匹配形式,验证
常用注解元素 @Controller 标注在Bean的类定义处 @RequestMapping 真正让Bean具备 Spring MVC Controller 功能的是 @RequestMapping ...
随机推荐
- svn强制添加注释脚本
@echo off setlocal set SVN_BINDIR=C:/Program Files/VisualSVN Server/bin/ set REPOS=%1 set TXN=%2 rem ...
- datatables完整的增删改查
1.需要指定datatables的ID <button class="btn btn-primary" id="newAttribute">新增证照 ...
- yum安装lamp环境
装了好些次lamp环境了,都没好好总结下,现在总结下 ^ ^ 1.替换163的yum源 1.检查系统版本 cat /etc/redhat-releas (我的版本是CentOS release 6 ...
- php curl模拟post请求提交数据
最近在做校园图书馆图书信息的采集程序,既然是图书馆图书的采集,肯定有提交搜索的页面,无非是post提交,让我想到了curl模拟提交,首先通过firebug进行抓包查询下post提交后的格式如下: tx ...
- delphi cxgrid导出excel去除货币符号
版本 : devexpress 13.1.4 打开 包在ExpressExportLibary目录中. 修改FCells.SetCellDataCurrency为FCells.SetCellData ...
- Python的简介以及安装和第一个程序以及用法
Python的简介: 1.Python是一种解释型.面向对象.动态数据类型的高级程序设计语言.自从20世纪90年代初Python语言诞生至今,它逐渐被广泛应用于处理系统管理任务和Web编程.Pytho ...
- Length of Last Word | Leetcode
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the l ...
- 理解和熟练运用js中的call及apply
call 和 apply 都是为了改变某个函数运行时的 context 即上下文而存在的,换句话说,就是为了改变函数体内部 this 的指向. 因为 JavaScript 的函数存在「定义时上下文」和 ...
- ubuntu修改grub2
转自修改系统启动项 grub2配置的方法 ubuntu 在早期的Ubuntu中,使用Grub作为系统的启动引导程序,想修改系统启动项非常简单,只要用gedit打开系统菜单设定文件( sudo gedi ...
- 快速搭建Web服务器软件PHP+Apache+MySQL
搭建网站或者博客,需要一个合适的 Web 服务器.除了如下能在购买的虚拟空间上进行操作外,我们也可以在自己的电脑上搞定,因为可以用来方便快捷地测试网站或者博客主题,无论是 Wordpress.Joom ...