SpringMVC的数据响应
SpringMVC的数据响应方式
- 页面跳转
- 直接返回字符串
- 通过ModelAndView对象返回
- 回写数据
- 直接返回字符串
- 返回对象或集合
页面跳转
-
返回字符串形式
直接返回字符串:这种方式会将返回的字符串与视图解析器的前后缀拼接后进行跳转
返回带前缀的字符串
- 返回ModelAnyView对象
@RequestMapping("/quick2")
public ModelAndView quickMethod2(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("redirect:index.jsp");
return modelAndView;
}
@RequestMapping("/quick3")
public ModelAndView quickMethod3(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName(("forward:/jsp/success.jsp"));
return modelAndView;
}
-
向Request域中存储数据
- 通过SpringMVC框架注入的request对象setAttribute()方法设置
@RequestMapping("/quick4") public String quickMethod4(HttpServletRequest request){ request.setAttribute("name","capkin"); return "success"; }
- 通过ModelAndView的addObject()方法设置
@RequestMapping("/quick5") public ModelAndView quickMethod5(){ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("forward:/jsp/success.jsp"); modelAndView.addObject("name","lisi"); return modelAndView; }
回写数据
在javaweb阶段,客户端访问服务器,若想将字符串 作为响应体返回的话,只需要使用response.getWriter().print(“Hello World”)即可,在Controler中
-
通过SpringMVC注入的response对象,使用response.getWriter().print(“Hello World”)回写数据,此时不需要视图跳转,业务方法返回值为void
@RequestMapping("/quick6") public void quickMethod6(HttpServletResponse response) throws IOException { response.getWriter().print("HelloWorld"); }
-
将需要回写的字符串直接返回,但此时需要@ResponseBody注解告知该字符串不是跳转而是在http响应体中返回
@RequestMapping("/quick7") @ResponseBody public String quickMethod7() throws IOException { return "hello springMVC!!!"; }
-
在异步的项目中,客户端和服务器往往要进行json格式字符串的交互,此时我们可以通过手动拼接json字符串返回
@RequestMapping("/quick8") @ResponseBody public String quickMethod8() { return "{\"name\":\"zhangsan\",\"age\":18}"; }
-
由于手动拼接比较麻烦,且在开发过程中,通常要将Java对象转换成json格式符,此时可以用jakeson进行转换
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.12.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.12.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.4</version> </dependency>
@RequestMapping("/quick9") @ResponseBody public String quickMethod9() throws JsonProcessingException { User user = new User(); user.setName("capkin"); user.setAge(18); ObjectMapper objectMapper = new ObjectMapper(); String s = objectMapper.writeValueAsString(user); return s; }
-
-
返回集合或对象
在方法上添加@ResponseBody就可以返回json格式的字符串,但是比较麻烦,我们可以采用mvc的注解驱动来完成
<!--在springmvc配置文件中进行配置RequestMappingHnadlerAdapter,注入list集合,list集合来自于Jackson --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean> </list> </property> </bean>
//返回对象 @RequestMapping("/quick10") @ResponseBody public User quickMethod10() { User user = new User(); user.setName("capkin"); user.setAge(18); return user; }
//返回集合 @RequestMapping("/quick11") @ResponseBody public ArrayList<String> quickMethod11(){ ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("capkin"); arrayList.add("willow"); return arrayList; }
SpringMVC获得请求数据
获得请求参数
客户端请求参数的格式是:name=value&name=value… …
服务端要获得请求的参数,有时还需要对数据进行封装,SpringMVC可以接收如下类型的参数:
- 基本数据类型
- POJO类型参数
- 数组类型参数
- 集合类型参数
获得基本类型参数
Controller中的业务方法的参数名称要与请求参数的name一致,参数值会自动映射匹配
http://localhost/SpringB2/quick12?username=capkin&age=18
@RequestMapping("/quick12")
@ResponseBody
public void quickMethod12(String username,int age){
System.out.println(username);
System.out.println(age);
}
获得POJO类型参数
Controller中的业务方法的POJO参数的属性名与其请求参数的name一致,参数值会自动映射匹配
http://localhost/SpringB2/quick13?name=capkin&age=18
@RequestMapping("quick13")
@ResponseBody
public void quickMethod13(User user){
System.out.println(user);
System.out.println(user.getAge());
System.out.println(user.getName());
}
获得数组类型参数
Controller中的业务方法数组名称与请求参数的name一致,参数值会自动映射匹配
http://localhost/SpringB2/quick14?strings=11&strings=12&strings=13
@RequestMapping("/quick14")
@ResponseBody
public void quickMethod14(String[] strings){
System.out.println(Arrays.asList(strings));
}
获得集合类型参数
获得集合参数时,要将集合参数包装到一个POJO中才可以
public class VO {
private List<User> userList;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
@Override
public String toString() {
return "VO{" +
"userList=" + userList +
'}';
}
}
@RequestMapping("/quick15")
@ResponseBody
public void quickMethod15(VO vo){
System.out.println(vo.getUserList());
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>null</title>
</head>
<body>
<h1>hello</h1>
<form action="${pageContext.request.contextPath}/quick15" method="post">
<input type="text" name="userList[0].name"><br>
<input type="text" name="userList[0].age"><br>
<input type="text" name="userList[1].name"><br>
<input type="text" name="userList[1].age"><br>
<input type="submit" value="提交"><br>
</form>
</body>
</html>
当使用ajax提交时,可以指定contextType为json类型,那么在方法参数位置使用@RequestBody可以直接接收集合数据而无需使用POJO进行包装
<script>
var userList = new Array();
userList.push({username:"张三",age:"20"});
userList.push({username:"lisi",age:"18"});
$.ajax({
type:"POST",
url:"/SpringJC/quick4",
data:JSON.stringify(userList),
contentType:'application/json;charset=utf-8'
});
</script>
@RequestMapping("/quick4")
@ResponseBody
public void quick4(@RequestBody List<User> userList){
System.out.println(userList);
for (int i = userList.size() - 1; i >= 0; i--) {
System.out.println(userList.get(i).getUsername() + userList.get(i).getAge());
}
}
静态资源被拦截
- 解决方案一:
<mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
对指定的资源放行
- 解决方案二:
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
在最后面对资源进行描述,如果在SpringMVC容器中找不到,就交还给原容器中找
请求数据乱码
当post请求数据时,数据会出现乱码,我们可以设置一个过滤器来进行编码的过滤。
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
@RequestParam参数绑定注解
当请求的参数名称与Controoller中的业务方法的参数名称不一致时,就需要通过@RequestParam注解显示的绑定。
<form action="${pageContext.request.contextPath}/quick5" method="post">
<input type="text" name="name"><br>
<input type="submit" value="提交"><br>
</form>
@RequestMapping("/quick5")
@ResponseBody
public void quick5(@RequestParam(value="name",required = false,defaultValue = "capkin")String username){
System.out.println(username);
}
- value:与请求参数的名称
- required:在此指定的请求参数是否必须包括,默认是true
- defaultValue:当请求没有指定参数时,就采取一个默认的参数
获得Result风格的参数
Result是一种软件架构风格、设计风格,不是标准,只是提供了一组设计原则和约束条件
主要用于客户端和服务器交互类的软件,基于这个风格设计的软件可以更简洁,更有层次,更容易实现缓存机制。
请求风格:
- GET:获取资源
- POST:新建资源
- PUT:更新资源
- DELETE:删除资源
eg:
- /user/1 GET: 得到id的1的user
- 余下同理
@RequestMapping("/quick6/{name}")
@ResponseBody
public void quick6(@PathVariable(value = "name",required = true)String name){
System.out.println(name);
}
http://localhost:8080/SpringJC/quick6/cwx
自定义类型转换器
SpringMVC默认已经提供了一些类型转换器。
而有些时候我们需要使用一些其他的转换器,此时就需要自己定义。
- 定义转换器实现Converter接口
package xyz.nchu200462.converter;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConverter implements Converter<String, Date> {
public Date convert(String source) {
SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd");
try {
Date date = format.parse(source);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
- 在配置文件中声明转换器
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="converterService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="xyz.nchu200462.converter.DateConverter"></bean>
</list>
</property>
</bean>
- 在<annotation-driven>中引用转换器
<mvc:annotation-driven conversion-service="converterService"/>
获得Servlet相关API
SpringMVC支持使用原始的ServletAPI对象作为控制器方法的参数注入
- HttpServletRequest
- HttpServletResponse
- HttpSession
@RequestMapping("/test04")
@ResponseBody
public void quickMethod3(HttpServletRequest request, HttpServletResponse response, HttpSession session){
System.out.println(request);
System.out.println(response);
System.out.println(session);
}
获得请求头
@RequestHeader
- value:请求头名称
- required:是否必须携带
@RequestMapping("/test02")
public void quickMethod1(@RequestHeader(value = "User-Agint",required = false) String headValue) {
System.out.println(headValue);
}
@CookieValue
- value:指定Cookie的名称
- required:是否必须携带
@RequestMapping("/test05")
@ResponseBody
public void quickMethod4(@CookieValue(value = "JESSIONID",required = false) String jsessionid){
System.out.println(jsessionid);
}
文件上传
客户端三要素
- 表单项type=“file”
- 表单的提交方式为post
- 表单的enctype属性是多部分表单形式,及entype=“multipart/form-data”
<form action="${pageContext.request.contextPath}/test06" method="post" enctype="multipart/form-data">
名称:<input type="text" name="username">
文件:<input type="file" name="file">
<input type="submit" value="提交">
</form>
原理
- 当form表单修改为多部分表单,request.getParameter()会失效
- enctype="application/x-www-form-urlencoded"时,表单的正文内容格式是:key=value&key=value&key=value
- 当form表单的enctype取值为Multilpart/form-data时,请求正文内容就变成了多部分形式
单文件上传
导入fileupload和io
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
配置文件上传解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxInMemorySize" value="5242800"/>
<property name="maxUploadSizePerFile" value="524800"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
编写文件上传代码
@RequestMapping("/test06")
@ResponseBody
public void quickMethod5(String username, MultipartFile file) throws IOException {
System.out.println(username);
String originalFilename = file.getOriginalFilename();
file.transferTo(new File("C:\\Users\\Lenovo\\Desktop\\code\\" + originalFilename));
}
多文件上传
将方法参数MultipartFile改为数组MultipartFile[]
然后在上传代码中对每个文件进行遍历