Spring MVCE的数据响应方式
页面跳转-直接返回字符串
<!--配置内部资源视图解析器-->
<!-- 只需要写名字就行了,会自动拼接后缀-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- /jsp/success.jsp -->
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
页面跳转-返回ModelAndView对象(模型和视图对象)
@RequestMapping(value="/quick2")
public ModelAndView save2(){
/*
Model:模型 作用封装数据
View:视图 作用展示数据
*/
ModelAndView modelAndView = new ModelAndView();
//设置模型数据
modelAndView.addObject("username","itcast");
//设置视图名称
modelAndView.setViewName("success");
return modelAndView;
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Success! ${username}</h1>
</body>
</html>
返回ModelAndView对象的其他形式
@RequestMapping(value="/quick4")
public String save4(Model model){
//将model与view拆开,view通过return返回,即success.jsp,model定义在下方
model.addAttribute("username","博学谷");//键值对形式
return "success";
}
@RequestMapping(value="/quick3")
public ModelAndView save3(ModelAndView modelAndView){
//传入实参modelAndView,所以可以在下方直接定义你想要的返回值
modelAndView.addObject("username","itheima");
modelAndView.setViewName("success");
return modelAndView;
}
返回ModelAndView对象往Request域当中存数据
@RequestMapping(value="/quick4")
public String save4(Model model){
//将model与view拆开,view通过return返回,即success.jsp,model定义在下方
model.addAttribute("username","博学谷");//键值对形式
return "success";
回写数据-直接返回字符串
@RequestMapping(value="/quick6")
public void save6(HttpServletResponse response) throws IOException {
//response回写
response.getWriter().print("hello itcast");
}
@RequestMapping(value="/quick7")
@ResponseBody //告知SpringMVC框架 不进行视图跳转 与ModelAndView形式区分开 直接进行数据响应
public String save7() throws IOException {
return "hello itheima";
}
回写数据-直接返回json格式字符串
直接转换
@RequestMapping(value="/quick8")
@ResponseBody
public String save8() throws IOException {
return "{\"username\":\"zhangsan\",\"age\":18}";
}
使用json转换工具-先导包
<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>
@RequestMapping(value="/quick9")
@ResponseBody
public String save9() throws IOException {
User user = new User();
user.setUsername("lisi");
user.setAge(30);
//使用json的转换工具将对象转换成json格式字符串在返回
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(user);
return json;
}
回写数据-返回对象或集合
主要是注入MappingJackson2HttpMessageConverter转换器
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</list>
</property>
</bean>
@RequestMapping(value="/quick10")
@ResponseBody
//期望SpringMVC自动将User转换成json格式的字符串
public User save10() throws IOException {
User user = new User();
user.setUsername("lisi2");
user.setAge(32);
return user;
}
先添加mvc的命名空间,以后这个是必写的
xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
<!--mvc的注解驱动-->
<mvc:annotation-driven conversion-service="conversionService"/>
SpringMVC获得请求数据
基本简单参数
@RequestMapping(value="/quick11")
@ResponseBody
public void save11(String username,int age) throws IOException {
System.out.println(username);
System.out.println(age);
}
POJO类型参数
@RequestMapping(value="/quick12")
@ResponseBody
public void save12(User user) throws IOException {
//传入一个user类,springmvc会自动给你封装
System.out.println(user);
}
数组类型参数
@RequestMapping(value="/quick13")
@ResponseBody
public void save13(String[] strs) throws IOException {
System.out.println(Arrays.asList(strs));
}
集合类型数据
@RequestMapping(value="/quick14")
@ResponseBody
public void save14(VO vo) throws IOException {
System.out.println(vo);
}
package com.itheima.domain;
import java.util.List;
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 +
'}';
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/quick14" 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>
</body>
</html>
可以直接收集数据而无需POJO包装(重要)使用jquery
D:\code\第三方扩展包\springmvc-ajax
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
<script>
var userList = new Array();
userList.push({username:"zhangsan",age:18});
userList.push({username:"lisi",age:28});
$.ajax({
type:"POST",
url:"${pageContext.request.contextPath}/user/quick15",
data:JSON.stringify(userList),
contentType:"application/json;charset=utf-8"
});
</script>
</head>
<body>
</body>
</html>
<!--开放资源的访问-->
<!--<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/img/**" location="/img/"/>-->
或者
<mvc:default-servlet-handler/>
@RequestMapping(value="/quick15")
@ResponseBody
public void save15(@RequestBody List<User> userList) throws IOException {
System.out.println(userList);
}
请求数据乱码问题(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>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
参数绑定注解@requestParam
数据转换 将浏览器传递的name 转换成username
@RequestMapping(value="/quick16")
@ResponseBody
public void save16(@RequestParam(value="name",required = false,defaultValue = "itcast") String username) throws IOException {
System.out.println(username);
}
@RequestMapping(value="/quick16")
@ResponseBody
public void save16(@RequestParam(value="name",required = false,defaultValue = "itcast") String username) throws IOException {
System.out.println(username);
}
获取Restful风格的参数
// localhost:8080/user/quick17/zhangsan
@RequestMapping(value="/quick17/{name}")
@ResponseBody
public void save17(@PathVariable(value="name") String username) throws IOException {
System.out.println(username);
}
自定义类型转换器
客户端请求的任何数据到服务端都会变成字符串
springmvc已经默认提供了一些类型转换器
例如:在网页中发送2018-12-21格式的数据就无法正确响应
package com.itheima.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 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.itheima.converter.DateConverter"></bean>
</list>
</property>
</bean>
<!--mvc的注解驱动-->
<mvc:annotation-driven conversion-service="conversionService"/>
@RequestMapping(value="/quick18")
@ResponseBody
public void save18(Date date) throws IOException {
System.out.println(date);
}
获得Servlet相关API
@RequestMapping(value="/quick19")
@ResponseBody
public void save19(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
System.out.println(request);
System.out.println(response);
System.out.println(session);
}
SpringMVC获得请求数据-获得请求头
例如:获取User-Agent
@RequestMapping(value="/quick20")
@ResponseBody
public void save20(@RequestHeader(value = "User-Agent",required = false) String user_agent) throws IOException {
System.out.println(user_agent);
}
@RequestMapping(value="/quick21")
@ResponseBody
public void save21(@CookieValue(value = "JSESSIONID") String jsessionId) throws IOException {
System.out.println(jsessionId);
}
SpringMVC获得请求数据-文件上传(客户端)
<form action="${pageContext.request.contextPath}/user/quick22" method="post" enctype="multipart/form-data">
名称<input type="text" name="username"><br/>
文件1<input type="file" name="uploadFile"><br/>
文件2<input type="file" name="uploadFile2"><br/>
<input type="submit" value="提交">
</form>
文件上传原理
单文件上传步骤(服务端)
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>
<!--配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UYF-8"/>
<property name="maxUploadSize" value="500000"/>
</bean>
<form action="${pageContext.request.contextPath}/user/quick23" method="post" enctype="multipart/form-data">
名称<input type="text" name="username"><br/>
文件<input type="file" name="uploadFile"><br/>
文件2<input type="file" name="uploadFile2"><br/>
<input type="submit" value="提交">
</form>
@RequestMapping(value="/quick22")
@ResponseBody
public void save22(String username, MultipartFile uploadFile,MultipartFile uploadFile2) throws IOException {
System.out.println(username);
//获得上传文件的名称
String originalFilename = uploadFile.getOriginalFilename();
uploadFile.transferTo(new File("C:\\upload\\"+originalFilename));
String originalFilename2 = uploadFile2.getOriginalFilename();
uploadFile2.transferTo(new File("C:\\upload\\"+originalFilename2));
}
多文件上传实现
<form action="${pageContext.request.contextPath}/user/quick23" 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="/quick23")
@ResponseBody
public void save23(String username, MultipartFile[] uploadFile) throws IOException {
System.out.println(username);
for (MultipartFile multipartFile : uploadFile) {
String originalFilename = multipartFile.getOriginalFilename();
multipartFile.transferTo(new File("C:\\upload\\"+originalFilename));
}
}