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

    一、注解类配置

    要使用springmvc的注解类,需要在springmvc.xml配置文件中用context:component-scan/扫描:

    二、五大重要的注解类

    1.RequestMapping注解

    RequestMapping注解类的使用方法

    在Controller控制器类的类定义和方法定义处都可以标注@RequestMapping注解
    DispatcherServlet截获请求后,就可以通过控制器上的@RequestMapping提供的映射信息确定请求所对应的处理方法

    package net.quickcodes.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    @RequestMapping("/home") //类级别,可以不需要,如果要了,下面所有的请求路径前都需要加上“/home”
    public class IndexController {
    
        //方法级别,必须有,决定这个方法处理哪个请求(这里处理/helloworld/home/index.html请求)
        @RequestMapping(value = "/index")
        public String helloWorld(){
            return "index";//"WEB-INF/page/index.jsp"
        }
        
    }

    RequestMapping注解类的属性

    RequestMapping注解类的属性,分别有 value, method, consumes, produces, params, headers
    1>.value属性
    • 代表具体的请求路径,比如上面的 "/home", "/index"都是value的值
    • value可以省略,就像例子中一样,直接用 @RequestMapping("/home") 的格式,它等同于@RequestMapping(value = "/home")

    2>.method属性
    • 指定请求的method类型, GET、POST、PUT、DELETE等:
    例:@RequestMapping(value = "/login", method = RequestMethod.POST) 那么只有发送POST请求才会触发这个方法
    • 它的值既可以是字符串也可以是数组:
    例:@RequestMapping(value = "/login", method = {RequestMethod.POST, RequestMethod.GET})

    3>.consumes属性
    • 指定请求的提交内容类型(Content-Type),例如application/json, text/html
    例:@RequestMapping(value = "/login", consumes = "application/json")
    • 它的值既可以是字符串也可以是数组
    例:@RequestMapping(value = "/login", consumes = {"application/json", "text/html"})

    4>.produces属性
    • 指定返回的内容的类型(Content-Type),例如application/json, text/html
    例:@RequestMapping(value = "/login", produces = "application/json")
    • 它的值既可以是字符串也可以是数组
    例:@RequestMapping(value = "/login", produces = {"application/json", "text/html"})

    5>.params属性
    • 指定请求中必须包含某些参数值,才会触发这个处理方法
    例:@RequestMapping(value = "/login", params = "id=1")
    • 参数中除了使用=等号外,还可以使用!=号,表示在参数的值不等于的情况下触发这个方法
    例:@RequestMapping(value = "/login", params = {"id=1","age!=18"})
    • 也可以不指定具体的值,直接使用 "paramName" 的格式,代表请求中必须包含参数名为 paramName 的参数
    • 直接使用 “!paramName”格式表示请求不能包含名为paramName的请求参数

    6>.headers属性
    • 请求头Header中必须包含某些指定的参数值,才能让该方法处理请求,可以利用这个特性拒绝非指定来源的客户端的访问,以加强站点的安全。
    例:@RequestMapping(value = "/login", headers = "content-type=text/*")
    例:@RequestMapping(value = "/login", headers = {"content-type=text/*","Referer=http://www.buyinplay.com"})

    定义Ant风格和带占位符的URL

    @RequestMapping不仅支持标准的URL,还支持Ant风格和带{xxx}占位符的URL,下面的URL都是合法的:

    •   /user/*/login:匹配/user/aaa/login,/user/任意字符/login 等
    •   /user/**/login:匹配/user/login, /user/aaa/bbb/login 等
    •   /user/login??:匹配/user/loginAA, /user/loginbb 等
    •   /user/{userId}:匹配/user/123, /user/234 等
    •   /user/**/{userId}:匹配/user/aaa/bbb/123,/user/aaa/234等
    

    2.Component注解

    Component注解是“Controller注解”、“Service注解”和“Repository注解”的通用注解,可以和它们起到相同的作用(在不清楚使用那个注解的时候,可以统统使用Component,为了代码逻辑清晰,还是建议使用具体的注解)。这四个注解都是类级别的, 可以不带任何参数,也可以带一个参数,代表bean名字,在进行注入的时候就可以通过名字进行注入了。

    ![](media/14612091580198/14612489590879.jpg)
    

    使用@Resource或@Autowired注解实现注入
    @Resource和@Autowired注解的异同:
    @Resource 用于注入,( j2ee提供的 ) 默认按名称装配,@Resource(name="beanName")
    @Autowired 用于注入,(srping提供的) 默认按类型装配,默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false,例如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用

    一般我会使用@Resource进行注入:

    3.Controller注解

    类级别的注解,用于声明控制器类。用法参考“Component注解”。

    @Controller 负责注册一个bean 到spring 上下文中,bean 的ID 默认为类名称开头字母小写,你也可以自己指定,如下
    方法一:
    @Controller
    public class TestController {}
     
    方法二:           
    @Controller("tmpController")
    public class TestController {}
     

    4.Service注解

    类级别的注解,用于声明Service类。用法参考“Component注解”。

    5.Repository注解

    类级别的注解,用于声明DAO类。用法参考“Component注解”。

    三、其他常用的注解类

    1.CookieValue注解

    读取Cookies中的值,并且赋值给变量
    有三个属性 value, required, defaultValue,分别表示Cookie的名字,是否必须有这个Cookie值,如果没有则使用默认值
    不带任何参数,表示需要的参数名与标注的变量名相同

    @RequestMapping("/listone")
    public String listone(@CookieValue String goodsName){//不带任何参数
        return "listone";
    }
    
    @RequestMapping("/listtwo")
    public String listtwo(@CookieValue("goodsName") String goodsName){//指定Cookie的名字
        return "listtwo";
    }
    
    @RequestMapping("/listthree")
    public String listthree(@CookieValue(value="goodsName",defaultValue="new",required =false) String goodsName){//指定Cookie的名字,如果没有这个名字,赋值默认值new
        return "listthree";
    }

    2.PathVariable注解

    1>.@PathVariable用于方法中的参数,表示方法参数绑定到地址URL的模板变量。
    例如:

    @RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)  
    public String findOwner(@PathVariable String ownerId, Model model) {  
      Owner owner = ownerService.findOwner(ownerId);    
      model.addAttribute("owner", owner);    
      return "displayOwner";  
    }  


     
    2>.@PathVariable用于地址栏使用{xxx}模版变量时使用。
    如果@RequestMapping没有定义类似"/{ownerId}" ,这种变量,则使用在方法中@PathVariable会报错。

    3.RequestBody注解

    4.RequestHeader注解

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

    5.RequestMethod注解

    6.RequestParam注解

    @RequestParam是一个可选参数,例如:@RequestParam("id") 注解,所以它将和URL所带参数 id进行绑定 。
    如果入参是基本数据类型(如 int、long、float 等),URL 请求参数中一定要有对应的参数,否则将抛出
    org.springframework.web.util.NestedServletException 异常,提示无法将 null 转换为基本数据类型.

    @RequestParam包含3个配置 @RequestParam(required = ,value="", defaultValue = "")
    required :参数是否必须,boolean类型,可选项,默认为true
    value: 传递的参数名称,String类型,可选项,如果有值,对应到设置方法的参数
    defaultValue:String类型,参数没有传递时为参数默认指定的值
     

    7.ResponseBody注解

    这个注解可以直接放在方法上,表示返回类型将会直接作为HTTP响应字节流输出(不被放置在Model,也不被拦截为视图页面名称)。可以用于ajax。

    用于将Controller的方法返回的对象,通过适当的HttpMessageConverter(转换器)转换为指定格式后,写入到Response对象的body数据区
    返回如json、xml等时使用
    在springmvc配置文件中通过,给AnnotationMethodHandlerAdapter初始化7个转换器

    • ByteArranHttpMessageConverter 读写二进制数据
    • StringHttpMessageConverter 将请求信息转换为字符串
    • ResourceHttpMessageConverter 读写org.springframework.core.io.Resource对象
    • SourceHttpMessageConverter 读写javax.xml.transform.Source类型的数据
    • XmlAwareFormHttpMessageConverter 处理表单中的XML数据
    • Jaxb2RootElementHttpMessageConverter 通过JAXB2读写XML消息,将请求消息转换到标注XmlRootElement和XmlType的注解类中
    • MappingJacksonHttpMessageConverter 读写JSON数据


     

    8.SessionAttribute注解

    session管理
    如果希望在多个请求之间公用某个模型属性数据,则可以在控制器类标注一个@SessionAttributes,Spring MVC会将模型中对应的属性暂存到HttpSerssion中
    除了SessionAttributes,还可以直接用原生态的request.getSession()来处理session数据

    Spring 允许我们有选择地指定 ModelMap 中的哪些属性需要转存到 session 中,以便下一个请求属对应的 ModelMap 的属性列表中还能访问到这些属性。这一功能是通过类定义处标注 @SessionAttributes 注解来实现的。@SessionAttributes 只能声明在类上,而不能声明在方法上。

     
    @SessionAttributes("currUser") // 将ModelMap 中属性名为currUser 的属性 
    
    
    @SessionAttributes({"attr1","attr2"}) 
    @SessionAttributes(types = User.class) 
    @SessionAttributes(types = {User.class,Dept.class}) 
    @SessionAttributes(types = {User.class,Dept.class},value={"attr1","attr2"}) 
    @Controller
    @RequestMapping(value = "/goods")
    @SessionAttributes("rowCount")//代码中所有名为rowCount的属性都会自动存入session中
    public class GoodsController {
    
        @Resource
        GoodsService service;
        
        /**注入语法
        @Autowired
        @Qualifier("goodsService")
        GoodsService service;
         */
        
        @RequestMapping(value = "/list")
        public String helloWorld(HttpServletRequest request){
            String currPageStr = request.getParameter("page");
            int currPage = 1;
            try {
                currPage = Integer.parseInt(currPageStr);
            } catch (Exception e) {
            }
            
            // 获取总记录数
            int rowCount = service.getRowCount();//被自动存入session中
            PageParam pageParam = new PageParam();
            pageParam.setRowCount(rowCount);
            if (pageParam.getTotalPage() < currPage) {
                currPage = pageParam.getTotalPage();
            }
            pageParam.setCurrPage(currPage);
            pageParam = service.getGoodsByPage(pageParam);
            
            request.setAttribute("pageParam", pageParam);
            
            return "list";
        }
        
        @RequestMapping("/clearsession")//本方法仅用于演示清除session
        public String doClearSession(String goodsName,SessionStatus status){
            status.setComplete();
            return "list";
        }
    }

    9.Scope("prototype")注解

    设定bean的作用域

    10.Transactional( rollbackFor={Exception.class})注解

    事务管理

    11.ModelAttribute注解

    1>.应用于方法参数,参数可以在页面直接获取,相当于request.setAttribute(,)
    2>.应用于方法,将任何一个拥有返回值的方法标注上 @ModelAttribute,使其返回值将会进入到模型对象的属性列表中.
    3>.应用于方法参数时@ModelAttribute("xx"),须关联到Object的数据类型,基本数据类型 如:int,String不起作用
    例如:
    Java代码  

    @ModelAttribute("items")//<——①向模型对象中添加一个名为items的属性 
    
    public List<String> populateItems() {  
            List<String> lists = new ArrayList<String>();  
            lists.add("item1");  
            lists.add("item2");  
            return lists;  
    }
     
    @RequestMapping(params = "method=listAllBoard")  
    public String listAllBoard(@ModelAttribute("currUser")User user, 
    
    ModelMap model) {  
            bbtForumService.getAllBoard();  
            //<——②在此访问模型中的items属性  
            System.out.println("model.items:" + ((List<String>)
    
    model.get("items")).size());  
            return "listBoard";  
    } 

     
    在 ① 处,通过使用 @ModelAttribute 注解,populateItem() 方法将在任何请求处理方法执行前调用,Spring MVC 会将该方法返回值以“items”为名放入到隐含的模型对象属性列表中。 所以在 ② 处,我们就可以通过 ModelMap 入参访问到 items 属性,当执行 listAllBoard() 请求处理方法时,② 处将在控制台打印出“model.items:2”的信息。当然我们也可以在请求的视图中访问到模型对象中的 items 属性。

  • 相关阅读:
    PHP通用函数
    Discuz 取各排行榜数据
    htaccess 增加静态文件缓存和压缩
    一个域名解析不同访问方法
    TP5:隐藏inde.php文件
    vscode:解决操作git总让输入用户名及密码问题
    vscode:配置git
    cmd:相关命令和笔记
    PHP:通过MVC,实现第三方登录(百度)
    Linux:301重定向 —— 将不带www的重定向到带www的
  • 原文地址:https://www.cnblogs.com/quickcodes/p/Spring-MVC-chang-yong-de-zhu-jie-lei.html
Copyright © 2011-2022 走看看