文章目录




SpringMVC的数据响应

SpringMVC的数据响应方式

1) 页面跳转

  • 直接返回字符串
  • 通过ModelAndView对象返回

2) 回写数据

  • 直接返回字符串
  • 返回对象或集合

页面跳转

1. 返回字符串形式

直接返回字符串:此种方式会将返回的字符串与视图解析器的前后缀拼接后跳转。

四、SpringMVC的请求和响应_SpringMVC

@RequestMapping(value="/test", method= RequestMethod.GET, params = {"username"})
public String test(){
// return "/test.jsp";
// return "forward:/test.jsp";
// return "redirect:/test.jsp";
return "test";
}

2. 返回ModelAndView对象

@RequestMapping(value="/test3")
public ModelAndView test3(ModelAndView modelAndView){

modelAndView.addObject("username", "hxx");
modelAndView.setViewName("test");
return modelAndView;
}

@RequestMapping(value="/test2")
public ModelAndView test2(){
/*
Model: 模型 作用封装数据
View: 视图 作用展示数据
*/
ModelAndView modelAndView = new ModelAndView();
// 设置模型数据
modelAndView.addObject("username", "wxx");
// 设置视图名称
modelAndView.setViewName("test");
return modelAndView;
}

在 test.jsp 中可以直接

${username}

3. 向request域存储数据

在进行转发时,往往要向 request 域中存储数据,在 jsp 页面中显示,那么Controller 中怎样向 request 域中存储数据呢?

① 通过SpringMVC框架注入的request对象setAttribute()方法设置

@RequestMapping(value="/test5")
public String test5(HttpServletRequest request){
request.setAttribute("username", "订单");
return "test";
}

② 通过ModelAndView的addObject()方法设置

@RequestMapping(value="/test3")
public ModelAndView test3(ModelAndView modelAndView){

modelAndView.addObject("username", "hxx");
modelAndView.setViewName("test");
return modelAndView;
}

@RequestMapping(value="/test2")
public ModelAndView test2(){
/*
Model: 模型 作用封装数据
View: 视图 作用展示数据
*/
ModelAndView modelAndView = new ModelAndView();
// 设置模型数据
modelAndView.addObject("username", "wxx");
// 设置视图名称
modelAndView.setViewName("test");
return modelAndView;
}

③ 通过 Model 中的 addAttribute() 方法设置

@RequestMapping(value="/test4")
public String test4(Model model){
model.addAttribute("username", "iiix");
return "test";
}

回写数据

1. 直接返回字符串

Web 基础阶段,客户端访问服务器端,如果想直接回写字符串作为响应体返回的话,只需要使用 ​​response.getWriter().print(“hello world”)​​​ 即可,那么在 ​​Controller​​ 中想直接回写字符串该怎样呢?

① 通过SpringMVC框架注入的 ​​response​​​ 对象,使用​​response.getWriter().print(“hello world”)​​​ 回写数据,此时不需要视图跳转,业务方法返回值为 ​​void​​。

@RequestMapping(value="/test6")
public void test6(HttpServletResponse response) throws IOException {
response.getWriter().println("Hello World!");
}

② 将需要回写的字符串直接返回,但此时需要通过 ​​@ResponseBody​​ 注解告知SpringMVC 框架,方法返回的字符串不是跳转是直接在 http 响应体中返回。

@RequestMapping(value="/test7")
@ResponseBody // 告知 SpringMVC 不进行视图跳转 直接进行数据响应
public String test7() {
return "hello Test7";
}

在异步项目中,客户端与服务器端往往要进行 ​​json​​​ 格式字符串交互,此时我们可以手动拼接 ​​json​​ 字符串返回。

@RequestMapping(value="/test8")
@ResponseBody
public String test8() {
return "{\"hello\" : \"Test7\"}";
}

上述方式手动拼接 ​​json​​​ 格式字符串的方式很麻烦,开发中往往要将复杂的 ​​java​​​ 对象转换成 ​​json​​​ 格式的字符串,我们可以使用 web 阶段学习过的 ​​json​​​ 转换工具 ​​jackson​​​ 进行转换,导入 ​​jackson​​ 坐标。

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>

通过 ​​jackson​​​ 转换 ​​json​​ 格式字符串,回写字符串。

@RequestMapping(value="/test9")
@ResponseBody
public String test9() throws JsonProcessingException {

User user = new User();
user.setUsername("lisi");
user.setAge(30);
// 使用 json 转换工具将对象转换成json格式字符串再返回
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(user);

return json;
}

2. 返回对象或集合

通过 ​​SpringMVC​​​ 帮助我们对对象或集合进行 ​​json​​​ 字符串的转换并回写,为处理器适配器配置消息转换参数,指定使用 ​​jackson​​​ 进行对象或集合的转换,因此需要在​​spring-mvc.xml​​ 中进行如下配置:

<!-- 配置处理器映射器 -->
<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(value="/test10")
@ResponseBody
public User test10() {

User user = new User();
user.setUsername("lisi2");
user.setAge(32);
return user;
}

在方法上添加 ​​@ResponseBody​​​ 就可以返回 ​​json​​ 格式的字符串,但是这样配置比较麻烦,配置的代码比较多,因此,我们可以使用 mvc 的注解驱动代替上述配置。

<!--mvc的注解驱动-->
<mvc:annotation-driven/>

在 SpringMVC 的各个组件中,​​处理器映射器​​​、​​处理器适配器​​​、​​视图解析器​​​ 称为 SpringMVC 的三大组件。使用 ​​<mvc:annotation-driven>​​​ 自动加载 RequestMappingHandlerMapping(处理映射器)和RequestMappingHandlerAdapter( 处 理 适 配 器 ),可用在 Spring-xml.xml 配置文件中使用 ​​<mvc:annotation-driven>​​​ 替代注解处理器和适配器的配置。
同时使用 ​​​<mvc:annotation-driven>​​ 默认底层就会集成 jackson 进行对象或集合的 json 格式字符串的转换。

SpringMVC 获得请求数据

获得请求参数

客户端请求参数的格式是:​​name=value&name=value… …​​ 服务器端要获得请求的参数,有时还需要进行数据的封装,SpringMVC可以接收如下类型的参数:

  • 基本类型参数
  • POJO类型参数
  • 数组类型参数
  • 集合类型参数

获得基本类型参数

Controller 中的业务方法的参数名称要与请求参数的 name 一致,参数值会自动映射匹配。

​http://localhost:8080/user/test11?username=zhangsan&age=12​

@RequestMapping(value="/test11")
@ResponseBody
public void test11(String username, int age) {

System.out.println(username);
System.out.println(age);
}

获得 POJO 类型参数

Controller 中的业务方法的 POJO 参数的属性名与请求参数的 name 一致,参数值会自动映射匹配。

​http://localhost:8080/user/test12?username=zhangsan&age=12​

public class User {

private String username;
private int age;

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", age=" + age +
'}';
}
}
@RequestMapping(value="/test12")
@ResponseBody
public void test12(User user) {
System.out.println(user);
}

获得数组类型参数

Controller中的业务方法数组名称与请求参数的name一致,参数值会自动映射匹配。

​http://localhost:8080/user/test13?strs=111&strs=222&strs=333​

@RequestMapping(value="/test13")
@ResponseBody
public void test13(String[] strs) {
System.out.println(Arrays.asList(strs));
}

获得集合类型参数

获得集合参数时,要将集合参数包装到一个 POJO 中才可以。

<form action="${pageContext.request.contextPath}/user/test14" method="post">
<%-- 表明是第几个 User 对象的 username age--%>
<input type="text" name="userList[0].username"> <br />
<input type="text" name="userList[0].age"> <br />
<input type="text" name="userList[1].username"> <br />
<input type="text" name="userList[1].age"> <br />
<input type="submit" value="提交">
</form>

​VO类​

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(value="/test14")
@ResponseBody
public void test14(VO vo) {
System.out.println(vo);
}

当使用 ajax 提交时,可以指定 contentType 为 json 形式,那么在方法参数位置使用​​@RequestBody​​ 可以直接接收集合数据而无需使用 POJO 进行包装。

<script src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
<script>
var userList = new Array();
userList.push({username: "zhangsan", age:17});
userList.push({username: "lisi", age:23});

$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/user/test15",
data: JSON.stringify(userList),
contentType: "application/json;charset=utf-8"
});
</script>

当使用 ajax 提交时,可以指定 contentType 为 json 形式,那么在方法参数位置使用 @RequestBody 可以直接接收集合数据而无需使用 POJO 进行包装。

@RequestMapping(value="/test15")
@ResponseBody
public void test15(@RequestBody List<User> userList) {
System.out.println(userList);
}

注意:通过谷歌开发者工具抓包发现,没有加载到 jquery 文件,原因是 SpringMVC 的前端控制器 DispatcherServlet 的 url-pattern 配置的是 ​​/​​,代表对所有的资源都进行过滤操作,我们可以通过以下两种方式指定放行静态资源:

• 在 ​​spring-mvc.xml​​​ 配置文件中指定放行的资源 ​​<mvc:resources mapping="/js/**" location="/js/"/>​​​ • 使用 ​​<mvc:default-servlet-handler/>​​ 标签

<!--    开放资源的访问-->
<!-- <mvc:resources mapping="/js/**" location="/js/" />-->

<mvc:default-servlet-handler />

请求数据乱码问题

当 post 请求时,数据会出现乱码,我们可以设置一个过滤器来进行编码的过滤。

<!--    配置全局过滤的filter,设置编码-->
<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>

参数绑定注解 @requestParam

当请求的参数名称与 Controller 的业务方法参数名称不一致时,就需要通过@RequestParam 注解显示的绑定。

<form action="${pageContext.request.contextPath}/user/test16" method="post">
<input type="text" name="name"><br>
<input type="submit" value="提交"><br>
</form>
@RequestMapping(value="/test16")
@ResponseBody
public void test16(@RequestParam(value="name", required = false, defaultValue = "lzjtu") String username) {
System.out.println(username);
}

注解 ​​@RequestParam​​ 还有如下参数可以使用:

  • value:与请求参数名称
  • required:此在指定的请求参数是否必须包括,默认是true,提交时如果没有此参数则报错
  • defaultValue:当没有指定请求参数时,则使用指定的默认值赋值

获得 Restful 风格的参数

Restful是一种软件架构风格、设计风格,而不是标准,只是提供了一组设计原则和约束条件。主要用于客户端和服务器交互类的软件,基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存机制等。

Restful风格的请求是使用“url+请求方式”表示一次请求目的的,HTTP 协议里面四个表示操作方式的动词如下:

  • GET:用于获取资源
  • POST:用于新建资源
  • PUT:用于更新资源
  • DELETE:用于删除资源

例如:

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

上述 url 地址 ​​/user/1​​​ 中的 ​​1​​​ 就是要获得的请求参数,在 SpringMVC 中可以使用占位符进行参数绑定。地址 ​​/user/1​​​ 可以写成 ​​/user/{id}​​​ ,占位符 ​​{id}​​​ 对应的就是 ​​1​​​ 的值。在业务方法中我们可以使用 ​​@PathVariable​​ 注解进行占位符的匹配获取工作。

localhost:8080/user/test17/zhangsan

四、SpringMVC的请求和响应_ssm_02

// localhost:8080/user/test17/zhangsan
@RequestMapping(value="/test17/{username}")
@ResponseBody
public void test17(@PathVariable("username") String username) {
System.out.println(username);
}

自定义类型转换器

• SpringMVC 默认已经提供了一些常用的类型转换器,例如客户端提交的字符串转换成 int 型进行参数设置。
• 但是不是所有的数据类型都提供了转换器,没有提供的就需要自定义转换器,例如:日期类型的数据就需要自定义转换器。

自定义类型转换器的开发步骤:
① 定义转换器类实现Converter接口
② 在配置文件中声明转换器
③ 在 ​​​<annotation-driven>​​ 中引用转换器

① 定义转换器类实现Converter接口

public class DateConvert implements Converter<String, Date> {

public Date convert(String dateStr) {
// 将日期字符串转换成日期对象 返回
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}

② 在配置文件中声明转换器

<!--    声明转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.xxx.convert.DateConvert"></bean>
</list>
</property>
</bean>

③ 在 ​​<annotation-driven>​​ 中引用转换器

<mvc:annotation-driven conversion-service="conversionService"/>
@RequestMapping(value="/test18")
@ResponseBody
public void test18(Date date) {
System.out.println(date);
}

获得Servlet相关API

SpringMVC支持使用原始ServletAPI对象作为控制器方法的参数进行注入,常用的对象如下:

  • HttpServletRequest
  • HttpServletResponse
  • HttpSession
@RequestMapping(value="/test19")
@ResponseBody
public void test19(HttpServletRequest req, HttpServletResponse resp, HttpSession session) {
System.out.println(req);
System.out.println(resp);
System.out.println(session);
}

获得请求头

1. @RequestHeader

使用@RequestHeader可以获得请求头信息,相当于web阶段学习的request.getHeader(name)

@RequestHeader注解的属性如下:

  • value:请求头的名称
  • required:是否必须携带此请求头
@RequestMapping(value="/test20")
@ResponseBody
public void test20(@RequestHeader(value = "User-Agent", required = false) String user_agent) {
System.out.println(user_agent);
}

2. @CookieValue

使用@CookieValue可以获得指定Cookie的值

@CookieValue注解的属性如下:

  • value:指定cookie的名称
  • required:是否必须携带此cookie
@RequestMapping(value="/test21")
@ResponseBody
public void test21(@CookieValue(value = "JSESSIONID") String jsessionId) {
System.out.println(jsessionId);
}

文件上传

1. 文件上传客户端三要素

  • 表单项type=“file”
  • 表单的提交方式是post
  • 表单的enctype属性是多部分表单形式,及enctype=“multipart/form-data”

四、SpringMVC的请求和响应_spring_03

2. 文件上传原理

  • 当form表单修改为多部分表单时,request.getParameter()将失效。
  • enctype=“application/x-www-form-urlencoded”时,form表单的正文内容格式是:key=value&key=value&key=value
  • 当form表单的enctype取值为Mutilpart/form-data时,请求正文内容就变成多部分形式:

四、SpringMVC的请求和响应_java_04

单文件上传步骤

① 导入fileupload和io坐标
② 配置文件上传解析器
③ 编写文件上传代码

① 导入fileupload和io坐标

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

② 配置文件上传解析器

<!--    配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
<property name="maxUploadSize" value="500000" />
</bean>

③ 编写文件上传代码

@RequestMapping(value="/test22")
@ResponseBody
public void test22(String username, MultipartFile uploadFile1, MultipartFile uploadFile2) throws IOException {

String originalFilename1 = uploadFile1.getOriginalFilename();
uploadFile1.transferTo(new File("/home/sweetheart/Desktop/upload/" + originalFilename1));
String originalFilename2 = uploadFile2.getOriginalFilename();
uploadFile2.transferTo(new File("/home/sweetheart/Desktop/upload/" + originalFilename2));
}

多文件上传实现

多文件上传,只需要将页面修改为多个文件上传项,将方法参数MultipartFile类型修改为 MultipartFile[] 即可

<form action="${pageContext.request.contextPath}/user/test23" method="post" enctype="multipart/form-data">
名称:<input type="text" name="username"><br />
文件1:<input type="file" name="uploadFile"><br />
文件2:<input type="file" name="uploadFile"><br />
<input type="submit" value="提交">
</form>
@RequestMapping(value="/test23")
@ResponseBody
public void test23(String username, MultipartFile[] uploadFile) throws IOException {

System.out.println(username);

for(MultipartFile multipartFile: uploadFile){
String originalFilename = multipartFile.getOriginalFilename();
multipartFile.transferTo(new File("/home/sweetheart/Desktop/upload/" + originalFilename));
}
}