SpringMVC获取请求带来的各种信息
一、默认方法获取参数
直接给方法入参写一个和请求名请求名相同的变量,这个变量就来接收请求参数的值
运行截图
二、获取请求参数的值-@RequestParam
参数默认是必带的
http://localhost:8080/SpringMVC/hand01? 报错400
@RequestParam(“user”)String usrname
usrname=requeset.getParameter(“user”);
value:指定要获取的参数的key(浏览器地址栏里的参数)
required:参数是否必带,required=false:不带不报错
defaultValue:不带参数时显示的值,默认为null
@RequestMapping("/hand01")
public String hand01(@RequestParam(value="user",required=false,defaultValue="ss")String usrname){
System.out.println("变量:"+usrname);
return "success";
}
@RequestParam(“user”)与 @PathVariable(“user”)区别
三、获取请求头中的信息-@RequestHeader
request.getHeader(“User-Agent”)
@RequestHeader(“User-Agent”)String userAgent
userAgent=request.getHeader(“User-Agent”)
三个属性同@RequestParam
@RequestMapping("/hand01")
public String hand01(@RequestHeader("User-Agent")String userAgent){
System.out.println("请求头中浏览器的信息:"+userAgent);
return "success";
}
四、获取请求中带来的某个cookie的值-@CookieValue
以前获取某个cookie的操作
Cookie[] cookies = request.getCookies();
for(Cookie c:cookies){
if(c.getName().equals("SESSIONID")){
String cv = c.getValue();
}
}
@CookieValue
@RequestMapping("/hand01")
public String hand01(@CookieValue(value="JSESSIONID",required=false)String jid){
System.out.println("cookie中jid的值:"+jid);
return "success";
}
五、传入-POJO
如果我们的请求参数数一个POJO
SpringMVC自动为这个POJO进行赋值:
1)将POJO中的每个属性,从request参数中尝试获取出来,并封装
2)还可以级联封装;属性的属性
@RequestMapping("/book")
public String addBook(Book book){
System.out.println("我要保存的图书:"+book);
return "success";
}
package com.jh.book;
public class Book {
private String bookName;
private String author;
private Double price;
private Integer stock;
private Integer sales;
private Adress adress;
package com.jh.book;
public class Adress {
private String province;
private String city;
private String street;
<form action="book" method="post">
书名:<input type="text" name="bookName"><br>
作者:<input type="text" name="author"><br>
价格:<input type="text" name="price"><br>
库存:<input type="text" name="stock"><br>
销量:<input type="text" name="sales"><br>
<hr>
作者省: <input type="text" name="Adress.province">
市: <input type="text" name="Adress.city">
街道: <input type="text" name="Adress.street">
<br>
<input type="submit">
</form>
解决乱码问题
提交的数据可能乱码
1.请求乱码
GET请求:改server.xml
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
POST请求:web.xml配置filter
web.xml中配置如下即可
<!-- 配置一个字符编码的filter -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- encoding:指定解决POST请求乱码 -->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<!-- forceEncoding:顺手解决响应乱码 -->
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.响应乱码
response.setContentType(“Text/html;charset=utf-8”)