客服端的请求参数的格式为:...?username=Alice&age=12...
SpringMVC框架接受到请求参数时,还可以对其进行封装:①基本类型 ②POJO类型 ③数组类型 ④集合类型
根据名称自动匹配。且可以自动类型转换(String -> ?)
@RequestMapping("/test1")
@ResponseBody
public void test10(String username, int age) throws IOException {
System.out.println(username);
System.out.println(age);
// http://localhost:8080/test1?username=Alice&age=12
}
竟然也可以根据名称自动匹配!
@RequestMapping("/test2")
@ResponseBody
public void test11(User user) throws IOException {
System.out.println(user);
// http://localhost:8080/test2?username=Alice&age=12
}
还是自动匹配。
@RequestMapping("/test3")
@ResponseBody
public void test3(String[] lolis) throws IOException {
System.out.println(Arrays.toString(arr));
// http://localhost:8080/test3?lolis=Alice&lolis=Cocoa&lolis=Hana
}
注意,这里不能直接根据请求参数名称自动匹配,而必须用POJO类型过渡一下。
重难点!!!弄清楚是如何过渡和对应的!!!
domain.VO过渡类 ----------------------------------------------------------------------------
public class VO {
private List<User> userList;
// generate...
}
<html>
<head>
<title>Titletitle>
head>
<body>
<form action="${pageContext.request.contextPath}/test4" method="post">
<input type="text" name="userList[0].username" />
<input type="text" name="userList[0].age" />
<br />
<input type="text" name="userList[1].username" />
<input type="text" name="userList[1].age" />
<br />
<input type="text" name="userList[2].username" />
<input type="text" name="userList[2].age" />
<br />
<input type="submit" value="提交">
form>
body>
html>
@RequestMapping("/test4")
@ResponseBody
public void test4(VO vo) throws IOException {
System.out.println(vo);
// http://localhost:8080/form.jsp
}
当请求由Ajax发出,且contentType为json格式,则可用加上 @RequestBody 注解的集合类型直接获得。
<html>
<head>
<title>Titletitle>
<script src="${pageContext.request.contextPath}/js/jquery-3.3.1.js" />
<script>
var userList = new Array();
userList.push({username:"Alice",age:12});
userList.push({username:"Hana",age:10});
$.ajax({
type:"POST",
url:"${pageContext.request.contextPath}/test5",
data:JSON.stringify(userList),
contentType:"application/json;charset=utf-8"
});
script>
head>
<body>
body>
html>
@RequestMapping("/test5")
@ResponseBody
public void test5(@RequestBody List<User> userList) throws IOException {
System.out.println(userList);
// http://localhost:8080/ajax.jsp
}
当我们在SpringMVC框架下去访问诸如/js/jquery-3.3.1.js
或/img/pic1.jpg
时,却显示找不到该目录或资源。
这是因为,我们在配置整个框架的核心——前端控制器DispatcherServlet时,是这样写的:
<servlet>
<servlet-name>DispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>DispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
注意这句
,其含义是:所有的资源(动态资源/静态资源)都会被DispatcherServlet拦截。
所以,我们要做的,就是“放行”这些静态资源。换句话说,开放它们的访问权限。
在spring-mvc.xml中,有以下两种配置方式:
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/img/**" location="/img/" />
<mvc:default-servlet-handler />
POST方式的中文请求数据,会出现乱码问题。我们使用一个全局过滤器进行解决。
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
上面说的中文乱码问题是指提交来的请求数据,这里指的是回写给页面的响应字符串。
@RequestMapping(value = "/test7", produces = "text/html;charset=UTF-8")
@ResponseBody
public String save(User user) {
userService.save(user);
return "保存成功!!!";
}
请求的参数名称可能与接收的参数名称不一致。此时需要借助 @RequestParam 注解绑定这两个不同的名称。
@RequestMapping("/test6")
@ResponseBody
public void test6(@RequestParam("name") String username) throws IOException {
System.out.println(username);
// http://localhost:8080/test6?name=Alice
}
该注解非常强大:
-------------------------------------------------------------------------------------------
注解@RequestParam还可以配置的参数:
- value: 请求参数的名称
- required: 请求是否必须包含该参数(默认true)
- defaultValue: 当请求不包含该参数时,则使用的默认值
-------------------------------------------------------------------------------------------
@RequestMapping("/test7")
@ResponseBody
public void test7(@RequestParam(value = "name", required = false, defaultValue = "Alice") String username) throws IOException {
System.out.println(username);
// http://localhost:8080/test7
}
Restful风格的请求用“URL+请求方式(GET/POST/PUT/DELETE)”表示出一次目的。
并且,请求参数不再以?key=value
的格式跟在URL尾巴后面,而是作为URL地址的一部分(比如http://localhost:8080/test/Alice
)。
因此,在获取该请求参数时,需要借助占位符以及 @PathVariable 注解。
@RequestMapping("/test8/{username}")
@ResponseBody
public void test8(@PathVariable("username") String username) throws IOException {
System.out.println(username);
// http://localhost:8080/test8/Alice
}
SpringMVC时提供了默认的类型转换器,因此我们得以用int
来接收String
。
但是日期的格式国家差异较大,SpringMVC可以将yyyy/MM/dd
的字符串转换为日期类型,但对诸如yyyy-MM-dd
的字符串便无能为力。
我们可以手写一个继承了Converter接口的类型转换器,并将它加入到类型转换工厂中。
① 自定义类型转换器(converter.DateConverter.class)
public class DateConverter implements Converter<String, Date> {
// 实现接口内部的convert方法
public Date convert(String s) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
② 在配置文件中进行相关声明(spring-mvc.xml)
<bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.samarua.converter.DateConverter" />
list>
property>
bean>
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean" />
③ 测试
@RequestMapping("/test9")
@ResponseBody
public void test9(Date date) throws IOException {
System.out.println(date);
// http://localhost:8080/test9?data=2022-12-12
}
这个问题之前已经讲过:在SpringMVC框架环境下,想使用WebServlet原生API,可以将这些原生对象写在方法的参数中,调用者(即框架)会自动进行注入,我们放心使用即可。
@RequestMapping("/test10")
@ResponseBody
public void test10(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
System.out.println(request);
System.out.println(response);
System.out.println(session);
}
上面的所有内容,都是获取请求行的信息。下面,我们尝试获取请求头的信息。
首先明确,请求行的格式是【请求方式 请求url 请求协议/版本】,请求头的格式是【键值对】(看下图)
获取请求头中任意键值对的信息,使用 @RequestHeader 注解:
@RequestMapping("/test11")
@ResponseBody
public void test11(@RequestHeader(value = "User-Agent") String userAgent) throws IOException {
System.out.println(userAgent);
}
特殊情况,直接获取请求头中Cookie中任意一个键值对的信息,使用 @CookieValue 注解:
@RequestMapping("/test12")
@ResponseBody
public void test12(@CookieValue(value = "JSESSIONID") String JSESSIONID) throws IOException {
System.out.println(JSESSIONID);
}
More >_<