菜鸟之路——Spring MVC(九)常用注解

来源:互联网 发布:淘宝弹力椅套 编辑:程序博客网 时间:2024/05/17 22:22

  抛开长长的xml文件,注解能解放我们的双手。我们就一起来看看Spring MVC 4中常用的那些注解。

  spring开启注解的配置如下,先需在XML头文件下引入 spring-context,然后:

<!-- 开启自动扫描 --><context:annotation-config/> <context:component-scan base-package="com.itxxz" use-default-filters="false"><context:include-filter type="annotation" expression="org.springframework.stereotype.Service" /><context:include-filter type="annotation" expression="org.springframework.stereotype.Repository" /><context:include-filter type="annotation" expression="org.springframework.stereotype.Component" /></context:component-scan>

  1、首先我们要指定包路径( base-package="com.itxxz" ),也就是项目中的dao、service、controller(或action)所在的目录。
  2、开启注解,也就是以上配置中的 Service、 Repository、 Component 三个声明。

  一、@Controller

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

  @Controller 用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象。分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用了@RequestMapping 注解。@Controller 只是定义了一个控制器类,而使用@RequestMapping 注解的方法才是真正处理请求的处理器。

  二、@RequestMapping

 RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径,此类路径下的方法都要加上其配置的路径。最常用是标注在方法上,表明哪个具体的方法来接受处理某次请求。

@Controller@RequestMapping(value="/book")public class BookController {@RequestMapping(value="/title")public String getTitle(){return "title";}@RequestMapping(value="/content")public String getContent(){return "content";}}
  @RequestMapping的value值前后是否有“/”对请求的路径没有影响,即value="title" 、"/title"、"/title/"其效果是一样的。

  RequestMapping注解有六个属性,下面我们把她分成三类进行说明。
  1、value, method
  value: 指定请求的实际地址,指定的地址可以是URI Template 模式或普通的具体值。如前面的value="/title"。URI 模板就是在URI 中给定一个变量,然后在映射的时候动态的给该变量赋值。如URI 模板http://localhost:8080/app/{variable1}/index.html ,这个模板里面包含一个变量variable1 ,那么当我们请求http://localhost:8080/app/hello/index.html 的时候,该URL 就跟模板相匹配,只是把模板中的variable1 用hello 来取代。这个变量在SpringMVC 中是使用@PathVariable 来标记的。在SpringMVC 中,我们可以使用@PathVariable 来标记一个Controller 的处理方法参数,表示该参数的值将使用URI 模板中对应的变量的值来赋值,如:

@RequestMapping(value="/get/{bookId}")public String getBookById(@PathVariable String bookId,Model model){model.addAttribute("bookId", bookId);return "book";}
      value还能灵活运用含正则表达式的一类值,比如:

  @RequestMapping(value="/get/{idPre:\\d+}-{idNum:\\d+}"):可以匹配“/get/123-1”,但不能匹配“/get/abc-1”,这样可以设计更加严格的规则。可以通过@PathVariable 注解提取路径中的变量(idPre,idNum)。

  还能灵活运用或关系:

@RequestMapping(value={"/get","/fetch"} )即 /get或/fetch都会映射到该方法上

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

@RequestMapping(value="/get/{bookid}",method={RequestMethod.GET,RequestMethod.POST})
  2、consumes,produces
  consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
  produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
  3、params,headers
  params: 指定request中必须包含某些参数值是,才让该方法处理。

@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&pram2=value2 的时候能够正确访问到该testParams 方法,当请求/testParams.do?param1=value1&pram2=value2&pram3=value3 的时候就不能够正常的访问到该方法,因为在@RequestMapping 的params 参数里面指定了参数param3 是不能存在的。
  headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。如:

  @RequestMapping(value="/header/id", headers = "Accept=application/json"):表示请求的URL必须为“/header/id 且 请求头中必须有“Accept =application/json”参数即可匹配。

  @RequestMapping 还可以使用 @Validated与BindingResult联合验证输入的参数,在验证通过和失败的情况下,分别返回不同的视图,比如:

@RequestMapping(value="/addUser", method=RequestMethod.GET)    public String addFavUser(@Validated FavUser favUser,BindingResult result){        if(result.hasErrors()){            return "favUser";        }        return "redirect:/favlist";    }
     @RequestMapping 中还支持通配符“* ”。如下面的代码就可以使用/myTest/whatever/wildcard.do 访问到Controller 的testWildcard 方法:

@Controller@RequestMapping ( "/myTest" )public class MyController {    @RequestMapping ( "*/wildcard" )    public String testWildcard() {       System. out .println( "wildcard------------" );       return "wildcard" ;    }  }

  @RequestMapping 标记的处理器方法支持的方法参数和返回类型:

  1. 支持的方法参数类型

 (1)HttpServlet 对象,主要包括HttpServletRequest 、HttpServletResponse 和HttpSession 对象。 这些参数Spring 在调用处理器方法的时候会自动给它们赋值,所以当在处理器方法中需要使用到这些对象的时候,可以直接在方法上给定一个方法参数的申明,然后在方法体里面直接用就可以了。但是有一点需要注意的是在使用HttpSession 对象的时候,如果此时HttpSession 对象还没有建立起来的话就会有问题。

 (2)Spring 自己的WebRequest 对象。 使用该对象可以访问到存放在HttpServletRequest 和HttpSession 中的属性值。
 (3)InputStream 、OutputStream 、Reader 和Writer 。 InputStream 和Reader 是针对HttpServletRequest 而言的,可以从里面取数据;OutputStream 和Writer 是针对HttpServletResponse 而言的,可以往里面写数据。

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

 (4)使用@PathVariable 、@RequestParam 、@CookieValue 和@RequestHeader 标记的参数。
 (5)使用@ModelAttribute 标记的参数。
 (6)java.util.Map 、Spring 封装的Model 和ModelMap。这些都可以用来封装模型数据,用来给视图做展示。
 (7)实体类。可以用来接收上传的参数。
 (8)Spring 封装的MultipartFile。用来接收上传文件的。
 (9 )Spring 封装的Errors 和BindingResult 对象。这两个对象参数必须紧接在需要验证的实体对象参数之后,它里面包含了实体对象的验证结果。
  2. 支持的返回类型
 (1)一个包含模型和视图的ModelAndView 对象。
 (2)一个模型对象,这主要包括Spring 封装好的Model 和ModelMap,以及java.util.Map,当没有视图返回的时候视图名称将由RequestToViewNameTranslator 来决定。
 (3)一个View对象。这个时候如果在渲染视图的过程中模型的话就可以给处理器方法定义一个模型参数,然后在方法体里面往模型中添加值。
 (4)一个String 字符串。这往往代表的是一个视图名称。这个时候如果需要在渲染视图的过程中需要模型的话就可以给处理器方法一个模型参数,然后在方法体里面往模型中添加值就可以了。
 (5)返回值是void 。这种情况一般是我们直接把返回结果写到HttpServletResponse 中了,如果没有写的话,那么Spring 将会利用RequestToViewNameTranslator 来返回一个对应的视图名称。如果视图中需要模型的话,处理方法与返回字符串的情况相同。
 (6)如果处理器方法被注解@ResponseBody 标记的话,那么处理器方法的任何返回类型都会通过HttpMessageConverters 转换之后写到HttpServletResponse 中,而不会像上面的那些情况一样当做视图或者模型来处理。
 (7)除以上几种情况之外的其他任何返回类型都会被当做模型中的一个属性来处理,而返回的视图还是由RequestToViewNameTranslator 来决定,添加到模型中的属性名称可以在该方法上用@ModelAttribute(“attributeName”) 来定义,否则将使用返回类型的类名称的首字母小写形式来表示。使用@ModelAttribute 标记的方法会在@RequestMapping 标记的方法执行之前执行。

   三、@PathVariable

  此注解前面已经提及,主要用于注解方法参数并将其绑定到URI模板变量的值上。@PathVariable 可以有多个注解,像下面这样:
@RequestMapping(value="/owners/{ownerId}/pets/{petId}", method=RequestMethod.GET)public String findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    Owner owner = ownerService.findOwner(ownerId);    Pet pet = owner.getPet(petId);    model.addAttribute("pet", pet);        return "displayPet";}
   @PathVariable中的参数可以是任意的简单类型,如int, long, Date等等。Spring会自动将其转换成合适的类型或者抛出 TypeMismatchException异常。当然,我们也可以注册支持额外的数据类型。
  如果@PathVariable使用Map<String, String>类型的参数时, Map会填充到所有的URI模板变量中。
  @PathVariable还支持使用正则表达式,这就决定了它的超强大属性,它能在路径模板中使用占位符,可以设定特定的前缀匹配,后缀匹配等自定义格式。

  四、@RequestParam

  @RequestParam主要用于在SpringMVC后台控制层获取参数,类似一种是request.getParameter("name"),它有三个常用参数:defaultValue = "0", required = false, value = "isApp";defaultValue 表示设置默认值,required 通过boolean设置是否是必须要传入的参数,value 值表示接受的传入的参数类型。其实,即使不配置该参数,注解也会默认使用该参数,如

@Controller  @RequestMapping("/pets")  @SessionAttributes("pet")  public class EditPetForm {     @RequestMapping(method = RequestMethod.GET)     public String setupForm(@RequestParam("petId") int petId, ModelMap model) {       Pet pet = this.clinic.loadPet(petId);       model.addAttribute("pet", pet);       return "petForm";     }} 

  几个常用参数绑定注解的区别:

  handler method 参数绑定常用的注解,我们根据他们处理的Request的不同内容部分分为四类:(主要讲解常用类型)
  1、处理requet uri 部分(这里指uri template中variable,不含queryString部分)的注解: @PathVariable;
  2、处理request header部分的注解: @RequestHeader, @CookieValue;
  3、处理request body部分的注解:@RequestParam, @RequestBody;
  4、处理attribute类型是注解: @SessionAttributes, @ModelAttribute;

  请求路径上有个id的变量值,可以通过@PathVariable来获取 @RequestMapping(value = "/page/{id}", method = RequestMethod.GET) ,@PathVariable绑定到方法的参数上。若方法参数名称和需要绑定的uri template中变量名称不一致,需要在@PathVariable("name")指定uri template中的名称。而@RequestParam用来获得静态的URL请求入参 spring注解时action里用到。

  @RequestParam 常用来处理简单类型的绑定,通过Request.getParameter() 获取的String可直接转换为简单类型的情况( String--> 简单类型的转换操作由ConversionService配置的转换器来完成);因为使用request.getParameter()方式获取参数,所以可以处理get 方式中queryString的值,也可以处理post方式中 body data的值;

  @RequestHeader 

  该注解,可以把Request请求header部分的值绑定到方法的参数上,如:

这是一个Request 的header部分:Host                    localhost:8080  Accept                  text/html,application/xhtml+xml,application/xml;q=0.9  Accept-Language         fr,en-gb;q=0.7,en;q=0.3  Accept-Encoding         gzip,deflate  Accept-Charset          ISO-8859-1,utf-8;q=0.7,*;q=0.7  Keep-Alive              300  
@RequestMapping("/displayHeaderInfo.do")  public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,                                @RequestHeader("Keep-Alive") long keepAlive)  {  }  
     上面的代码,把request header部分的 Accept-Encoding的值,绑定到参数encoding上了, Keep-Alive header的值绑定到参数keepAlive上。

  @CookieValue 

  可以把Request header中关于cookie的值绑定到方法的参数上。例如有如下Cookie值:

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

  即把JSESSIONID的值绑定到参数cookie上。

  @RequestBody 

  具体是指方法参数应该被绑定到HTTP请求Body上。该注解常用来处理Content-Type不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等。需要注意的是,例如当为application/json时,接收的是一个Json对象的字符串,而不是一个Json对象,一般用于处理ajax请求往往传的都是Json对象,这时可以用 JSON.stringify(data)的方式就能将对象变成字符串。同时ajax请求的时候也要指定dataType: "json",contentType:"application/json" 这样就可以轻易的将一个对象或者List传到Java端,使用@RequestBody即可绑定对象或者List。
  它是通过使用HandlerAdapter 配置的HttpMessageConverters来解析post data body,然后绑定到相应的bean上的。
因为配置有FormHttpMessageConverter,所以也可以用来处理 application/x-www-form-urlencoded的内容。如果觉得@RequestBody不如@RequestParam趁手,我们可以使用 HttpMessageConverter将request的body转移到方法参数上, HttMessageConverser将 HTTP请求消息在Object对象之间互相转换,但一般情况下不会这么做。事实证明,@RequestBody在构建REST架构时,比@RequestParam有着更大的优势,如:

@RequestMapping(value = "/something", method = RequestMethod.PUT)  public void handle(@RequestBody String body, Writer writer) throws IOException {    writer.write(body);  } 
  当与ajax交互的例子:
  JavaScript代码:

<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);     } 

 @SessionAttributes 

  该注解用来绑定HttpSession中的attribute对象的值,便于在方法中的参数里使用。该注解有value、types两个属性,可以通过名字和类型指定要使用的attribute 对象。在默认情况下,ModelMap 中的属性作用域是 request 级别是,也就是说,当本次请求结束后,ModelMap 中的属性将销毁。如果希望在多个请求中共享 ModelMap 中的属性,必须将其属性转存到 session 中,这样 ModelMap 的属性才可以被跨请求访问。
  Spring 允许我们有选择地指定 ModelMap 中的哪些属性需要转存到 session 中,以便下一个请求属对应的 ModelMap 的属性列表中还能访问到这些属性。这一功能是通过类定义处标注 @SessionAttributes 注解来实现的,如:

@Controller  @RequestMapping("/Forum")  @SessionAttributes("currUser") //①将ModelMap中属性名为currUser的属性  放到Session属性列表中,以便这个属性可以跨请求访问 public class BbtForumController {  …      @RequestMapping(params = "method=list")      public String listBoardTopic(@RequestParam("id")int topicId, User user,  ModelMap model) {          ...         System.out.println("user:" + user);          model.addAttribute("currUser",user);//②向ModelMap中添加一个属性        return "listTopic";      }    }  
       我们在 ② 处添加了一个 ModelMap 属性,其属性名为 currUser,而 ① 处通过 @SessionAttributes 注解将 ModelMap 中名为 currUser 的属性放置到 Session 中,所以我们不但可以在 listBoardTopic() 请求所对应的 JSP 视图页面中通过 request.getAttribute(“currUser”) 和 session.getAttribute(“currUser”) 获取 user 对象,还可以在下一个请求所对应的 JSP 视图页面中通过 session.getAttribute(“currUser”) 或 ModelMap#get(“currUser”) 访问到这个属性。
  这里我们仅将一个 ModelMap 的属性放入 Session 中,其实 @SessionAttributes 允许指定多个属性。可以通过字符串数组的方式指定多个属性,如 @SessionAttributes({“attr1”,”attr2”})。此外,@SessionAttributes 还可以通过属性类型指定要 session 化的 ModelMap 属性,如 @SessionAttributes(types = User.class),当然也可以指定多个类,如 @SessionAttributes(types = {User.class,Dept.class}),还可以联合使用属性名和属性类型指定:@SessionAttributes(types = {User.class,Dept.class},value={“attr1”,”attr2”})。

  @ModelAttribute 

  该注解有两个用法,一个是用于方法上,一个是用于参数上;
  用于方法上时: 通常用来在处理@RequestMapping之前,为请求绑定需要从后台查询的model。标明该方法的目的是添加一个或多个模型属性(model attributes)。该方法支持与@RequestMapping一样的参数类型,但并不能直接映射成请求。被@ModelAttribute注释的方法会在此controller每个方法执行前被执行,因此对于一个controller映射多个URL的用法来说,要谨慎使用。

 (1)@ModelAttribute注释void返回值的方法

 public class HelloWorldController {            @ModelAttribute          public void populateModel(@RequestParam String abc, Model model) {             model.addAttribute("attributeName", abc);          }            @RequestMapping(value = "/helloWorld")          public String helloWorld() {             return "helloWorld";          }      }
   这个例子,在获得请求/helloWorld 后,populateModel方法在helloWorld方法之前先被调用,它把请求参数(/helloWorld?abc=text中的"text")加入到一个名为attributeName的model属性中(key为"attributeName"),在它执行后helloWorld被调用,返回视图名helloWorld和model(已由@ModelAttribute方法生产好了)。
  这个例子中model属性名称和model属性对象由model.addAttribute()实现,不过前提是要在方法中加入一个Model类型的参数。当URL或者post中不包含此参数时,会报错。

 (2)@ModelAttribute注释返回具体类的方法

@ModelAttribute      public Account addAccount(@RequestParam String number) {         return accountManager.findAccount(number);      }  
     这种情况,model属性的名称没有指定,它由返回类型隐含表示,如这个方法返回Account类型,那么这个model属性的名称是account。这个例子中model属性名称由返回对象类型隐含表示(使用返回类型的类名称(首字母小写)作为属性名称),model属性对象就是方法的返回值。它无须要特定的参数。这种方式实际的效果就是在调用@RequestMapping的方法之前,为request对象的model里put(“account”, Account)。当需要指定model的key时,可以这么写@ModelAttribute(value="")或直接@ModelAttribute("我们想设定的名称")

 (3)@ModelAttribute和@RequestMapping同时注释一个方法

public class HelloWorldController {            @RequestMapping(value = "/helloWorld.do")          @ModelAttribute("attributeName")          public String helloWorld() {             return "hi";          }      }
   这时这个方法的返回值并不是表示一个视图名称,而是model属性的值,视图名称由RequestToViewNameTranslator根据请求"/helloWorld.do"转换为逻辑视图helloWorld。Model属性名称由@ModelAttribute(value=””)指定,相当于在request中封装了key=attributeName,value=hi。

  一个更具体的例子:

@Controller@RequestMapping ( "/test" )public class MyController {    @ModelAttribute ( "hello" )    public String getModel() {       System. out .println( "-------------Hello---------" );       return "world" ;    }    @ModelAttribute ( "intValue" )    public int getInteger() {       System. out .println( "-------------intValue---------------" );       return 10;    }    @ModelAttribute ( "user2" )    public User getUser(){       System. out .println( "---------getUser-------------" );       return new User(3, "user2" );    }    @RequestMapping ( "sayHello" )    public void sayHello( @ModelAttribute ( "hello" ) String hello, @ModelAttribute ( "intValue" ) int num,       @ModelAttribute ( "user2" ) User user, Writer writer, HttpSession session) throws IOException {       writer.write( "Hello " + hello + " , Hello " + user.getUsername() + num);       writer.write( "\r" );       Enumeration enume = session.getAttributeNames();       while (enume.hasMoreElements())           writer.write(enume.nextElement() + "\r" );    }}
   当我们请求 /test/sayHello.do 的时候使用 @ModelAttribute 标记的方法会先执行,然后把它们返回的对象存放到模型中。最终访问到 sayHello 方法的时候,使用 @ModelAttribute 标记的方法参数都能被正确的注入值。执行结果如下所示:

Hello world,Hello user210

  由执行结果我们可以看出来,此时 session 中没有包含任何属性,也就是说上面的那些对象都是存放在模型属性中,而不是存放在 session 属性中。那要如何才能存放在 session 属性中呢?这个时候需要使用 @SessionAttributes。

  用于参数上时: 

public class HelloWorldController {            @ModelAttribute("user")          public User addAccount() {             return new User("jz","123");          }            @RequestMapping(value = "/helloWorld")          public String helloWorld(@ModelAttribute("user") User user) {             user.setUserName("jizhou");             return "helloWorld";          }      }
      在这个例子里,@ModelAttribute("user") User user注释方法参数,参数user的值来源于addAccount()方法中的model属性。

  另外,我们可以在需要访问 Session 属性的 controller 上加上 @SessionAttributes,然后在 action 需要的 User 参数上加上 @ModelAttribute,并保证两者的属性名称一致。SpringMVC 就会自动将 @SessionAttributes 定义的属性注入到 ModelMap 对象,在 setup action 的参数列表时,去 ModelMap 中取到这样的对象,再添加到参数列表。只要我们不去调用 SessionStatus 的 setComplete() 方法,这个对象就会一直保留在 Session 中,从而实现 Session 信息的共享,如:

@Controller  @SessionAttributes("currentUser") public class GreetingController{    @RequestMapping    public void hello(@ModelAttribute("currentUser") User user){    //user.sayHello()    }  }  

  值得注意的是,以前面提到的例子为例,进行修改,加入@SessionAttributes注解:

@Controller@RequestMapping ( "/test" )@SessionAttributes (value={ "intValue" , "stringValue" }, types={User. class })public class MyController {    @ModelAttribute ( "hello" )    public String getModel() {       System. out .println( "-------------Hello---------" );       return "world" ;    }    @ModelAttribute ( "intValue" )    public int getInteger() {       System. out .println( "-------------intValue---------------" );       return 10;    }      @ModelAttribute ( "user2" )    public User getUser() {       System. out .println( "---------getUser-------------" );       return new User(3, "user2" );    }    @RequestMapping ( "sayHello" )    public void sayHello(Map<String, Object> map, @ModelAttribute ( "hello" ) String hello, @ModelAttribute ( "intValue" ) int num,       @ModelAttribute ( "user2" ) User user, Writer writer, HttpServletRequest request) throws IOException {       map.put( "stringValue" , "String" );       writer.write( "Hello " + hello + " , Hello " + user.getUsername() + num);       writer.write( "\r" );       HttpSession session = request.getSession();       Enumeration enume = session.getAttributeNames();       while (enume.hasMoreElements())           writer.write(enume.nextElement() + "\r" );       System. out .println(session);    }}
  在上面代码中我们指定了属性为 intValue 或 stringValue 或者类型为 User 的都会放到 Session中,利用上面的代码当我们访问 /test/sayHello.do 的时候,结果如下:
Hello world,Hello user210
     仍然没有打印出任何 session 属性,这是怎么回事呢?怎么定义了把模型中属性名为 intValue 的对象和类型为 User 的对象存到 session 中,而实际上没有加进去呢?难道我们错啦?我们当然没有错,只是在第一次访问 /myTest/sayHello.do 的时候 @SessionAttributes 定义了需要存放到 session 中的属性,而且这个模型中也有对应的属性,但是这个时候还没有加到 session 中,所以 session 中不会有任何属性,等处理器方法执行完成后 Spring 才会把模型中对应的属性添加到 session 中。所以当请求第二次的时候就会出现如下结果:
Hello world,Hello user210user2intValuestringValue

  五、@Resource和@Autowired

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

  1、共同点
  两者都可以写在字段和setter方法上。两者如果都写在字段上,那么就不需要再写setter方法,个人习惯在controller类里,用@Resource来注释service。
  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自动注入策略。
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去操作属性,而不是直接去操作属性。
  @Resource装配顺序:
  1、如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常。
  2、如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常。
  3、如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或是找到多个,都会抛出异常。
  4、如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配。
  @Resource的作用相当于@Autowired,只不过@Autowired按照byType自动注入。

  六、@ResponseBody

  @ResponseBody与@RequestBody类似,它的作用是将返回类型直接输入到HTTP response body中,在使用REST风格时要非常小心,因为返回的String值将直接输入到HTTP response body中,而不再去解析。@ResponseBody在输出JSON格式的数据时,会经常用到,代码见下图:

@RequestMapping(value = "/something", method = RequestMethod.PUT)@ResponseBodypublic String helloWorld() {    return "Hello World";}
  使用时机:返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

  七、@RestController 

  我们经常见到一些控制器实现了REST的API,只为服务于JSON,XML或其它自定义的类型内容,@RestController用来创建REST类型的控制器,与@Controller类似。@RestController就是这样一种类型,简单的说就是@Controller与@ResponseBody的结合,不用每次都写两个标签罢了。

  八、@Repository

  用于注解dao层,在daoImpl类上面注解,作为持久化。

  九、@Service

  在类上面定义,指定被注解的类是业务逻辑组件,如果不指定具体的Bean ID,则采用默认命名方式,即类名的首字母小写。

  后记:

  < context:component-scan base-package = "" />默认扫描的注解类型是 @Component,不过,在 @Component 语义基础上细化后的 @Repository, @Service 和 @Controller 也同样可以获得 component-scan 的青睐。有了<context:component-scan>,另一个<context:annotation-config/>标签根本可以移除掉,因为已经被包含进去了。<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>都不能同时存在。
 

1 0
原创粉丝点击