Spring MVC代码实例系列-03:@PathVariable、@RequestHeader、@RequestParam、@RequestBody、@ModelAttribute等
超级通道 :Spring MVC代码实例系列-绪论
本章主要进行请求参数相关注解的实例编码,涉及到的技术有:
- @PathVariable:用于构建Restful
风格的GET
请求URL
- @RequestHeader:用于获取http请求的header
部分信息
- @RequestParam:用于获取简单数据类型的参数如String
、List<Integer>
等
- @RequestBody:将传入的JSON字符串获取XML转化成POJO,如MyUser
等。
- @ResponseBody:将返回的POJO对象转化成JSON字符串或者XML。一般与@RequestBody搭配。
- @SessionAttribute:用于设置和获取session作用域的数据
- @ModelAttribute:用于设置类作用域的数据和传参
- Spring MVC 静态资源文件加载方式
1.目录结构
src
\---main
\---java
| \---pers
| \---hanchao
| \---hespringmvc
| \---requestannotation
| \---RequestAnnotationController.java
| \---User.java
\---webapp
\---requestannotation
| \---pathvariable.jsp
| \---requestheader.jsp
| \---requestparam.jsp
| \---sessionattribute.jsp
| \---modelattribute.jsp
\---static
| \---query-3.2.1.min.js
\---WEB-INF
| \---spring-mvc-servlet.xml
| \---web.xml
\---index.jsp
2.Spring MVC加载静态资源文件
两种方式:
1. 使用mvc:default-servlet-handler
2. 通过mvc:resources指定静态资源
具体看代码:spring-mvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--开启component注解自动扫描-->
<context:component-scan base-package="pers.hanchao.*"/>
<!-- Spring MVC默认的注解映射的支持 :提供Controller请求转发,json自动转换等功能-->
<mvc:annotation-driven />
<!--开启注解:提供spring容器的一些注解-->
<context:annotation-config/>
<!--静态资源处理方式一:使用mvc:default-servlet-handler,
default-servlet-name="所使用的Web服务器默认使用的Servlet名称",一般情况下为"default" -->
<!--<mvc:default-servlet-handler default-servlet-name="default"/>-->
<!--静态资源处理方式二:通过mvc:resources指定静态资源-->
<!--所有URI为"/static/**"的资源都从"/static/"里查找,这些静态资源缓存1年(即 : 31536000秒)-->
<mvc:resources mapping="/static/**" location="/static/" cache-period="31536000"/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
aaa@qq.com实例
@PathVariable实例:用来构成restful风格的URL请求的一种方式,只适合GET请求
3.1.RequestAnnotationController.java
package pers.hanchao.hespringmvc.requestannotation;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
/**
* <p>参数请求相关注解实例</p>
* @author hanchao 2018/1/14 18:09
**/
@Controller
@RequestMapping("/requestannotation")
public class RequestAnnotationController {
/**
* <p>@PathVariable实例:用来构成restful风格的URL请求的一种方式,只适合GET请求</p>
* @author hanchao 2018/1/14 0:43
**/
@GetMapping("/getpathvariable/{name}/time/{time}")
public String getPathVariable(@PathVariable String name,@PathVariable String time,Model model){
model.addAttribute("name",name);
model.addAttribute("time",time);
return "/requestannotation/pathvariable";
}
}
3.2.requestheader.jsp
<%--
Created by IntelliJ IDEA.
User: hanchao
Date: 2018/1/14
Time: 0:54
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>@RequestHeader</title>
</head>
<body>
<h4>Accept:${accept}</h4>
<h4>Accept-Encoding:${encoding}</h4>
<h4>Accept-Language:${language}</h4>
<h4>Connection:${alive}</h4>
<h4>Cookie:${cookie}</h4>
<h4>Host:${host}</h4>
<h4>Referer:${referer}</h4>
<h4>Upgrade-Insecure-Requests:${upgrade}</h4>
<h4>User-Agent:${agent}</h4>
</body>
</html>
3.3.index.jsp
<%--@PathVariable实例--%>
<a href="/requestannotation/getpathvariable/张三/time/昨天">@PathVariable实例 : /requestannotation/getpathvariable/张三/time/昨天</a><hr/>
3.4.result
aaa@qq.com
@RequestHeader实例:用来获取Header信息,GET和POST都可以
4.1.RequestAnnotationController.java
package pers.hanchao.hespringmvc.requestannotation;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
/**
* <p>参数请求相关注解实例</p>
* @author hanchao 2018/1/14 18:09
**/
@Controller
@RequestMapping("/requestannotation")
public class RequestAnnotationController {
/**
* <p>@RequestHeader实例:用来获取Header信息,GET和POST都可以</p>
* @author hanchao 2018/1/14 0:52
**/
@GetMapping("/requestheader")
public String getRequestHeader(@RequestHeader("Accept") String accept,
@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Accept-Language") String language,
@RequestHeader("Connection") String alive,
@RequestHeader("Cookie") String cookie,
@RequestHeader("Host") String host,
@RequestHeader("Referer") String referer,
@RequestHeader("Upgrade-Insecure-Requests") String upgrade,
@RequestHeader("User-Agent") String agent,
Model model){
model.addAttribute("accept",accept);
model.addAttribute("encoding",encoding);
model.addAttribute("language",language);
model.addAttribute("alive",alive);
model.addAttribute("cookie",cookie);
model.addAttribute("host",host);
model.addAttribute("referer",referer);
model.addAttribute("upgrade",upgrade);
model.addAttribute("agent",agent);
return "/requestannotation/requestheader";
}
}
4.2.requestheader.jsp
<%--
Created by IntelliJ IDEA.
User: hanchao
Date: 2018/1/14
Time: 0:54
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>@RequestHeader</title>
</head>
<body>
<h4>Accept:${accept}</h4>
<h4>Accept-Encoding:${encoding}</h4>
<h4>Accept-Language:${language}</h4>
<h4>Connection:${alive}</h4>
<h4>Cookie:${cookie}</h4>
<h4>Host:${host}</h4>
<h4>Referer:${referer}</h4>
<h4>Upgrade-Insecure-Requests:${upgrade}</h4>
<h4>User-Agent:${agent}</h4>
</body>
</html>
4.3.index.jsp
<%--@RequestHeader实例--%>
<a href="/requestannotation/requestheader">@RequestHeader实例</a><hr/>
4.4.result
aaa@qq.com实例
- @RequestParam只能用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。
- @RequestParam可以理解为Request.getParameter()。
- 由于
GET
请求的queryString
的值和POST
请求中的body data的值都会被转化到Request.getParameter()中,所以#RequestParam可以获取到这些值。 - @RequestParam常用于获取简单类型的数据,如
String
、List<String>
等。
5.1.RequestAnnotationController.java
package pers.hanchao.hespringmvc.requestannotation;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
/**
* <p>参数请求相关注解实例</p>
* @author hanchao 2018/1/14 18:09
**/
@Controller
@RequestMapping("/requestannotation")
public class RequestAnnotationController {
/**
* <p>@RequestParam实例。@RequestParam可以理解为获取Request.getParameter()的参数。
* 由于get方式中queryString的值,和post方式中body data的值都会被Servlet接受到并转化到
* Request.getParameter()中,所以@RequestParam可以获取到。</p>
* <p>@RequestParam只能用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。</p>
* @author hanchao 2018/1/14 1:07
**/
@GetMapping("/getrequestparam")
public String getRequestParam(@RequestParam String getname,Model model){
model.addAttribute("getname",getname);
return "/requestannotation/requestparam";
}
/**
* <p>@RequestParam实例:GET和POST都可以,常用来处理简单类型,如String,List<String>等</>。</p>
* <p>@RequestParam只能用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。</p>
* @author hanchao 2018/1/14 1:11
**/
@PostMapping("/postrequestparam")
public String postRequestParam(@RequestParam String postname,Model model){
model.addAttribute("postname",postname);
return "/requestannotation/requestparam";
}
}
5.2.requestparam.jsp
<%--
Created by IntelliJ IDEA.
User: hanchao
Date: 2018/1/14
Time: 1:16
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>@RequestParam</title>
</head>
<body>
<h3>getRequestParam:${getname}</h3>
<h3>postRequestParam:${postname}</h3>
</body>
</html>
5.3.index.jsp
<%aaa@qq.com实例--%>
<a href="/requestannotation/getrequestparam?getname=张三">@RequestParam[GET]实例 : /requestannotation/getrequestparam?getname=张三</a><br>
<form action="/requestannotation/postrequestparam" method="post">
<input value="李四" name="postname">
<input type="submit" value="@RequestParam[POST]实例"/>
</form><hr/>
5.4.result
aaa@qq.com实例
- @RequestBody实例常用来处理Content-Type不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等。
- @RequestBody适合处理POJO类型的数据传参
- @RequestBody,在传参时会将JSON字符串转化为POJO对象
- 在返回值时,会将POJO对象转化成JSON字符串,这个实现需要@ResponseBody注解的帮助。
- 所以
pom.xml
中需要加入jackson
相关jar包。
6.1.RequestAnnotationController.java
package pers.hanchao.hespringmvc.requestannotation;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
/**
* <p>参数请求相关注解实例</p>
* @author hanchao 2018/1/14 18:09
**/
@Controller
@RequestMapping("/requestannotation")
public class RequestAnnotationController {
/**
* <p>@RequestBody实例:只能POST,常用来处理bean类型,该注解常用来处理Content-Type:
* 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等。
* @RequestBody 适合处理Json类型的传参,@ResponseBody将对象以Json的形式返回给前台
* </p>
* @author hanchao 2018/1/14 1:25
**/
@PostMapping("/requestbody")
@ResponseBody
public User postRequestBody(@RequestBody User user){
return user;
}
}
6.2.index.jsp
<%aaa@qq.com实例--%>
<input type="button" onclick="requestbody()" value="@RequestBody[POST]实例"/>
<input type="text" id="requestbody" class="text"/>
<hr/>
</body>
<script type="text/javascript" src="static/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
//@RequestBody实例:必须指定contentType:application/json
function requestbody() {
$.ajax({
type:"POST",
url:"/requestannotation/requestbody",
data:JSON.stringify(
{name:"张三",sex:"男"}
),
contentType:"application/json; charset=utf-8",
success:function (data) {
console.log(data);
$("#requestbody").val(data.name + "是" + data.sex + "的");
}
});
}
</script>
</html>
6.3.result
aaa@qq.com实例
@SessionAttributes,用于设置和获取session基本的数据。
7.1.RequestAnnotationController.java
package pers.hanchao.hespringmvc.requestannotation;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
/**
* <p>参数请求相关注解实例</p>
* @author hanchao 2018/1/14 18:09
**/
@Controller
@RequestMapping("/requestannotation")
//@SessionAttributes,将"session"的作用于设置为session级别的
@SessionAttributes(value = {"session"})
public class RequestAnnotationController {
/**
* <p>设置session</p>
* @author hanchao 2018/1/14 18:09
**/
@GetMapping("/setsession")
public String setSession(Model model){
System.out.println("set session");
model.addAttribute("session","Here is a session!");
model.addAttribute("request","Here is a request!");
return "redirect:/index.jsp";
}
/**
* <p>@SessionAttribute:指定获取的数据为session级别</p>
* @author hanchao 2018/1/14 18:10
**/
@GetMapping("/getsession")
public String getSession(){
return "/requestannotation/sessionattribute";
}
/**
* <p>@SessionAttribute:通过SessionStatus.setComplete()清除session作用域的值</p>
* @author hanchao 2018/1/15 22:10
**/
@GetMapping("/delsession")
public String delSession(SessionStatus sessionStatus){
sessionStatus.setComplete();
return "redirect:/index.jsp";
}
}
7.2.sessionattribute.jsp
<%--
Created by IntelliJ IDEA.
User: hanchao
Date: 2018/1/14
Time: 2:15
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>@SessionAttribute</title>
</head>
<body>
<h3>requestScope.request : ${requestScope.request}</h3>
<h3>sessionScope.session : ${sessionScope.session}</h3>
</body>
</html>
7.3.index.jsp
<%aaa@qq.com实例--%>
<a href="/requestannotation/setsession">@SessionAttribute实例[set]</a><br>
<a href="/requestannotation/getsession">@SessionAttribute实例[get]</a><br>
<a href="/requestannotation/delsession">@SessionAttribute实例[del]</a><br><hr/>
7.4.result
aaa@qq.com实例
@ModelAttribute主要有前两种用法(对我来说):
1. 注解在方法上:在执行每个业务方法前,执行这些被@ModelAttribute注解的类,提取设置好ModelAndView里的Model属性。
2. 注解在方法参数上:辅助传参,可以不加。
3. 注解在方法的返回值上…
8.1.RequestAnnotationController.java
package pers.hanchao.hespringmvc.requestannotation;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
/**
* <p>参数请求相关注解实例</p>
* @author hanchao 2018/1/14 18:09
**/
@Controller
@RequestMapping("/requestannotation")
public class RequestAnnotationController {
/**
* <p>@ModelAttribute 注解在void返回值的方法时,将一些值注入到ModelAndView中。</p>
* <p>@ModelAttribute 注解的方法,将会在当前类的其他方法执行前被执行。</p>
* @author hanchao 2018/1/15 21:28
*/
@ModelAttribute
public void setSimpleAttribute(Model model){
model.addAttribute("voidmethod","将一些值注入到ModelAndView中");
}
/**
* <p>@ModelAttribute 以默认方式,注解在非void返回值的方法时,将通过返回值的类型的小写格式,注入方法返回的值,
* 如当前方法相当于model.addAttribute("user",user);</p>
* <p>@ModelAttribute 注解的方法,将会在当前类的其他方法执行前被执行。</p>
* @author hanchao 2018/1/15 21:28
**/
@ModelAttribute
public User setDefaultBeanAttribute(){
User user = new User("message","以返回类型的小写格式为默认key,设置对象数据到Model中");
return user;
}
/**
* <p>@ModelAttribute 以指定方式,注解在非void返回值的方法时,将通过指定的key,注入方法返回的值,
* 如当前方法相当于model.addAttribute("useruser",user);</p>
* <p>@ModelAttribute 注解的方法,将会在当前类的其他方法执行前被执行。</p>
* @author hanchao 2018/1/15 21:34
**/
@ModelAttribute("methoduser")
public User setBeanAttribute(){
User user = new User("message","以指定的key,设置对象数据到Model中");
return user;
}
///@ModelAttribute和@RequestMapping一起使用的方式未写实例,因为不常用也不建议用
// @ModelAttribute
// @RequestMapping("/getxxx")
// public String getxxx(){}
///@ModelAttribute注释返回类型的用法未写实例,因为不常用也不建议用
// @RequestMapping
// public @ModelAttribute("uuuu") User getUser(){}
/**
* <p>@ModelAttribute实例:从请求中获取数据(不传也可以)</p>
* @author hanchao 2018/1/15 21:53
**/
@GetMapping("/getmodelattribute")
public String getUser(@ModelAttribute User user,@ModelAttribute("user2") User user2, Model model){
model.addAttribute("parammeteruser",user);
model.addAttribute("parammeteruser2",user2);
return "/requestannotation/modelattribute";
}
}
8.2.modelattribute.jsp
<%--
Created by IntelliJ IDEA.
User: hanchao
Date: 2018/1/15
Time: 21:46
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>@ModelAttribute</title>
</head>
<body>
<h3>@ModelAttribute 注解在void f()上: ${voidmethod}</h3>
<h3>@ModelAttribute 注解在Object f()上: ${user.sex}</h3>
<h3>@ModelAttribute(...)注解在Object f()上: ${methoduser.sex}</h3>
<h3>@ModelAttribute 注解在方法参数上: ${parammeteruser.sex}</h3>
<h3>@ModelAttribute 注解在方法参数上: ${parammeteruser2.sex}</h3>
</body>
</html>
8.3.index.jsp
<%--@ModelAttribute实例--%>
<a href="/requestannotation/getmodelattribute?name=张三&sex=传参,会覆盖默认的ModelAttribut">@ModelAttribute[GET]实例</a><br>