1、转发和重定向
1.1、转发
1.1.1、返回 String
controller:
@Controller
public class ViewController {
@RequestMapping("view01")
public String view01(Model model){
model.addAttribute("message", "hello view!");
// 逻辑视图名
return "hello";
}
}
hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${message}
</body>
</html>
1.1.2、返回 ModelAndView
@Controller
public class ViewController {
@RequestMapping("view02")
public ModelAndView view02(){
// 实例化对象
ModelAndView view = new ModelAndView();
// 存储数据
view.addObject("message", "hello ModelAndView!");
// 指定视图
view.setViewName("hello");
// 逻辑视图名
return view;
}
}
1.1.3、实例化 ModelAndView 时指定视图
@Controller
public class ViewController {
@RequestMapping("view03")
public ModelAndView view03(){
// 实例化对象
ModelAndView view = new ModelAndView("hello");
// 存储数据
view.addObject("message", "hello ModelAndView!");
// 逻辑视图名
return view;
}
}
1.1.4、forward:视图解析器不进行解析,需添加后缀名
@Controller
public class ViewController {
@RequestMapping("view04")
public ModelAndView view04(){
// 实例化对象
ModelAndView view = new ModelAndView("forward:hello.jsp");
// 存储数据
view.addObject("message", "hello ModelAndView!");
// 逻辑视图名
return view;
}
}
@Controller
public class ViewController {
@RequestMapping("view05")
public ModelAndView view05(){
// 实例化对象
ModelAndView view = new ModelAndView();
// 存储数据
view.addObject("message", "hello ModelAndView!");
view.setViewName("forward:hello.jsp");
// 逻辑视图名
return view;
}
}
1.2、重定向
1.2.1、redirect:视图解析器不进行解析,需添加后缀名,却无法正常获取数据
@Controller
public class ViewController {
@RequestMapping("view06")
public String view06(Model model){
model.addAttribute("message", "hello redirect!");
return "redirect:hello.jsp";
}
}
1.2.2、redirect 重定向获取数据
@Controller
public class ViewController {
@RequestMapping("view07")
public ModelAndView view07(){
ModelAndView view = new ModelAndView("redirect:hello.jsp?str=yangzhiqiang");
return view;
}
}
hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${message}
${param.str}
</body>
</html>
1.2.3、redirect + session 重定向获取数据
@Controller
public class ViewController {
@RequestMapping("view08")
public ModelAndView view08(HttpSession session){
session.setAttribute("message", "hello session");
ModelAndView view = new ModelAndView("redirect:hello.jsp");
return view;
}
}
2、JSON 数据开发
2.1、添加环境
添加依赖
<!-- 添加 json 依赖 jar 包 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.10.0</version>
</dependency>
springmvc.xml 文件中添加 json 解析器
<!-- 注解的驱动 -->
<mvc:annotation-driven>
<!-- json 解析器 -->
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
2.2、@ResponseBody:将响应数据转为 json 格式
@Controller
public class JsonController {
@RequestMapping("Json01")
@ResponseBody
public User say01(){
// 实例化对象
User user = new User();
user.setUserid(1001);
user.setUsername("zhangsan");
user.setAge(20);
return user;
}
}
@Controller
public class JsonController {
@RequestMapping("Json02")
@ResponseBody
public List<User> say02(){
// 实例化对象
List<User> list = new ArrayList<User>();
User user1 = new User();
user1.setUserid(1001);
user1.setUsername("zhangsan");
user1.setAge(20);
User user2 = new User();
user2.setUserid(1002);
user1.setUsername("lisi");
user1.setAge(18);
list.add(user1);
list.add(user2);
return list;
}
}
2.3、@RequestBody:将请求实体中符合 json 格式的字符串,转为 javaBean 的属性值
@Controller
public class JsonController {
@RequestMapping("Json03")
@ResponseBody
public User say03(@RequestBody User user){
System.out.println(user);
return user;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<script>
$(function(){
$("#btn").click(function(){
$.ajax({
type : "post",
url : "Json03",
data : '{"userid" : 1001, "username" : "zhangsan", "password" : "123456"}',
contentType : "application/json;charset=utf-8",
dataType : "json",
success : function (message){
alert(message);
}
});
});
});
</script>
<button id="btn">发送数据</button>
</body>
</html>
3、拦截器
3.1、作用
拦截器的主要作用是拦截用户的请求并进行相应的处理。比如通过它来进行权限验证,或者是来判断用户是否登陆等操作
3.2、实现
3.2.1、实现 HandlerInterceptor 接口
-
接口实现
public class MyInterceptor01 implements HandlerInterceptor {
/**
* 在目标 Handler (方法)执行前执行
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// true:执行 handler 方法
// false:阻止目标 handler 方法执行
System.out.println("执行目标 handler 方法之前执行 preHandle()方法");
// 放行
return true;
}
/**
* 在目标 Handler (方法)执行后,视图生成前执行
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("执行目标 handler 方法之后,视图生成之前执行 postHandle()方法");
}
/**
* 在目标 Handler (方法)执行后,视图生成后执行
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("执行目标 handler 方法之后,视图生成之后执行 afterCompletion()方法");
}
}
- spring 配置文件添加配置
<!-- 拦截器 方式一 -->
<mvc:interceptors>
<bean class="com.yjxxt.interceptor.MyInterceptor01"></bean>
</mvc:interceptors>
<!-- 拦截器 方式二 可配置多个 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 拦截的路径 -->
<mvc:mapping path="/**"/>
<!-- 放行的路径 -->
<mvc:exclude-mapping path="/js/**"/>
<mvc:exclude-mapping path="/css/**"/>
<mvc:exclude-mapping path="/images/**"/>
<!-- 目标拦截器对象 -->
<bean class="com.yjxxt.interceptor.MyInterceptor01"></bean>
</mvc:interceptor>
</mvc:interceptors>
3.2.2、继承 HandlerInterceptorAdapter (实际上最终还是 HandlerInterceptor 接口实现)
public class MyInterceptor01 implements HandlerInterceptor {
/**
* 在目标 Handler (方法)执行前执行
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// true:执行 handler 方法
// false:阻止目标 handler 方法执行
System.out.println("执行目标 handler 方法之前执行 preHandle()方法");
// 放行
return true;
}
/**
* 在目标 Handler (方法)执行后,视图生成前执行
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("执行目标 handler 方法之后,视图生成之前执行 postHandle()方法");
}
/**
* 在目标 Handler (方法)执行后,视图生成后执行
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("执行目标 handler 方法之后,视图生成之后执行 afterCompletion()方法");
}
}
3.2.3、登录案例
users 实体类:
public class Users {
private String username;
private String password;
public Users() {}
public Users(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Users{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
login.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="login" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
LoginInterceptor:
public class LoginInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 放行登录页面
String uri = request.getRequestURI();
if (uri.contains("login")) {
return true;
}
// 获取 session
Users temp = (Users) request.getSession().getAttribute("users");
if (temp != null) {
// 放行
return true;
}
// 跳转登录页面
request.getRequestDispatcher("login.jsp").forward(request, response);
// 拦截
return false;
}
}
配置拦截器:
<mvc:interceptors>
<mvc:interceptor>
<!-- 拦截 -->
<mvc:mapping path="/**"/>
<!-- 放行 -->
<mvc:exclude-mapping path="/js/**"/>
<!-- 目标拦截器 -->
<bean class="com.yjxxt.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
controller:
@Controller
public class HelloController {
@RequestMapping("login")
public String login(Users users, HttpSession session){
// 判断
if ("YANG".equals(users.getUsername()) && "123456".equals(users.getPassword())){
// 登陆成功
session.setAttribute("users", users);
return "index";
}
else {
// 登录失败
return "forward:login.jsp";
}
}
}
4、文件上传
4.1、环境配置
4.1.1、添加依赖
<!-- 添加 commons-fileupload 依赖 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
4.1.2、添加配置
<!-- 文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 允许文件上传的最大尺寸 -->
<property name="maxUploadSize">
<value>104857600</value>
</property>
<!--
设置文件放入临时文件夹的最大大小限制。
此值是阈值,低于此值,则保存在内存中,如高于此值,则生成硬盘上的临时文件。
-->
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
4.2、上传单个文件
fileUpload.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
上传:<input type="file" name="myFile">
<input type="submit" value="上传">
</form>
</body>
</html>
controller:
@Controller
public class HelloController {
@RequestMapping("upload")
public String upload(MultipartFile myFile, HttpServletRequest req, HttpServletResponse resp) throws IOException {
// 判断文件是否存在
if (!myFile.isEmpty()) {
// 获取文件名称
String fileName = myFile.getOriginalFilename();
// 获取文件的后缀名
String suffix = fileName.substring(fileName.lastIndexOf("."));
// 构建文件前缀
Long prefix = System.currentTimeMillis();
// 构建新的文件名
fileName = prefix + suffix;
// 上传的路径
String path = req.getServletContext().getRealPath("/");
File fileDir = new File(path + "/upload");
if (!fileDir.exists()) {
fileDir.mkdir();
}
// 构建文件
File file = new File(fileDir, fileName);
// 构建输入流
myFile.transferTo(file);
// 上传成功
req.setAttribute("message", "上传成功!!!");
}
else {
System.out.println("请选择文件");
req.setAttribute("message", "文件不存在!!!");
}
return "success";
}
}
success.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
上传成功!!!
</body>
</html>