您的位置:首页 > 编程语言 > Java开发

SpringMVC常用注解详解

2017-05-09 18:27 190 查看

先说扫描注解

<context:component-scan base-package = "" />

component-scan 默认扫描的注解类型是 @Component,不过,在 @Component 语义基础上细化后的 @Repository, @Service 和 @Controller 也同样可以获得 component-scan 的青睐

有了
<context:component-scan>
,另一个
<context:annotation-config/>
标签根本可以移除掉,因为已经被包含进去了

另外
<context:annotation-config/>
还提供了两个子标签

1.
<context:include-filter> //指定扫描的路径


2.
<context:exclude-filter> //排除扫描的路径


<context:component-scan>
有一个use-default-filters属性,属性默认为true,表示会扫描指定包下的全部的标有@Component的类,并注册成bean.也就是@Component的子注解@Service,@Reposity等。

这种扫描的粒度有点太大,如果你只想扫描指定包下面的Controller或其他内容则设置use-default-filters属性为false,表示不再按照scan指定的包扫描,而是按照
<context:include-filter>
指定的包扫描,示例:

<context:component-scan base-package="com.tan" use-default-filters="false">
<context:include-filter type="regex" expression="com.tan.*"/>//注意后面要写.*
</context:component-scan>


当没有设置use-default-filters属性或者属性为true时,表示基于base-packge包下指定扫描的具体路径

<context:component-scan base-package="com.tan" >
<context:include-filter type="regex" expression=".controller.*"/>
<context:include-filter type="regex" expression=".service.*"/>
<context:include-filter type="regex" expression=".dao.*"/>
</context:component-scan>


效果相当于:

<context:component-scan base-package="com.tan" >
<context:exclude-filter type="regex" expression=".model.*"/>
</context:component-scan>


注意:
无论哪种情况<context:include-filter>和<context:exclude-filter>都不能同时存在


@Controller

在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ,然后再把该Model 返回给对应的View 进行展示。在SpringMVC 中提供了一个非常简便的定义Controller 的方法,你无需继承特定的类或实现特定的接口,只需使用@Controller 标记一个类是Controller ,然后使用@RequestMapping 和@RequestParam 等一些注解用以定义URL 请求和Controller 方法之间的映射,这样的Controller 就能被外界访问到。此外Controller 不会直接依赖于HttpServletRequest 和HttpServletResponse 等HttpServlet 对象,它们可以通过Controller 的方法参数灵活的获取到

@Controller
public class SpringMVCController {
@RequestMapping("/index")
public ModelAndView index(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
modelAndView.addObject("sunwukong");
return modelAndView;
}
}


ModelAdnView的addObject底层其实就是往HashMap里put值,我们可以看下源码实现

public ModelAndView addObject(Object attributeValue)
{
getModelMap().addAttribute(attributeValue);
return this;
}


在进一步看下addAttribute的实现

public ModelMap addAttribute(String attributeName, Object attributeValue)
{
Assert.notNull(attributeName, "Model attribute name must not be null");
put(attributeName, attributeValue);
return this;
}
// put方法就是HashMap的put
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}


@Controller 用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象。分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用了@RequestMapping 注解。@Controller 只是定义了一个控制器类,而使用@RequestMapping 注解的方法才是真正处理请求的处理器 。单单使用@Controller 标记在一个类上还不能真正意义上的说它就是SpringMVC 的一个控制器类,因为这个时候Spring 还不认识它。把这个控制器类交给Spring 来管理的方法有两种如下

1、在SpringMVC的配置文件中定义SpringMVCController的bean 对象

<bean class="com.nyonline.sp2p.controller.SpringMVCController"/>


2、在SpringMVC的配置文件中让Spring去扫描获取

< context:component-scan base-package = "com.nyonline.sp2p.controller" >
< context:exclude-filter type = "annotation"
expression = "org.springframework.stereotype.Service" /> <!-- 排除@service -->
</ context:component-scan


@RequestMapping

RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。RequestMapping注解有六个属性,下面我们把她分成三类进行说明

1、value与Method

/**
* value:指定请求的实际地址,指定的地址可以是URI Template 模式
* method:指定请求的method类型, GET、POST、PUT、DELETE等吗,更接近rest模式
* @return
*/
@RequestMapping (value= "testMethod" , method={RequestMethod.GET ,RequestMethod.DELETE})
public String testMethod() {
return "method" ;
}


2、consumes与produces

consumes:指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回

/**
* 方法仅处理request Content-Type为“application/json”类型的请求.
* produces标识==>处理request请求中Accept头中包含了"application/json"的请求,
* 同时暗示了返回的内容类型为application/json
* @return
*/
@RequestMapping (value= "testConsumes" ,consumes = "application/json",produces = "application/json")
public String testConsumes() {
return "consumes" ;
}


3、params与headers

params:指定request中必须包含某些参数值是,才让该方法处理。

headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。

/**
* headers 属性的用法和功能与params 属性相似。在上面的代码中当请求/testHeaders.do的时候只有当请求头包含Accept信息,
* 且请求的host 为localhost和name=sunwukong的时候才能正确的访问到testHeaders方法。
* @return
*/
@RequestMapping (value= "testHeaders" , headers={ "host=localhost" , "Accept"},params={"name=sunwukong"})
public String testHeaders() {
return "headers" ;
}


@Resource和@Autowired

@Resource和@Autowired都是做bean的注入时使用,其实@Resource并不是Spring的注解,它的包是javax.annotation.Resource,需要导入,但是Spring支持该注解的注入。

1、共同点

两者都可以写在字段和setter方法上。两者如果都写在字段上,那么就不需要再写setter方法

2、不同点

@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默认按照ByName自动注入,由J2EE提供,需要导入包javax.annotation.Resource。@Resource有两个重要的属性:name和type,而Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以,如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不制定name也不制定type属性,这时将通过反射机制使用byName自动注入策略。

@Resource(name="ad")
private AdBo ad;

@Resource(type=BidBo.class)
private BidBo bid;


①如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常。

②如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常。

③如果指定了type,则从上下文中找到类似匹配的唯一bean进行装配,找不到或是找到多个,都会抛出异常。

④如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配。

@Resource的作用相当于@Autowired,只不过@Autowired按照byType自动注入。

@ModelAttribute

代表的是:该Controller的所有方法在调用前,先执行此@ModelAttribute方法,可用于注解和方法参数中,可以把这个@ModelAttribute特性,应用在BaseController当中,所有的Controller继承BaseController,即可实现在调用Controller时,先执行@ModelAttribute方法。

@modelAttribute可以在两种地方使用,参数和方法体,

先介绍下方法体的用法

@ModelAttribute("user")
public User getUser() {
User user = new User();
user.setId(1234567L);
user.setName("sunwukong");
user.setPassword("admin");
return user;
}
@RequestMapping(value = "testUser", method = {RequestMethod.GET, RequestMethod.POST})
public String testUser(Map<String, Object> map) {
System.out.println(map.get("user"));
return "success";
}


当我们发出/testUser.do这个请求时,SpringMvc 在执行该请求前会先逐个调用在方法级上标注了

@ModelAttribute 的方法,然后将该模型参数放入testUser()函数的Map参数中

执行结果:

User{id=123456,name=”sunwukong”,password=”admin”}

作用在参数上

SpringMVC先从模型数据中获取对象,再将请求参数绑定到对象中,再传入形参,并且数据模型中的对象会被覆盖

@RequestMapping(value = "test1")
public ModelAndView test1(@ModelAttribute("user1") User user, ModelAndView modelAndView) {
System.out.println(user + ":test1");
modelAndView.setViewName("redirect:/test2.do");
return modelAndView;
}
@RequestMapping(value = "test2", method = { RequestMethod.GET, RequestMethod.POST })
public String test2(Map<String, Object> map) {
System.out.println(map.get("user1"));
return "success";
}
@ModelAttribute("user1")
public User getUser() {
User user = new User();
user.setId(123456L);
user.setName("sunwukong");
user.setPassword("admin");
return user;
}


访问http://localhost/test1.do?name=qitiandasheng,输出结果:

User{id=123456,name=”齐天大圣”,password=”admin”}

我们传入了name此时user的name被传入的值覆盖,如果请求参数中有的参数已经绑定到了user中,那么请求参数会覆盖掉user中已存在的值,并且user对象会被放入数据模型中覆盖掉原来的user1对象。也就是模型数据中的user1的优先级低于请求参数

@SessionAttributes

该注解用来绑定HttpSession中的attribute对象的值,便于在方法中的参数里使用。

@Controller
@SessionAttributes(value = {"user1"})
public class SpringMVCController {

@RequestMapping(value = "test4", method = {RequestMethod.GET, RequestMethod.POST})
public String test4(Map<String, Object> map, HttpSession session) {
System.out.println(map.get("user1"));
System.out.println("session:" + session.getAttribute("user1"));
return "success";
}
@ModelAttribute("user1")
public User getUser() {
User user = new User();
user.setId(123456L);
user.setName("sunwukong");
user.setPassword("admin");
return user;
}
}


当我第一次执行test4.do输出结果:

User [id=123456, name=sunwukong, password=admin]

session:null

第二次执行

User [id=123456, name=sunwukong, password=admin]

session:User [id=123456, name=sunwukong, password=admin]

只是在第一次访问 test4.do 的时候 @SessionAttributes 定义了需要存放到 session 中的属性,而且这个模型中也有对应的属性,但是这个时候还没有加到 session 中,所以 session 中不会有任何属性,等处理器方法执行完成后 Spring 才会把模型中对应的属性添加到 session 中。

@PathVariable和@RequestParam

请求路径上有个id的变量值,可以通过@PathVariable来获取
@RequestMapping(value = "/page/{id}", method = RequestMethod.GET)


@RequestParam用来获得静态的URL请求入参,spring注解时action里用到。它有三个常用参数:defaultValue = “0”, required = false, value = “pageNo”;defaultValue 表示设置默认值,required 通过boolean设置是否是必须要传入的参数,value 值表示接受的传入的参数类型。

例如:

地址①

http://localhost:8989/test/index?pageNo=2

地址②

http://localhost:8989/test/index/7

如果想获取地址①中的 pageNo的值 ‘2’ ,则使用 @RequestParam ,

如果想获取地址②中的 emp/7 中的 ‘7 ’ 则使用 @PathVariable

@RequestMapping("/index")
public String list(@RequestParam(value="pageNo",required=false,
defaultValue="1")String pageNoStr,Map<String, Object>map){

int pageNo = 1;

try {
//对pageNo 的校验
pageNo = Integer.parseInt(pageNoStr);
if(pageNo<1){
pageNo = 1;
}
} catch (Exception e) {}

Page<Employee> page = employeeService.getPage(pageNo, 5);
map.put("page",page);

return "index/list";
}

@RequestMapping(value="/index/{id}",method=RequestMethod.GET)
public String edit(@PathVariable("id")Integer id,Map<String , Object>map){
Employee employee = employeeService.getEmployee(id);
List<Department> departments = departmentService.getAll();
map.put("employee", employee);
map.put("departments", departments);
return "index/input";
}


@ResponseBody

该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

使用时机:返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

/**
* 返回处理结果到前端
* @param msg: Success or fail。
* @throws IOException
*/
public void sendToCFT(String msg) throws IOException {
String strHtml = msg;
PrintWriter out = this.getHttpServletResponse().getWriter();
out.println(strHtml);
out.flush();
out.close();

}


如果用SpringMVC注解

@ResponseBody
@RequestMapping("/pay/tenpay")
public String tenpayReturnUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
unpackCookie(request, response);
payReturnUrl.payReturnUrl(request, response);
return "pay/success";
}


@Component

泛指组件,当组件不要好归类时,可以使用这个注解进行标注

@Repository

用于注解dao层,在daoImpl类上面注解。

@Repository(value=”userDao”)注解是告诉Spring,让Spring创建一个名字叫“userDao”的UserDaoImpl实例

@RequestBody

@RequestBody接收的是一个Json对象的字符串,而不是一个Json对象。然而在ajax请求往往传的都是Json对象,后来发现用 JSON.stringify(data)的方式就能将对象变成字符串。同时ajax请求的时候也要指定dataType: “json”,contentType:”application/json” 这样就可以轻易的将一个对象或者List传到Java端,使用@RequestBody即可绑定对象或者List

<script type="text/javascript">
$(document).ready(function(){
var saveDataAry=[];
var data1={"userName":"test","address":"gz"};
var data2={"userName":"ququ","address":"gr"};
saveDataAry.push(data1);
saveDataAry.push(data2);
$.ajax({
type:"POST",
url:"user/saveUser",
dataType:"json",
contentType:"application/json",
data:JSON.stringify(saveData),
success:function(data){

}
});
});
</script>


Java代码:

@RequestMapping(value = "saveUser", method = {RequestMethod.POST }})
@ResponseBody
public void saveUser(@RequestBody List<User> users) {
userService.batchSave(users);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: