VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > Java教程 >
  • springspring注解

回到顶部

一、@ResponseBody

 用法:放在controller层的方法上;

将Controller的方法返回的对象,SpringMVC会根据返回值类型(Map、Llist)找到可以处理的消息转换器,并确定结果的MediaType。返回对象、map和List结果将由MappingJackson2HttpMessageConverter处理,并且MediaType为:application/json。后面写入到Response对象的body数据区。

使用时机:
当我们想让页面知道我们返回的数据不是按照html标签的页面来解析,而是其他某种格式的数据解析时(如json、xml等)使用
eg.

复制代码
1 @RequestMapping("/getList")
2 @ResponseBody
3 public Map<String,Object> getStudentList(HtppServletRequest request){
4     Map<String,Object> map=new HashMap<String,Object>();
5     Dto dto=getParamAsDto(request);
6     List li=studentAction.getList(dto.get("age"));
7     map.put("studentInfo",li);
8 }
复制代码
回到顶部

二、@RequestBody

用法:一般放在controller层的具体请求方法的入参中。比如:

1 @PostMapping("/url")
2 public urlBo getUrlByPhoneNumber(@RequestBody String json,HttpServetRequest request){
3     UrlBo ub=new Gson().fromJson(json,UrlBo.class);
4     ....//其他处理逻辑
5 }

 这里的@RequestBody用于读取Http请求的body部分数据——就是我们的请求数据。比如json或者xml。然后把数据绑定到 controller中方法的参数上,这里就是String json这个入参啦~。

使用时要注意能不能用@RequestBody把request请求的数据解析,并赋给我们定义的参数上是由请求头的Content-Type的值来决定的。

当我们用get/post方式提交请求后, Content-Type的值有以下几种,分别对应能不能解析数据如下:

 

 Content-Type数据格式 @RequestBody是否必须 备注
application/x-www-form-urlencoded 可选

这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理;

这种格式的特点就是,name/value 成为一组,每组之间用 & 联接,而 name与value 则是使用 = 连接

如:a=1&b=2

multipart/form-data 不能处理 即使用@RequestBody不能处理这种格式的数据
其他格式(比如application/json, application/xml) 必须 必须使用@RequestBody来处理

 

回到顶部

 三、@NotBlank

只用于String,不能为null且trim()之后size>0

回到顶部

四、@NotNull

不能为null,但可以为empty,没有Size的约束

回到顶部

五、 @NotEmpty 用在集合类上面

加了@NotEmpty的String类、Collection、Map、数组,是不能为null或者长度为0的(String Collection Map的isEmpty()方法)

一:@Autowired(按类型注入)
1.1通过 @Autowired的使用来消除 set ,get方法。
@Autowired
private Dao dao;
这样就可以删除set ,get方法和spring中的相关配制了。
<bean id="service" class="com.Servcie">
<property name="dao" ref="dao">
</bean>
<bean id="dao" class="com.dao"/>

1.2通过@Autowired属的Setter方法给父类中的属性注入值。
@Autowired
public void setDataSource(DataSource ds){
super.setDataSource(ds);
}

1.3当不能确定 Spring 容器中一定拥有某个类的 Bean 时,可以在需要自动注入该类 Bean 的地方可以使用 @Autowired(required = false) ,这等于告诉 Spring:在找不到匹配 Bean 时    也不报错。@Autowired(required = false)

二:@Resource(按名称注入)
1.1
@Resource(name="dao")
private Dao dao;

@Repository("dao")
Public class Dao{}

三:@Controller  

作用:Controllers provide access to the application behavior that you typically define through a service interface.

  Controllers interpret user input and transform it into a model that is represented to the user by the view.

  Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers.

 控制器提供访问你通过service定义的接口的应用,控制器解释用户输入和转换为由视图表示给用户的模型;spring实现了一个控制器非常抽象的方式,他可以使你可以创造一个非常宽广的控制器。
1.1 EG: @Controller("com.LogAction") //标识控制器bean id

2.2 @Controller 和 @Component 的区别是什么呢?

Spring provides further stereotype annotations: @Component, @Service, and @Controller.

@Component is a generic stereotype for any Spring-managed component.

@Repository, @Service, and @Controller are specializations of @Component for more specific use cases,for example, in the persistence, service, and presentation layers, respectively.

Therefore, you can annotate your component classes with @Component, but by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects.

For example, these stereotype annotations make ideal targets for pointcuts.

It is also possible that @Repository, @Service, and @Controller may carry additional semantics in future releases of the Spring Framework.

Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated above, @Repository is already supported as a marker for automatic exception translation in your persistence layer.

意思就是说: spring 提供了很多样板注释: @Component, @Service, 和 @Controller.而@Component是任何spring管理的组件的一个通用的构造件;比如,分别在在持久层、service和、表示层。

因此,你可以注入你的组件类@Component,但是 注入@Repository, @Service, 和 @Controller 来代替注入@Component的话,你的类会更适合通过工具或者切面的结合的处理。例如,这些刻板印象注解是切入点的理想目标。

@Repository,@Service和@Controller也可能在Spring Framework的未来版本中携带额外的语义。因此,如果您在为服务层使用@Component或@Service之间进行选择,@Service显然是更好的选择。同样,如上所述,已经支持@Repository作为持久层自动异常转换的标记。

四:@RequestMapping
1.1EG: @RequestMapping("log/login.htm",
                        method="RequestMethod.POST",
headers="Content-Type=application/json",
consumes={"application/json"},
produces={"application/json"})
参数有(value={"",""},method={"RequestMethod.GET",""},params={"submitFlag=create",""}...)
 
value:请求的url,params :请求的参数中含有该值;在@RequestMapping 中 params 的参数组合使用是 且的意思
headers:请求参数 Content-Type=application/json 表示客户端发送的文件内容类型,从而服务器按这种类型来解析;
                Accept=application/xml 表示客户端只接收该类型内容从而服务器发送该类型数据
headers="Content-Type=application/json" 对应--> consumes="application/json"
headers="Accept=application/json" 对应--> produces="application/json"
consumes:表示服务器只能消费的数据类型;produces:标示服务器只负责生产的数据

@RequestMapping(value = "/produces", produces = "application/json"):表示将功能处理方法将生产json格式的数据,此时根据请求头中的Accept进行匹配,如请求头“Accept:application/json”时即可匹配;
@RequestMapping(value = "/produces", produces = "application/xml"):表示将功能处理方法将生产xml格式的数据,此时根据请求头中的Accept进行匹配,如请求头“Accept:application/xml”时即可匹配。

此种方式相对使用@RequestMapping的“headers = "Accept=application/json"”更能表明你的目的。
服务器控制器代码详解cn.javass.chapter6.web.controller.consumesproduces.ProducesController;
客户端代码类似于之前的Content-Type中的客户端,详见ProducesController.java代码。
当你有如下Accept头:
①Accept:text/html,application/xml,application/json
      将按照如下顺序进行produces的匹配 ①text/html ②application/xml ③application/json
②Accept:application/xml;q=0.5,application/json;q=0.9,text/html
      将按照如下顺序进行produces的匹配 ①text/html ②application/json ③application/xml
      q参数为媒体类型的质量因子,越大则优先权越高(从0到1)
③Accept:*/*,text/*,text/html
      将按照如下顺序进行produces的匹配 ①text/html ②text/* ③*/*

 

@RequestMapping 配合PathVariable 一起使用;
捕获的URI变量可以通过访问@PathVariable

 

 

1 @RequestMapping("/owners/{ownerId}/{petId}")
2 public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
3     // ...
4 }

 

 

前端传参 "/xxx/owners/"+ownerId+"/"+petId;这里ownerId 和 petId都是参数

 

出处:https://blog.csdn.net/lzwglory/article/details/17252099


五:@Component = @Service or @Reponsitory
1.1 当组件描述不明确时可以统一用@Component

 

六:@ModeAttribute

https://blog.csdn.net/lovesomnus/article/details/78873089

很值得注意:

An @ModelAttribute on a method indicates the purpose of that method is to add one or more model attributes.

Such methods support the same argument types as @RequestMapping methods but cannot be mapped directly to requests.

Instead @ModelAttribute methods in a controller are invoked before @RequestMapping methods, within the same controller.

而是在同一个控制器中的@RequestMapping方法之前调用控制器中的@ModelAttribute方法。)一般在使用期间,如果需要全局用到的东西,我一般继承该Controller;

七:参数绑定注解

1、@RequestParam绑定单个请求参数值;
2、@PathVariable绑定URI模板变量值;
3、@CookieValue绑定Cookie数据值
4、@RequestHeader 绑定请求头数据;
5、@ModelValue绑定参数到命令对象;
6、@SessionAttributes绑定命令对象到session;
7、@RequestBody绑定请求的内容区数据并能进行自动类型转换等,注意,他修改时的对象,传入的参数必须是json,不能是FirstName=Bill&LastName=Gates;
$("form").serialize()形式不可以;
8、@RequestPart 绑定“multipart/data”数据,除了能绑定@RequestParam 能做到的请求参数外,还能绑定上传的文件

9、@DateTimeFormat(pattern ="yyyy-MM-dd") Date类型的参数,自动转换格式

@RequestParam (value="",required=false[默认true],defaultValue="zhang")
绑定单个参数  public void method(@RequestParam(value="username") String name){}  --> ...htm?username=zzd
        绑定多个参数  public void method(@RequestParam(value="role")  String[] roles){}  或者  
      public void method(@RequestParam(value="role" )  List<String> roles) {} -->...htm?role=admin&role=test

 

@RequestMapping(value="/users/{userId}/topics/{topicId}") 
EG:public String test( @PathVariable(value="userId")  int  userId, @PathVariable(value="topicId")  int topicId)
     将url 中的{userId}、{topicId} 绑定到@PathVariable 标注的变量中

 

@CookieValue
public String test(@CookieValue(value="JSESSIONID", defaultValue="") String sessionId) 

 

@RequestHeader
public String test( @RequestHeader("User-Agent") String userAgent,     @RequestHeader(value="Accept") String[] accepts)

 

七:@Valid:

该注解就是告诉spring 这个参数需要确保满足校验条件限制;

 

备注

<context:component-scan/> 扫描指定的包中的类上的注解,常用的注解有:

@Controller 声明Action组件
@Service    声明Service组件    @Service("myMovieLister") 
@Repository 声明Dao组件
@Component   泛指组件, 当不好归类时. 
@RequestMapping("/menu")  请求映射
@Resource  用于注入,( j2ee提供的 ) 默认按名称装配,@Resource(name="beanName") 
@Autowired 用于注入,(srping提供的) 默认按类型装配 

  例如:

    @Autowired
    pirvate CurryUserService curryUserService;
    @Autowired
    pirvate CurryUserService abc;
    //这两种都可以注入成功

    而
    @Resource(name = "curryUserService") 
    private CurryUserService curryUserService;  //注入成功

    @Resource(name = "curryUserService") 
    private CurryUserService abc;  //注入失败,因为对象名和@Resource中的name值不一致
@Transactional( rollbackFor={Exception.class}) 事务管理
@ResponseBody
@Scope("prototype")   设定bean的作用域

 

转载地址:https://www.cnblogs.com/leonkobe/p/3530872.html

https://blog.csdn.net/u010739551/article/details/82882175

我从来不相信什么懒洋洋的自由。我向往的自由是通过勤奋和努力实现的更广阔的人生。 我要做一个自由又自律的人,靠势必实现的决心认真地活着。

来源:https://www.cnblogs.com/lixiuming521125/p/7885741.html

相关教程