【springmvc】注解开发的详细使用

首先,所有注解都要提前在配置文件中开启扫描。
< context:component-scan base-package = “” />
\context:include-filter //指定扫描的路径
\context:exclude-filter //排除扫描的路径

<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
注册一个bean到spring,标记一个类为controller,这样才能被外界访问到

@RequestMapping(“/xxx”)
注册xxx请求绑定注解下面的类或方法.
该注解一共有六个属性,分别为value、method、consumes、produces、 params、headers。
value:指定请求的实际地址,指定的地址可以是URI Template 模式,即请求的URI中可以包含变量,如
/test/{variable}/log.jsp,当请求/test/haha/log.jsp时,variable1对应为’haha’,配合@PathVariable使用。
另外,该注解还支持通配符

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

@RequestMapping (value= "testMethod" , method={RequestMethod. GET , RequestMethod. DELETE })
public String testMethod() {
        return "method" ;
    }

在上面的代码中就使用method 参数限制了以GET 或DELETE 方法请求/testMethod 的时候才能访问到该Controller 的testMethod 方法

consumes:指定处理请求的提交内容类型(Content-Type),例如application/json, text/html
produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回
params:指定request中必须包含某些参数值时,才让该方法处理

@RequestMapping (value= "testParams" , params={ "param1=value1" , "param2" , "!param3" })
public String testParams() {
       System. out .println( "test Params..........." ); return "testParams" ;
    }

上面代码表面当/aa.action?后面有param1=value&param2={something}且无param3时才能成功访问下面的方法

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

@RequestMapping (value= "testHeaders" , headers={ "host=localhost" , "Accept" }) 
public String testHeaders() { 
        return "headers" ;
    }

在上面的代码中当请求/testHeaders.do 的时候只有当请求头包含Accept 信息,且请求的host 为localhost 的时候才能正确的访问到testHeaders 方法


@Resource和@Autowired
两者都用来注入bean,@Resource其实并不是spring的注解,仔细看import部分可以看到是javax.annotation.*下的包。
共同点:可以写在bean的声明或者setter方法上,如果写在字段上,就不用写setter方法。
不同点:
@Autowired是按照类型装配对象,默认要求依赖对象必须存在,如果允许存在,设置required属性为false。按名称装配时要加@Qualifier(“xxx”)
@Resource默认按名称装配,需要配置name属性@Resource(name=”xxx”),也可以设置type属性来按类型装配。


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

@ModelAttribute ( "hello" ) 
public String getModel() {
      System. out .println( "-------------Hello---------" );
      return "world" ;
   }

上面代码会在访问方法执行前执行,打印,并把字符串”world”存入model对象中,对应关键字为”hello”
也可以在另外的方法参数前加上@ModelAttribute(“xxx”)即可把model里的xxx值映射到这个参数里

@SessionAttributes
将值放到session作用域中,写在class上面。

@SessionAttributes(value={"name","theid"},type={User.class})
public class MyController{
    //xxxxxx....
}

上面的代码指定了遇到属性name或者theid或者User类型使用modelattribute注解存放的时候,都会存放到session对象里。当 @ModelAttribute 标记在处理器方法参数上的时候,表示该参数的值将从模型或者 Session 中取对应名称的属性值,该名称可以通过 @ModelAttribute(“attributeName”) 来指定,若未指定,则使用参数类型的类名称(首字母小写)作为属性名称
}


request uri部分(variable/)
@PathVariable
用来将URL中的变量映射到方法的参数里

@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";  
}

request body部分{

@RequestParam
主要用于在SpringMVC后台控制层获取参数,类似一种是request.getParameter(“name”),它有三个常用参数:defaultValue = “0”, required = false, value = “isApp”;defaultValue 表示设置默认值,required 通过boolean设置是否是必须要传入的参数,value 值表示接受的传入的参数类型

public String setupForm(@RequestParam("petId") int petId, ModelMap model) {  
    //xxx 
 }    

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

@RequestMapping(value = "/something", method = RequestMethod.PUT) 
public void handle(@RequestBody String body, Writer writer) throws IOException {  
  writer.write(body);  
}

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

}


request header部分{
@RequestHeader

public  void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive")   long  keepAlive) {
}

这段代码把request header部分的Accept-Encoding和Keep-Alive值映射到对应的参数里。

@CookieValue

@RequestMapping("/displayHeaderInfo.do") public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie)  {  
}

上面代码把cookie里的JSESSIONID值映射到对应的参数里。

}


@Component
通用的注解,当不知道一个类归于哪层时,使用。不推荐使用。

@Repository
注解dao层,在daoImpl类上注解