Spring MVC 常用注解

Spring mvc常用4个基本注解

@Component、@Repository 、@Service、@Controller

@Controller 控制层 ,通常我们所说的action层

@Service 业务逻辑层,通常我们所说的service层或者manger层

@Repository 持久层,通常我们所说的Dao层

@Component 组件,书面意思就是我们不知道在哪一层时使用

虽然对于spring来说,这4个注解的效果都是一样的,当spring扫描到这些注解时,都会当做需要注入的bean加载到上下文中

但是在项目中,我们应该严格按照这几个注解的含义来使用,这样有利于我们web架构

1、控制层

[java]  view plain  copy
  1. @Controller  
  2. @RequestMapping("/")  
  3. public class HelloController {  
  4.     @Autowired  
  5.     @Qualifier("kbCityService")  
  6.     private KbCityService kbCityService;  
  7. <span style="white-space:pre">    *****以下代码省略*****</span>  
  8. }  
2、业务逻辑层

[java]  view plain  copy
  1. @Service("kbCityService")  
  2. public class KbCityServiceImpl implements KbCityService{  
  3.     @Autowired  
  4.     @Qualifier("kbCityMapper")  
  5.     private KbCityMapper kbCityMapper;  
  6.   
  7.     ********其他代码省略***********  
  8. }  


3、持久层
[java]  view plain  copy
  1. @Repository("kbCityMapper")  
  2. public interface KbCityMapper {  
  3.   
  4.    ********其他代码省略***********  
  5.   
  6. }  


持久层也可以不写,在配置文件中添加如下代码也可以:

[html]  view plain  copy
  1.       <bean id="kbCityMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">  
  2. <property name="mapperInterface" value="com.spring.dao.KbCityMapper" />  
  3. <property name="sqlSessionFactory" ref="sqlSessionFactory" />  
  4. lt;/bean>  

一、@RequestMapping简介

@RequestMapping是用来映射URL,它可用在类定义处和方法定义处。我们映射的url是相对于根目录而言的,如代码所示:

[java]  view plain  copy
  1. package com.gray.user.controller;    
  2.     
  3. import org.springframework.beans.factory.annotation.Autowired;    
  4. import org.springframework.stereotype.Controller;    
  5. import org.springframework.ui.Model;    
  6. import org.springframework.web.bind.annotation.RequestMapping;    
  7.     
  8. import com.gray.user.entity.User;    
  9. import com.gray.user.service.impl.UserServiceImpl;    
  10.     
  11. @Controller    
  12. @RequestMapping("/test")     
  13. public class LoginController {    
  14.     @Autowired    
  15.     private UserServiceImpl userService;    
  16.     
  17. @RequestMapping("/dologin.do"//url    
  18. public String dologin(User user, Model model){    
  19.     if(userService.doUserLogin(user)){    
  20.         model.addAttribute("successMsg""登陆成功!");//返回到页面所夹带的参数    
  21.         model.addAttribute("name", user.getUsername());    
  22.         return "/success";//返回的页面    
  23.     }else{    
  24.         model.addAttribute("failMsg""用户不存在或密码错误!");    
  25.         return "/fail";    
  26.     }       
  27. }    
  28. }   
dologin方法所映射的url地址我们写成 http://localhost:9090/test/dologin.do

关于RequestMapping这个注解,里面一共有6个属性

1.value

指定请求的实际地址;

2.method

指定请求的method类型, GET、POST、PUT、DELETE等;

3.consumes

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

4.produces

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

5.params

指定request中必须包含某些参数值;

6.headers

指定request中必须包含某些指定的header值;

二、@PathVariable简介

当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId}, 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。

三、@RequestBody简介

             该注解用于读取Request请求的body部分数据,这主要是通过spring的消息转换器messageConverter实现的,首先我们需要在配置文件里面配上这个bean,通过已经配置的消息转换器把相应的数据转换成要传入的对象进而绑定到方法的参数中。

四、@RequestParam简介

             在处理方法入参处使用 @RequestParam 可以把请求参数传递给请求方法,我们可以对传入参数指定参数名,前端传进来的参数名要和这个value值一致我们也可以通过required=false或者true来要求@RequestParam配置的前端参数是否一定要传。

五、@ResponseBody简介

和@RequestBody相似的用法,根据配置的消息转换器将对象转换为指定格式后,写入到Response对象的body数据区。

六、@CookieValue简介

从Http请求头中的Cookie提取指定的某个Cookie。

七、常见注解用法实例

  1. 关于@RequestMapping
  • value

value是默认属性,即@RequestMapping("/dologin.do")和@RequestMapping(value="/dologin.do")是等价的。

  • method

@RequestMapping(value = {"/ws/createEmployeeBasic","/ws/updateEmployeeBasic"}, method = RequestMethod.POST)

注:mapping的value是可以写多个的。

  • consumes

consumes="application/json",就是需要参数以json格式传进来我才能接收。如1的代码所示,随后我们把传进来的数据通过@RequestBody转换成我要的对象。

  • produces

@RequestMapping(value="/test.do",produces="application/json;charset=UTF-8"),和上面那个用法差不多。两者区别就是前者只管请求,后者两个都管。

  • params

@RequestMapping(value="/dologin.do",params={"user=gray","pwd=111111"})

这种写法就限制了只有当传进来的参数user=gray并且pwd=111111时才能映射到下面的方法,否则报404。

  • headers

老实说这个用法我几乎没用过。它用于指定请求头里面的参数,限客户端的请求。如:

@RequestMapping(value="/dologin.do", headers="Host=localhost:9090")

这种写法就是限制了只有本机发来的请求才接收。

        2.关于@RequestBody和@PathVariable

在这里我要说一下,带占位符的url,是Spring 3.0的新功能,我在项目中实现restful风格的url就是根据这个来实现的。

例如:

[java]  view plain  copy
  1. @RequestMapping(value = "/ws/OEmployeeBasic/{token}/{timestamp}", method = RequestMethod.POST, consumes="application/json")  
  2. @ResponseBody  
  3. public void pageList(  
  4.         @RequestBody Employee emp,  
  5.         @PathVariable String token, @PathVariable String timestamp,   
  6.         HttpServletRequest request, HttpServletResponse response){  
  7.     ......  
  8. }  
{token}等需要通过@PathVariable注解将占位符中的参数绑定到方法的参数中。

       3.关于@ResponseBody

在springmvc的开发中,所有返回数据的请求都需要加上这个注解。如:

[java]  view plain  copy
  1. @RequestMapping("/myEspPageList.do")  
  2. @ResponseBody  
  3. public Object myPageList(Employee emp, HttpServletRequest request, HttpServletResponse response){  
  4.     Object obj = super.pageList(emp, request, response);  
  5.     return obj;  
  6. }  

        4.关于@RequestParam

[java]  view plain  copy
  1.       @RequestMapping("/empTableList.do")  
  2. ublic String list(Model model,@RequestParam(value="tabs",required=false)Integer tabs){  
  3. if (tabs == null || tabs > 3 || tabs < 0) tabs = 0// tabs只允许0/1/2/3,默认为0  
  4. model.addAttribute("tabs",tabs);  
  5. return "/configuration/basetable_list";  
正如上面所说的,返回页面是不需要加 @ResponseBody

1.@RequestMapping

国际惯例先介绍什么是@RequestMapping,@RequestMapping 是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径;用于方法上,表示在类的父路径下追加方法上注解中的地址将会访问到该方法,此处需注意@RequestMapping用在类上可以没用,但是用在方法上必须有

例如:

@Controller
//设置想要跳转的父路径
@RequestMapping(value = "/Controllers")
public class StatisticUserCtrl {
    //如需注入,则写入需要注入的类
    //@Autowired

            // 设置方法下的子路经
            @RequestMapping(value = "/method")
            public String helloworld() {

                return "helloWorld";

            }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

其原理也非常好了解,其对应的 action 就是“ (父路径) controller/(父路径下方法路经)method ”。因此,在本地服务器上访问方法 http://localhost:8080/controller/method 就会返回(跳转)到“ helloWorld.jsp ”页面。

说到这了,顺便说一下 @PathVariable 注解,其用来获取请求路径(url )中的动态参数。

页面发出请求:

function login() {
    var url = "${pageContext.request.contextPath}/person/login/";
    var query = $('#id').val() + '/' + $('#name').val() + '/' + $('#status').val();
    url += query;
    $.get(url, function(data) {
        alert("id: " + data.id + "name: " + data.name + "status: "
                + data.status);
    });
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

例如:

/**
* @RequestMapping(value = "user/login/{id}/{name}/{status}") 中的 {id}/{name}/{status}
* 与 @PathVariable int id、@PathVariable String name、@PathVariable boolean status
* 一一对应,按名匹配。
*/

@RequestMapping(value = "user/login/{id}/{name}/{status}")
@ResponseBody
//@PathVariable注解下的数据类型均可用
public User login(@PathVariable int id, @PathVariable String name, @PathVariable boolean status) {
//返回一个User对象响应ajax的请求
    return new User(id, name, status);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

@ResponseBody

@Responsebody 注解表示该方法的返回的结果直接写入 HTTP 响应正文(ResponseBody)中,一般在异步获取数据时使用,通常是在使用 @RequestMapping 后,返回值通常解析为跳转路径,加上 @Responsebody 后返回结果不会被解析为跳转路径,而是直接写入HTTP 响应正文中。 
作用: 
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。 
使用时机: 
返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

当页面发出异步请求:

function login() {
    var datas = '{"username":"' + $('#username').val() + '","userid":"' + $('#userid').val() + '","status":"' + $('#status').val() + '"}';
    $.ajax({
        type : 'POST',
        contentType : 'application/json',
        url : "${pageContext.request.contextPath}/user/login",
        processData : false,
        dataType : 'json',
        data : datas,
        success : function(data) {
            alert("userid: " + data.userid + "username: " + data.username + "status: "+ data.status);
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            alert("出现异常,异常信息:"+textStatus,"error");
        }
    });
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

例如:

@RequestMapping(value = "user/login")
@ResponseBody
// 将ajax(datas)发出的请求写入 User 对象中,返回json对象响应回去
public User login(User user) {   
    User user = new User();
    user .setUserid(1);
    user .setUsername("MrF");
    user .setStatus("1");
    return user ;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

异步获取 json 数据,加上 @Responsebody 注解后,就会直接返回 json 数据。

@RequestBody

@RequestBody 注解则是将 HTTP 请求正文插入方法中,使用适合的 HttpMessageConverter 将请求体写入某个对象。

作用:

1) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上; 
2) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。

使用时机:

A) GET、POST方式提时, 根据request header Content-Type的值来判断:

application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理); 
multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据); 
其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);

B) PUT方式提交时, 根据request header Content-Type的值来判断:

application/x-www-form-urlencoded, 必须;multipart/form-data, 不能处理;其他格式, 必须;

说明:request的body部分的数据编码格式由header部分的Content-Type指定;

例如:

@RequestMapping(value = "user/login")
@ResponseBody
// 将ajax(datas)发出的请求写入 User 对象中
public User login(@RequestBody User user) {   
// 这样就不会再被解析为跳转路径,而是直接将user对象写入 HTTP 响应正文中
    return user;    
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

猜你喜欢

转载自blog.csdn.net/qq_35427437/article/details/80228596