博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring MVC 常用注解的使用
阅读量:6934 次
发布时间:2019-06-27

本文共 5795 字,大约阅读时间需要 19 分钟。

  • @Controller

     注解一个类表示控制器,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ,然后再把该Model 返回给对应的View,Spring MVC会自动扫描标注了这个注解的类

@Controllerclass Demo{...}

 

  • @RequestMapping

     请求路径映射,有六个属性,下面我们把她分成三类进行说明,满足请求条件才执行方法

      1、 value, method;

        value:     指定请求的实际地址,指定的地址可以是URI Template 模式

             用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径  http://localhost:8080/项目名/hello/方法的mapping

             用于方法上,表示响应请求方法的路径映射  http://localhost:8080/项目名/方法的mapping

@Controller@RequestMapping(value = "/hello")  // @RequestMapping("/hello")class Demo{}

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

@RequestMapping("/hello" , method=RequestMethod.GET) //指定请求方式

      2、 consumes,produces;

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

@RequestMapping(value="/test",consumes="application/json")

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

@RequestMapping(value="/test",produces="application/json")    //同时暗示了返回的内容类型为application/json

      3、 params,headers;

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

@RequestMapping(value="/test",params="name=tom")

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

@RequestMapping(value="/test",headers="Referer=http://www.clockin.com/")

 

  • @RequestParam

     放在参数前面,只能接收参数 a=b 格式的数据,即Content-Type 为 application/x-www-form-urlencoded类型的内容

      此时必须输入 localhost:8080/login?id=?  带参数才会调用该方法

 

public String login(@RequestParam int id){
}

      当设置 @RequestParam(required=false) 里面的required为false(默认为true 代表必须带参数) ,就可以不带参数

      当设置 @RequestParam(defaultValue="0") ,这样在地址里面也可以不带参数,如果带了参数会接收,不带参数会默认为0

      当设置 @RequestParam(value="sid")  int id ,sid会代替id,id赋值给sid,URL为 sid = ? 

  • @RequestBody

     常用来处理content-type不是默认的application/x-www-form-urlcoded编码的内容,比如说:application/json或者是application/xml

@requestMapping("/login")public void login(@requestBody String userName,@requestBody String pwd){    System.out.println(userName+" :"+pwd);}

       

{"userName":"admin","pwd","admin123"}

     将JSON字符串中的两个变量的值分别赋予User类中的:String userName , String pwd 属性

     就将上述参数可以改为 @requestBody User user  这种形式会将JSON字符串中的值赋予user中对应的属性上

     需要注意的是,JSON字符串中的key必须对应user中的属性名

  • @ResponseBody

     此方法返回的数据放在request body里面,而不是跳转页面,通常用来返回JSON数据或者是XML

     在使用此注解之后不会再走试图处理器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据

@RequestMapping("/login")@ResponseBodypublic User login(User user){      return user;}

     User的属性: userName,pwd

     前台接收到的数据: '{"userName":"xxx","pwd":"xxx"}'

  • @RestController

       @RestController = @Controller + @ResponseBody  返回参数都在request body中,return ""无法返回指定页面

  • @PathVariable

     用于绑定restful路径上的变量,映射 URL 绑定的占位符

     将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过@PathVariable(“xxx“) 绑定到操作方法的入参中

@RequestMapping("/test/{id}")public String test(@PathVariable("id") String id){    System.out.println("test:"+id);    return null;}

 

  • @RequestHeader

     放在方法参数前,可以把Request请求header部分的值绑定到方法的参数上

1 Host                    localhost:8080  2 Accept                  text/html,application/xhtml+xml,application/xml;q=0.9  3 Accept-Language         fr,en-gb;q=0.7,en;q=0.3  4 Accept-Encoding         gzip,deflate  5 Accept-Charset          ISO-8859-1,utf-8;q=0.7,*;q=0.7  6 Keep-Alive              300
@RequestMapping(“/header”)  public void header(@RequestHeader(“Accept-Encoding”) String encoding,@RequestHeader(“Keep-Alive”) long keepAlive)  {    }

     request header部分的 Accept-Encoding的值,绑定到参数encoding, Keep-Alive header的值绑定到参数keepAlive

  • @CookieValue

    放在方法参数前,把Request header中关于cookie的值绑定到方法的参数上

JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84
@RequestMapping(“/cookie”)  public void cookie(@CookieValue(“JSESSIONID”) String cookie)  {    }

    JSESSIONID的值绑定到参数cookie

  • @ModelAttribute

    可标记在参数前

       当 hello1 重定向到 hello2 时,hello2 的@ModelAttribute("...") 会根据"..."找到重定向中对应的键赋值给参数temp上

@RequestMapping("hello1")public String test(RedirectAttributes ra) {    ra.addFlashAttribute("temps", "abcdef");    return "redirect:/hello2"; }    @RequestMapping("helle2")public String test1(RedirectAttributes ra,@ModelAttribute("temps") String temp) {        System.out.println(temp);        return null;}

 

    可标记在方法前

      标有该注解的方法,会在目标方法前执行,用来封装请求参数,告诉Spring MVC 封装时不会再new User

      Map 和 Model 同是:BindingAwareModelMap 对象,数据都保存在该对象中,既是“隐含模型”

@ModelAttributepublic void work(Map
map) { //在功能test方法前执行 User user = new User(1,"tom",20); //模拟从数据库查询出的数据 map.put("user", user); //map保存对象数据}@RequestMapping("/test")public String test(@ModelAttribute("user") User user) { System.out.println(user.toString()); return null;}

      

      标有该注解的方法,可以直接在前端页面使用这个list对象

      隐含模型是幽灵,无处不在

/***   jsp使用JSTL, ${list} 得到集合*/@ModelAttribute("list")  public List
hobbiesList(){ List
hobbise = new LinkedList
(); hobbise.add("basketball"); hobbise.add("football"); hobbise.add("tennis"); return hobbise; }

 

  • @SessionAttribute

      只能作用在类上,将Model中的属性同步到session当中

@Controller@SessionAttributes("name")public class SessionController {    @RequestMapping("/hello")    public String test(Model model){        model.addAttribute("name", "tom");        return null;}

      上面的代码将Model中的name参数保存到了session中(如果Model中没有name参数,而session中存在一个name参数,那么SessionAttribute会讲这个参数塞进Model中)

      SessionAttribute有两个参数:

        String[] value:要保存到session中的参数名称

        Class[] typtes:要保存的参数的类型,和value中顺序要对应上

      所以可以这样写:@SessionAttributes(types = {User.class,Dept.class},value={“attr1”,”attr2”})

      如果想删除session中共享的参数,可以通过SessionStatus.setComplete(),这句只会删除通过@SessionAttribute保存到session中的参数

@RequestMapping("/hello")  public ModelAndView test(SessionStatus status) {  ModelAndView model = new ModelAndView("success.jsp");  status.setComplete();  return model;}

 

转载于:https://www.cnblogs.com/stamp/p/springMVC_annotation.html

你可能感兴趣的文章
javaScript事件(二)事件处理程序
查看>>
数据库——修改表信息(转)
查看>>
SQL 存储过程 解析XML
查看>>
Atitit.木马病毒自动启动-------------win7计划任务的管理
查看>>
Javascript学习总结三(Array对象的用法)
查看>>
hiho_1050_树中的最长路
查看>>
Centos6.5搭建java开发环境
查看>>
08Spring_Spring和junit测试集成
查看>>
ArcGIS API for Silverlight 点沿着线流动
查看>>
在kali linux之下安装wps之后 报错字体缺失
查看>>
rem计算适配
查看>>
MySQL主主双机负载均衡
查看>>
EL与OGNL以及值栈的理解
查看>>
utf8汉字编码16进制对照(转载)
查看>>
java基础之【堆、栈、方法区】结构图
查看>>
POJ3321:Apple Tree(树状数组)
查看>>
弹出框插件layer使用
查看>>
细说 iOS 消息推送
查看>>
官方 React 快速上手脚手架 create-react-app
查看>>
位运算和典型应用详解
查看>>