SpringMVC常用注解

it2024-01-24  69

SpringMVC常用注解

1.1 RequestParam注解 作用: 把请求中指定名称的参数给控制器中的形参赋值。 属性: value:请求参数中的名称。 required:请求参数中是否必须提供此参数。默认值:true。表示必须提供,如果不提供将报错。 1).在anno.jsp编写如下代码:

<%-- Created by IntelliJ IDEA. User: Adair Date: 2018/4/29 Time: 23:35 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%--常用的注解--%> <a href="anno/testRequestParam?name=哈哈">RequestParam</a> </body> </html>

2).创建常用的注解控制器类的代码如下:

package com.txw.controller; import com.txw.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 javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Date; import java.util.Map; /** * 常用的注解 *@author Adair */ @Controller @RequestMapping("/anno") @SuppressWarnings("all") // 注解警告信息 public class AnnoController { @RequestMapping("/testRequestParam") public String testRequestParam(@RequestParam(name="name") String username){ System.out.println("执行了..."); System.out.println(username); return "success"; } }

3).使用TomCat运行结果如图: 4).通过浏览器访问http://localhost:8080/anno.jsp结果如图所示: 5).点击RequestParam会跳转到如图所示的界面: 6).控制台打印结果如图所示: 1.2 RequestBody 作用: 用于获取请求体内容。直接使用得到是key=value&key=value…结构的数据。 get请求方式不适用。 属性: required:是否必须有请求体。默认值是:true。当取值为true时,get请求方式会报错。如果取值为false,get请求得到是null。 1).在anno.jsp编写如下代码:

<%-- Created by IntelliJ IDEA. User: Adair Date: 2018/4/29 Time: 23:35 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%--常用的注解--%> <form action="anno/testRequestBody" method="post"> 用户姓名:<input type="text" name="username" /><br/> 用户年龄:<input type="text" name="age" /><br/> <input type="submit" value="提交" /> </form> </body> </html>

2).创建常用的注解控制器类的代码如下:

package com.txw.controller; import com.txw.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 javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Date; import java.util.Map; /** * 常用的注解 *@author Adair */ @Controller @RequestMapping("/anno") @SuppressWarnings("all") // 注解警告信息 public class AnnoController { /** * 获取到请求体的内容 * @return */ @RequestMapping("/testRequestBody") public String testRequestBody(@RequestBody String body){ System.out.println("执行了..."); System.out.println(body); return "success"; } }

3).使用TomCat运行结果如图: 4).通过浏览器访问http://localhost:8080/params.jsp结果如图所示: 5).点击RequestParam会跳转到如图所示的界面: 6).控制台打印结果如图所示: 1.3 PathVaribale 作用: 用于绑定url中的占位符。例如:请求url中 /delete/{id},这个{id}就是url占位符。 url支持占位符是spring3.0之后加入的。是springmvc支持rest风格URL的一个重要标志。 属性: value:用于指定url中占位符名称。 required:是否必须提供占位符。 1).在anno.jsp编写如下代码:

<%-- Created by IntelliJ IDEA. User: Adair Date: 2018/4/29 Time: 23:35 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%--常用的注解--%> <a href="anno/testPathVariable/10">testPathVariable</a> </body> </html>

2).创建常用的注解控制器类的代码如下:

package com.txw.controller; import com.txw.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 javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Date; import java.util.Map; /** * 常用的注解 *@author Adair */ @Controller @RequestMapping("/anno") @SuppressWarnings("all") // 注解警告信息 public class AnnoController { /** * PathVariable注解 * @return */ @RequestMapping(value="/testPathVariable/{sid}") public String testPathVariable(@PathVariable(name="sid") String id){ System.out.println("执行了..."); System.out.println(id); return "success"; } }

3).使用TomCat运行结果如图: 4).通过浏览器访问http://localhost:8080/params.jsp结果如图所示: 5).点击testPathVariable会跳转到如图所示的界面: 6).控制台打印结果如图所示: 1.4 REST风格URL 什么是rest: REST(英文:Representational State Transfer,简称REST)描述了一个架构样式的网络系统,比如 web 应用程序。它首次出现在 2000 年 Roy Fielding 的博士论文中,他是 HTTP 规范的主要编写者之一。在目前主流的三种Web服务交互方案中,REST相比于SOAP(Simple Object Access protocol,简单对象访问协议)以及XML-RPC更加简单明了,无论是对URL的处理还是对Payload的编码,REST都倾向于用更加简单轻量的方法设计和实现。值得注意的是REST并没有一个明确的标准,而更像是一种设计的风格。 它本身并没有什么实用性,其核心价值在于如何设计出符合REST风格的网络接口。 restful的优点 它结构清晰、符合标准、易于理解、扩展方便,所以正得到越来越多网站的采用。 restful的特性: 资源(Resources):网络上的一个实体,或者说是网络上的一个具体信息。 它可以是一段文本、一张图片、一首歌曲、一种服务,总之就是一个具体的存在。可以用一个URI(统一资源定位符)指向它,每种资源对应一个特定的 URI 。要获取这个资源,访问它的URI就可以,因此 URI 即为每一个资源的独一无二的识别符。 表现层(Representation):把资源具体呈现出来的形式,叫做它的表现层 (Representation)。 比如,文本可以用 txt 格式表现,也可以用 HTML 格式、XML 格式、JSON 格式表现,甚至可以采用二进制格式。 状态转化(State Transfer):每 发出一个请求,就代表了客户端和服务器的一次交互过程。 HTTP协议,是一个无状态协议,即所有的状态都保存在服务器端。因此,如果客户端想要操作服务器,必须通过某种手段,让服务器端发生“状态转化”(State Transfer)。而这种转化是建立在表现层之上的,所以就是 “表现层状态转化”。具体说,就是 HTTP 协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。它们分别对应四种基本操作:GET 用来获取资源,POST 用来新建资源,PUT 用来更新资源,DELETE 用来删除资源。 restful的示例:

/account/1 HTTP GET : 得到 id = 1 的 account /account/1 HTTP DELETE: 删除 id = 1的 account /account/1 HTTP PUT: 更新id = 1的 account /account HTTP POST: 新增 account

1.5 HiddentHttpMethodFilter过滤器 作用: 由于浏览器 form 表单只支持 GET 与 POST 请求,而DELETE、PUT 等 method 并不支持,Spring3.0 添加了一个过滤器,可以将浏览器请求改为指定的请求方式,发送给我们的控制器方法,使得支持 GET、POST、PUT 与DELETE 请求。 使用方法: 第一步:在web.xml中配置该过滤器。 第二步:请求方式必须使用post请求。 第三步:按照要求提供_method请求参数,该参数的取值就是我们需要的请求方式。 1.6 RequestHeader注解 作用: 用于获取请求消息头。 属性: value:提供消息头名称 required:是否必须有此消息头。 注: 在实际开发中一般不怎么用。 1).在anno.jsp编写如下代码:

<%-- Created by IntelliJ IDEA. User: Adair Date: 2018/4/29 Time: 23:35 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%--常用的注解--%> <a href="anno/testRequestHeader">RequestHeader</a> </body> </html>

2).创建常用的注解控制器类的代码如下:

package com.txw.controller; import com.txw.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 javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Date; import java.util.Map; /** * 常用的注解 *@author Adair */ @Controller @RequestMapping("/anno") @SuppressWarnings("all") // 注解警告信息 public class AnnoController { /** * 获取请求头的值 * @param header * @return */ @RequestMapping(value="/testRequestHeader") public String testRequestHeader(@RequestHeader(value="Accept") String header, HttpServletRequest request,HttpServletResponse response) throws IOException { System.out.println("执行了..."); System.out.println(header); return "success"; } }

3).使用TomCat运行结果如图: 4).通过浏览器访问http://localhost:8080/params.jsp结果如图所示: 5).点击RequestParam会跳转到如图所示的界面: 6).控制台打印结果如图所示: 1.7 CookieValue注解 作用: 用于把指定cookie名称的值传入控制器方法参数。 属性: value:指定cookie的名称。 required:是否必须有此cookie。 1).在anno.jsp编写如下代码:

<%-- Created by IntelliJ IDEA. User: Adair Date: 2018/4/29 Time: 23:35 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%--常用的注解--%> <a href="anno/testCookieValue">CookieValue</a> </body> </html>

2).创建常用的注解控制器类的代码如下:

package com.txw.controller; import com.txw.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 javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Date; import java.util.Map; /** * 常用的注解 *@author Adair */ @Controller @RequestMapping("/anno") @SuppressWarnings("all") // 注解警告信息 public class AnnoController { /** * 获取Cookie的值 * @return */ @RequestMapping(value="/testCookieValue") public String testCookieValue(@CookieValue(value="JSESSIONID") String cookieValue){ System.out.println("执行了..."); System.out.println(cookieValue); return "success"; } }

3).使用TomCat运行结果如图: 4).通过浏览器访问http://localhost:8080/params.jsp结果如图所示: 5).点击CookieValue会跳转到如图所示的界面: 6).控制台打印结果如图所示: 1.8 ModelAttribute注解 作用: 该注解是SpringMVC4.3版本以后新加入的。它可以用于修饰方法和参数。 出现在方法上,表示当前方法会在控制器的方法执行之前,先执行。它可以修饰没有返回值的方法,也可以修饰有具体返回值的方法。 出现在参数上,获取指定的数据给参数赋值。 属性: value:用于获取数据的key。key可以是POJO的属性名称,也可以是map结构的key。 应用场景: 当表单提交数据不是完整的实体类数据时,保证没有提交数据的字段使用数据库对象原来的数据。 例如: 我们在编辑一个用户时,用户有一个创建信息字段,该字段的值是不允许被修改的。在提交表单数据是肯定没有此字段的内容,一旦更新会把该字段内容置为null,此时就可以使用此注解解决问题。 1).在anno.jsp编写如下代码:

<%-- Created by IntelliJ IDEA. User: Adair Date: 2018/4/29 Time: 23:35 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%--常用的注解--%> <form action="anno/testModelAttribute" method="post"> 用户姓名:<input type="text" name="uname" /><br/> 用户年龄:<input type="text" name="age" /><br/> <input type="submit" value="提交" /> </form> </body> </html>

2).创建常用的注解控制器类的代码如下:

package com.txw.controller; import com.txw.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 javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Date; import java.util.Map; /** * 常用的注解 *@author Adair */ @Controller @RequestMapping("/anno") @SuppressWarnings("all") // 注解警告信息 public class AnnoController { /** * 获取Cookie的值 * @return */ @RequestMapping(value="/testCookieValue") public String testCookieValue(@CookieValue(value="JSESSIONID") String cookieValue){ System.out.println("执行了..."); System.out.println(cookieValue); return "success"; } /**@ModelAttribute public void showUser(String uname, Map<String,User> map){ System.out.println("showUser执行了..."); // 通过用户查询数据库(模拟) User user = new User(); user.setUname(uname); user.setAge(20); user.setDate(new Date()); map.put("abc",user); }*/ /** * 该方法会先执行 @ModelAttribute public User showUser(String uname){ System.out.println("showUser执行了..."); // 通过用户查询数据库(模拟) User user = new User(); user.setUname(uname); user.setAge(20); user.setDate(new Date()); return user; } }

3).使用TomCat运行结果如图: 4).通过浏览器访问http://localhost:8080/params.jsp结果如图所示: 5).点击提交会跳转到如图所示的界面: 6).控制台打印结果如图所示: 1.9 SessionAttributes注解 作用: 用于多次执行控制器方法间的参数共享。 属性: value:用于指定存入的属性名称 type:用于指定存入的数据类型。 1).在anno.jsp编写如下代码:

<%-- Created by IntelliJ IDEA. User: Adair Date: 2018/4/29 Time: 23:35 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%--常用的注解--%> <a href="anno/testSessionAttributes">testSessionAttributes</a> <a href="anno/getSessionAttributes">getSessionAttributes</a> <a href="anno/delSessionAttributes">delSessionAttributes</a> </body> </html>

2).创建常用的注解控制器类的代码如下:

package com.txw.controller; 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; /** * 常用的注解 *@author Adair */ @Controller @RequestMapping("/anno") @SessionAttributes(value={"msg"}) // 把msg=美美存入到session域对中 @SuppressWarnings("all") // 注解警告信息 public class AnnoController { /** * SessionAttributes的注解 * @return */ @RequestMapping(value="/testSessionAttributes") public String testSessionAttributes(Model model){ System.out.println("testSessionAttributes..."); // 底层会存储到request域对象中 model.addAttribute("msg","美美"); return "success"; } /** * 获取值 * @param modelMap * @return */ @RequestMapping(value="/getSessionAttributes") public String getSessionAttributes(ModelMap modelMap){ System.out.println("getSessionAttributes..."); String msg = (String) modelMap.get("msg"); System.out.println(msg); return "success"; } /** * 清除 * @param status * @return */ @RequestMapping(value="/delSessionAttributes") public String delSessionAttributes(SessionStatus status){ System.out.println("delSessionAttributes..."); status.setComplete(); return "success"; } }

3).使用TomCat运行结果如图: 4).通过浏览器访问http://localhost:8080/params.jsp结果如图所示: 需要修改成功页面的代码如下:

<%-- Created by IntelliJ IDEA. User: Adair Date: 2020/7/1 0030 Time: 9:37 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>成功页面</title> </head> <body> <h3>入门成功!!!!!</h3> ${requestScope.msg } ${sessionScope } </body> </html>
最新回复(0)