zoukankan      html  css  js  c++  java
  • Spring MVC 常用注解的使用

    • @Controller

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

    @Controller
    class Demo{...}
    • @RequestMapping

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

    ·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) //指定请求方式

    ·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

    ·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){}
    public String login(@RequestParam("list") List<String> list){}
    public String login(@RequestParam("list")) String[] list){} 

          当设置 @RequestParam(required=false) 里面的required为false,此时如果不传参数的话,会报错;(默认为true 代表必须带参数) ,就可以不带参数

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

          当设置 @RequestParam(value="sid")  int id ,sid会代替id,id赋值给sid,URL为 sid = ?  人话:括号里是传入的key

    • @RequestBody

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

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

           

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

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

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

    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.4</version>
    </dependency>

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

    • @ResponseBody

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

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

    @RequestMapping("/login")
    @ResponseBody
    public 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 对象,数据都保存在该对象中,既是“隐含模型

    @ModelAttribute
    public void work(Map<String,Object> 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<String> hobbiesList(){  
        List<String> hobbise = new LinkedList<String>();  
        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;
    }
  • 相关阅读:
    VisualVM 分析full GC问题记录
    HTTPS协议、TLS协议、证书认证过程解析
    java.lang基础数据类型boolean、char、byte、short、int、long、float、double (JDK1.8)
    java.lang.StringBuilder和java.lang.StringBuffer (JDK1.8)
    MVC中自带的异步((Ajax.BeginForm)无效
    百度富文本编辑器UEDITOR
    只有在配置文件或 Page 指令中将 enableSessionState 设置为 true 时,才能使用会话状态。还请确保在应用程序配置的 // 节中包括 System.Web.SessionSta
    【知识碎片】CSS 篇
    js 将json字符串转换为json对象的方法解析
    【知识碎片】Asp.Net 篇
  • 原文地址:https://www.cnblogs.com/stamp/p/springMVC_annotation.html
Copyright © 2011-2022 走看看