赞!SpringMVC中常用注解(案例讲解)

240 阅读7分钟

赞!SpringMVC中常用注解(案例讲解)

SpringMVC中常用注解

  • RequestParam
  • RequestBody
  • PathVaribale
    • 先了解下REST 风格 URL
  • RequestHeader
  • CookieValue
  • ModelAttribute
    • 修饰的方法有返回值
    • 修饰的方法没有返回值
  • SessionAttribute

RequestParam

说明

作用:
把请求中指定名称的参数给控制器中的形参赋值。
属性:
value:请求参数中的名称。
required:请求参数中是否必须提供此参数。默认值:true。表示必须提供,如果不提供将报错。

代码示例

jsp代码:

<%--  Created by IntelliJ IDEA.  User: Keafmd  Date: 2021/1/25  Time: 10:48  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>常用注解</title></head><body>     <!-- requestParams 注解的使用 -->    <a href="anno/testRequestParam?name=keafmd">RequestParam</a><br/> </body></html>12345678910111213141516171819

控制器代码:

package com.Keafmd.controller; import com.Keafmd.domain.User;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.*;import org.springframework.web.bind.support.SessionStatus; import java.util.Date;import java.util.Map; /** * Keafmd * * @ClassName: AnnoConteoller * @Description: 注解的控制器 * @author: 牛哄哄的柯南 * @date: 2021-01-25 10:50 */@Controller@RequestMapping("/anno")public class AnnoConteoller {     /**     * requestParams 注解的使用     * @param username     * @return     */    @RequestMapping("/testRequestParam")    public String testRequestParam(@RequestParam(value="name") String username){        // @RequestParam(value="name") 必须传name,required:请求参数中是否必须提供此参数,默认值是true,必须提供        // 获得当前类名        String clazz = Thread.currentThread().getStackTrace()[1].getClassName();        // 获得当前方法名        String method = Thread.currentThread().getStackTrace()[1].getMethodName();         System.out.println("执行了:"+clazz+" - "+method);        System.out.println("username:"+username);        return "success";    } }12345678910111213141516171819202122232425262728293031323334353637383940414243

输出结果:

执行了:com.Keafmd.controller.AnnoConteoller - testRequestParamusername:keafmd12

这样我们在href中传入name就会赋值给username。

RequestBody

说明

作用:
用于获取请求体内容。直接使用得到是 key=value&key=value…结构的数据。
get 请求方式不适用。
属性:
required:是否必须有请求体。默认值是:true。当取值为 true 时,get 请求方式会报错。如果取值为 false,get 请求得到是 null。

代码示例

jsp代码:

<form action="anno/testRequestBody" method="post">        用户姓名:<input type="text" name="uname" /><br/>        用户年龄:<input type="text" name="age" /><br/>        用户生日:<input type="text" name="birthday" /><br/>        <input type="submit" value="提交"></form>123456

控制器代码:

/*** 获取到请求体的内容 RequestBody */ @RequestMapping("/testRequestBody")public String testRequestBody(@RequestBody String body){    String method = Thread.currentThread().getStackTrace()[1].getMethodName();    System.out.println("执行了:"+" "+method);    System.out.println("body:"+body);    return "success";}1234567891011

输出结果:

执行了: testRequestBodybody:uname=Keafmd&age=21&birthday=2000-01-0112

PathVaribale

先了解下REST 风格 URL

REST(英文:Representational State Transfer,简称 REST)描述了一个架构样式的网络系统,比如 web 应用程序。值得注意的是 REST 并没有一个明确的标准,而更像是一种设计的风格。

说明

作用:
用于绑定 url 中的占位符。例如:请求 url 中 /delete/{id},这个{id}就是 url 占位符。
url 支持占位符是 spring3.0 之后加入的。是 springmvc 支持 rest 风格 URL 的一个重要标志。
属性:
value:用于指定 url 中占位符名称。
required:是否必须提供占位符。

代码示例

jsp代码:

<a href="anno/testPathVariable/10">testPathVariable</a><br/>1

控制器代码:

/*** PathVariable* @param id* @return*/@RequestMapping("/testPathVariable/{sid}")public String testPathVariable(@PathVariable(name="sid") String id){   // 获得当前方法名   String method = Thread.currentThread().getStackTrace()[1].getMethodName();   System.out.println("执行了:"+" "+method);   System.out.println("id:"+id);   return "success";}12345678910111213

输出结果:

执行了: testPathVariableid:1012

RequestHeader

说明

作用:
用于获取请求消息头。
属性:
value:提供消息头名称
required:是否必须有此消息头
提示:
在实际开发中一般不常用

代码示例

jsp代码:

<a href="anno/testRequestHeader">testRequestHeader</a><br/>1

控制器代码:

/*** RequestHeader获取请求头的值  不常用* @param head* @return*/@RequestMapping("/testRequestHeader")public String testRequestHeader(@RequestHeader(value = "Accept") String head){   // 获得当前方法名   String method = Thread.currentThread().getStackTrace()[1].getMethodName();   System.out.println("执行了:"+" "+method);    System.out.println("head:"+head);   return "success";}1234567891011121314

输出结果:

执行了: testRequestHeaderhead:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b312

CookieValue

说明

作用:
用于把指定 cookie 名称的值传入控制器方法参数。
属性:
value:指定 cookie 的名称。
required:是否必须有此 cookie。

代码示例

jsp代码:

<a href="anno/testCookieValue">testCookValue</a><br/>1

控制器代码:

/** * CookieValue 不常用 * @param cookievalue * @return */@RequestMapping("/testCookieValue")public String testCookieValue(@CookieValue(value = "JSESSIONID") String cookievalue){    // 获得当前方法名    String method = Thread.currentThread().getStackTrace()[1].getMethodName();    System.out.println("执行了:"+" "+method);     System.out.println("cookievalue:"+cookievalue);    return "success";}1234567891011121314

输出结果:

执行了: testCookieValuecookievalue:DCCFE2C1F975AC04D4F55973ADA5C89C12

ModelAttribute

说明

作用:
该注解是 SpringMVC4.3 版本以后新加入的。它可以用于修饰方法和参数。
出现在方法上,表示当前方法会在控制器的方法执行之前,先执行。它可以修饰没有返回值的方法,也可以修饰有具体返回值的方法。
出现在参数上,获取指定的数据给参数赋值。
属性:
value:用于获取数据的 key。key 可以是 POJO 的属性名称,也可以是 map 结构的 key。
应用场景:
当表单提交数据不是完整的实体类数据时,保证没有提交数据的字段使用数据库对象原来的数据。

代码示例

jsp代码:

<form action="anno/testModelAttribute" method="post">	用户姓名:<input type="text" name="uname" /><br/>    用户年龄:<input type="text" name="age" /><br/>    <input type="submit" value="提交"></form>12345

修饰的方法有返回值

控制器代码:

/** * ModelAttribute * @return */ @RequestMapping("/testModelAttribute")public String testModelAttribute(User user){    // 获得当前方法名    String method = Thread.currentThread().getStackTrace()[1].getMethodName();    System.out.println("执行了:"+" "+method);    System.out.println(user);    return "success";} //有返回值@ModelAttributepublic User showUser(String uname){    String method = Thread.currentThread().getStackTrace()[1].getMethodName();    System.out.println("执行了:"+" "+method);    User user = new User();    user.setUname(uname);    user.setAge(20);    user.setBirthday(new Date());    return user;}12345678910111213141516171819202122232425

输出结果:

执行了: testModelAttributeUser{uname='牛哄哄的柯南', age=21, birthday=Mon Jan 25 19:34:46 CST 2021}12

修饰的方法没有返回值

注意:没有返回值的时候利用Map把参数传回去,testModelAttribute的参数User前加上@ModelAttribute(“abc”)接收Map传回的数据。

控制器代码:

/** * ModelAttribute * @return */ @RequestMapping("/testModelAttribute")public String testModelAttribute(@ModelAttribute("abc")User user){    // 获得当前方法名    String method = Thread.currentThread().getStackTrace()[1].getMethodName();    System.out.println("执行了:"+" "+method);    System.out.println(user);    return "success";} //无返回值@ModelAttributepublic void showUser(String uname, Map<String,User> map){    String method = Thread.currentThread().getStackTrace()[1].getMethodName();    System.out.println("执行了:"+" "+method);    User user = new User();    user.setUname(uname);    user.setAge(20);    user.setBirthday(new Date());    map.put("abc",user);}12345678910111213141516171819202122232425

输出结果:

执行了: testModelAttributeUser{uname='牛哄哄的柯南', age=21, birthday=Mon Jan 25 19:32:20 CST 2021}12

SessionAttribute

说明

作用:
用于多次执行控制器方法间的参数共享。
属性:
value:用于指定存入的属性名称
type:用于指定存入的数据类型。

代码示例

jsp代码:

<a href="anno/testSessionAttributes">存入SessionAttributes</a><br/><a href="anno/getSessionAttributes">获取SessionAttributes</a><br/><a href="anno/delSessionAttributes">清除SessionAttributes</a><br/>123

控制器代码:

注意:需要在类的上面添加@SessionAttributes(value = {"msg"}) //把msg=牛哄哄的柯南存到session域中。

package com.Keafmd.controller; import com.Keafmd.domain.User;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.*;import org.springframework.web.bind.support.SessionStatus; import java.util.Date;import java.util.Map; /** * Keafmd * * @ClassName: AnnoConteoller * @Description: 注解的控制器 * @author: 牛哄哄的柯南 * @date: 2021-01-25 10:50 */@Controller@RequestMapping("/anno")@SessionAttributes(value = {"msg"}) //把msg=牛哄哄的柯南存到session域中public class AnnoConteoller {     /**     * SessionAttributes注解,存入msg     * @return     */    @RequestMapping("/testSessionAttributes")    public String testSessionAttributes(Model model){        // 获得当前方法名        String method = Thread.currentThread().getStackTrace()[1].getMethodName();        System.out.println("执行了:"+" "+method);         //底层会存到Request域中        model.addAttribute("msg","牛哄哄的柯南");         return "success";    }     /**     * 获取     * @param modelMap     * @return     */    @RequestMapping("/getSessionAttributes")    public String getSessionAttributes(ModelMap modelMap){        // 获得当前方法名        String method = Thread.currentThread().getStackTrace()[1].getMethodName();        System.out.println("执行了:"+" "+method);         //从session域中取出来        String msg = (String)modelMap.get("msg");        System.out.println(msg);        return "success";    }     /**     * 清除     * @param sessionStatus     * @return     */    @RequestMapping("/delSessionAttributes")    public String delSessionAttributes(SessionStatus sessionStatus) {        // 获得当前方法名        String method = Thread.currentThread().getStackTrace()[1].getMethodName();        System.out.println("执行了:"+" "+method);         //从session域中清除        sessionStatus.setComplete();        return "success";    }  } 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677

依次点击存入->获取->清除->获取。

输出结果:

执行了: testSessionAttributes执行了: getSessionAttributes牛哄哄的柯南执行了: delSessionAttributes执行了: getSessionAttributesnull123456

在success.jsp可以通过msg{msg}和{sessionScope}获取到在类上面把msg存入到session域的内容:牛哄哄的柯南和{msg=牛哄哄的柯南}
在success.jsp可以通过${requestScope}获取到在testSessionAttributes方法中存入Request域中的内容。

以上就是SpringMVC中常用注解(案例讲解)的全部内容。

点点关注!

看完记得点赞+评论+转发哦~