1. springmvc简介
2. springmvc开发步骤
springmvc-servlet.xml
springmvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springmvc-servlet.xml
springmvc
/
@Controller
public class PrintDateController {
@RequestMapping(value="/printDate")
public String printDate(HttpServletResponse response) throws IOException{
response.getWriter().println(new Date());
return null;
}
}
3. controller方法的返回值类型
controller方法的返回值类型包括:
1.ModelAndView
2.String
3.void
@Controller
public class MethodReturnTypeController {
//类型1:返回为对象类型
@RequestMapping(value="/modelAndView")
public ModelAndView modelAndView(){
//创建ModeAndView对象
ModelAndView mv=new ModelAndView();
//ModeAndView的存储范围和request一样
mv.addObject("hill", "hello");
//设置逻辑视图名 真正的视图名://WEB-INF/jsp/hello.jsp
mv.setViewName("hello");
return mv;
}
//类型2:返回为String类型
@RequestMapping(value="/returnStringForWard")
public String returnStringForWard(){
//return "forward://WEB-INF/jsp/hello.jsp";
return "forward:index.jsp";
}
//当注解中只有一个value值,可以直接写url地址值
@RequestMapping("/returnStringRedirect")
public String returnStringRedirect(){
return "redirect:index.jsp";
}
@RequestMapping("/returnStringViewName")
public String returnStringViewName(){
//hello是逻辑视图,真正视图是://WEB-INF/jsp/hello.jsp
return "hello";
}
//类型2:返回为void类型
@RequestMapping("/returnVoidForWard")
public void returnVoidForWard(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
request.getRequestDispatcher("index.jsp").forward(request,response);
}
@RequestMapping("/returnVoidRedirect")
public void returnVoidRedirect(HttpServletResponse response) throws IOException{
response.sendRedirect("index.jsp");
}
@RequestMapping("/returnVoidJson")
public void returnVoidJson(HttpServletResponse response) throws IOException{
//创建用户对象
User user = new User();
user.setId(1);
user.setUsername("admin");
user.setPassword("admin");
response.getWriter().println(JSONObject.fromObject(user).toString());
}
}
4. 参数绑定
参数绑定指的是将请求参数中的值绑定到controller方法参数的过程。
参数绑定支持的数据类型包括:
默认数据类型:HttpServletRequest、HttpServletResponse、HttpSession、
Model/ModelMap:ModelMap是Model接口的实现类
Model:模型,保存数据的对象就是Model,可以将Model当成一个和request session一样的容器
public String paramBinding(String code, String name, Double price, Integer count, Integer status,String description){
System.out.println(code + "\t" + name + "\t" + price + "\t" + count + "\t" + status + "\t" + description);
return null;
}
@RequestMapping("/paramBindingDefaultType")
public String paramBindingDefaultType(HttpServletRequest request,HttpServletResponse response,HttpSession session,Model model){
String code = request.getParameter("code");
String name = request.getParameter("name");
System.out.println("code"+"\t"+"name");
model.addAttribute("code", code);
model.addAttribute("name", name);
return "forward:index.jsp";
}
@RequestMapping("/paramBindingPackType")
public String paramBindingPackType(Product product,Model model){
model.addAttribute("product", product);
return "forward:index.jsp";
}
@RequestMapping("/paramBindingPackObjectType")
public String paramBindingPackObjectType(Order order,Model model){
model.addAttribute("order", order);
return "forward:index.jsp";
}
@RequestMapping("/paramBindingArrayType")
public String paramBindingArrayType(int [] ids){ //ids要和表单的name属性值保持一致
for (int i : ids) {
System.out.println(i);
}
return "forward:index.jsp";
}
batchDeleteUser.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">批量删除用户信息</h1>
<form action="paramBindingArrayType" method="post">
<table border="1px" width="300px" height="400px" style="text-align: center;" align="center">
<tr>
<td>全选</td>
<th>用户ID</th>
<th>用户名</th>
<th>用户密码</th>
</tr>
<tr>
<td><input type="checkbox" name="ids" value="1"/></td>
<td>1</td>
<td>张三</td>
<td>admin</td>
</tr>
<tr>
<td> <input type="checkbox" name="ids" value="2"/></td>
<td>2</td>
<td>李四</td>
<td>admin4</td>
</tr>
<tr>
<td> <input type="checkbox" name="ids" value="3"/></td>
<td>3</td>
<td>王五</td>
<td>wangw</td>
</tr>
<tr>
<td> <input type="checkbox" name="ids" value="4"/></td>
<td>4</td>
<td>赵6</td>
<td>zhao6</td>
</tr>
<tr>
<td colspan="4"><input type="submit" value="批量删除"/></td>
</tr>
</table>
</form>
</body>
</html>
package com.xx.entity;
import java.util.List;
public class UserVO {
private List<User> users;
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public UserVO() {
super();
// TODO Auto-generated constructor stub
}
}
com.xx.controller:
@RequestMapping("/paramBindingListType")
public String paramBindingListType(UserVO userVO){
List<User> users = userVO.getUsers();
for (User user : users) {
System.out.println(user.getId()+"\t"+user.getUsername()+"\t"+user.getPassword());
}
return "forward:index.jsp";
}
5. 中文乱码处理
在web.xml文件下:
<!-- 配置处理中文乱码的过滤器 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*
6. 静态资源文件处理
静态资源包括:js css image等
要访问静态资源需要在web.xml配置
<!-- 处理静态资源 -->
<mvc:default-servlet-handler />
7. 文件上传
@RequestMapping("/upload")
public String upload(MultipartFile file) throws IllegalStateException, IOException{
//获取上传文件的名称
String name =file.getOriginalFilename();
String fileName = String.valueOf(UUID.randomUUID());
String sufffix = "";
System.out.println(name);
File descFile = new File("E:/image/"+fileName+sufffix);
//将上传文件存入目标文件
file.transferTo(descFile);
return "forward:success.jsp";
}
upload.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
8. @RequestBody @ResponseBody
注意:引入相应jar包
@RequestBody使用在controller方法的参数上。
作用是将json格式的数据转成java对象
i) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上;
ii) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。
com.xx.controller包下:
@RequestMapping(value="/requestBody")
public String requestBody(@RequestBody User user, Model model) {
System.out.println(user.getUsername()+"\t"+user.getPassword());
model.addAttribute("user", user);
return "forward:index.jsp";
com.xx.entity包下有user实体类定义
index.jsp
${user.id} ${user.username} ${user.password}
@ResponseBody使用在方法的声明上
作用:将java对象转成Json个数数据
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区
com.xx.controller包下:
@RequestMapping("/responseBody")
@ResponseBody
public User responseBody() {
User user = new User();
user.setId(111);
user.setUsername("name1");
user.setPassword("123465");
return user;
}
注意:需要在/WebContent/WEB-INF/jsp/responseBody.jsp 写responseBody.jsp
9.@RequestParam
@RequesetParam是用在controller方法参数上,
作用是解决请求参数的名称和controller方法的参数名称不一致时,
参数绑定的问题。
/**
* @RequestParam name属性表示页面传递的请求参数名称
* value属性表示页面传递的请求参数的别名
* 使用name和value效果一样
* name属性和value属性的值必须和页面上传递的请求参数的名称一致。
* defaultValue:表示请求参数的默认值
* required表示请求参数是否必须,true 表示必须(必须传递=) false表示不必须(可选)
* @param username1
* @param password
* @return
*/
@RequestMapping("/login")
public String login(@RequestParam(value="username",defaultValue="admin",required=false) String username1, String password) {
System.out.println(username1+"\t"+password);
if (username1.equals("admin") && password.equals("admin")) {
return "forward:index.jsp";
} else {
return "forward:login.jsp";
}
}
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">登录页面</h1>
<form action="requestBody" method="post" >
<table border="1px" width="350px" height="200px" align="center" style="text-align: center;">
<tr>
<td>用户名:</td>
<td><input type="text" name="id" size="25"/></td>
</tr>
<tr>
<td>用户名:</td>
<td><input type="text" name="username" size="25"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password" size="25"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="登录"/>
</td>
</tr>
</table>
</form>
</body>
</html>
10.@PathVariable
PathVariable路径变量,支持RESTFul风格的请求。
可以将参数直接传递在URL地址的编程风格叫RESTFul风格
@RequestMapping("/login2/{username}/{password}")
public void login2(@PathVariable String username,@PathVariable String password,HttpServletResponse response) throws IOException{
response.getWriter().println("username:"+username+"---password:"+password);
}
打开浏览器输入:http://localhost/SpringMVC_002/login2/admin/admin
浏览器显示:username:admin—password:admin
/**
* @PathVariable name属性表示请求路径中{}中请求参数的名称
* value属性表示请求路径中{}中请求参数的别名
* name和value属性的值必须和请求路径中{}中变量名一致
* @param username1
* @param password
* @param response
* @throws IOException
*/
@RequestMapping(value={"/login2/{username}/{password}","/login2/{username}","/login2//{password}"})
public void login2(@PathVariable(name="username",value="username",required=false) String username1,@PathVariable(name="password",required=true) String password,HttpServletResponse response) throws IOException{
response.getWriter().print("username:"+username1+"\t"+"password:"+password);
}
11. 拦截器
过滤器和拦截器的区别:
①拦截器是基于java的反射机制的(拦截器–>处理器(Controller)),而过滤器是基于函数回调。doFilter()
②拦截器不依赖与servlet容器,过滤器依赖与servlet容器。
③拦截器只能对非.jsp的请求起作用,而过滤器则可以对几乎所有的请求起作用(包括.jsp)。
com.xx.util包下:
public class CheckLoginInterceptor implements HandlerInterceptor {
/**
* arg0:表示请求对象
* arg1:表示响应对象
* arg2:表示处理器对象(Handle)
* preHandle:在请求到达目标资源之前先执行
* return true:表示拦截器继续向下执行,如果没有下一个拦截器那么就可以访问目标资源
* return false:表示程序终止,返回结果
* */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("preHandle...");
return true;
}
/**
* postHandle方法是在controller方法执行后在视图解析之前(View Resolver)之前
* 在postHandle方法中可以对模型视图进行修改
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
System.out.println("postHandle...");
}
/**
* 在请求执行之后,并且在视图渲染之后调用该方法,在该方法中一般进行删除临时文件、关闭资源等操作
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("afterComletion...");
}
}
修改springmvc-servlet.xml配置文件:
<!-- 配置拦截器 -->
<mvc:interceptors>
<!-- 配置全局拦截器 -->
<bean class="com.xx.util.CheckLoginInterceptor"></bean>
</mvc:interceptors>
com.xx.controller包下:
@Controller
public class LoginController {
@RequestMapping("/myLogin")
public String myLogin(String username,String password) {
System.out.println("myLogin...");
if (username.equals("admin") && password.equals("admin")) {
return "forward:index.jsp";
} else {
return "forward:login.jsp";
}
}
}
输出:
preHandle…
myLogin…
postHandle…
afterComletion…
com.xx.util包下:
/**
* postHandle方法是在controller方法执行后在视图解析之前(View Resolver)之前
* 在postHandle方法中可以对模型视图进行修改
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
ModelMap modelMap=modelAndView.getModelMap();
User user=(User) modelMap.get("user");
System.out.println("postHandle..."+user.getUsername()+"---"+user.getPassword());
System.out.println("postHandle...");
}
com.xx.controller包下:
@Controller
public class LoginController {
@RequestMapping("/myLogin")
public String myLogin(User user,Model model) {
System.out.println("myLogin...");
if (user.getUsername().equals("admin") && user.getPassword().equals("admin")) {
model.addAttribute("user", user);
return "forward:index.jsp";
} else {
return "forward:login.jsp";
}
}
}
输出:
preHandle…
myLogin…
postHandle…admin—admin
postHandle…
afterComletion…
springmvc拦截器的使用参考网址:https://blog.csdn.net/kingmax54212008/article/details/79333878
https://www.cnblogs.com/jianjianyang/p/5009457.html
过滤器不过滤css js images等静态资源文件的方式,参考网址:
https://www.jb51.net/article/103704.htm
注意
Servlet:Filter拦截请求 (css js img)
Springmvc:Interceptor 拦截请求(不包含css js img)
自定义拦截器:1.实现HandlerInterceptor 2.WebR equestIntercepter
拦截器的执行顺序和springmvc-servlet.xml配置文件中的配置文件的顺序有关
全局拦截器的preHandle–true->局部拦截器的preHandle—》局部拦截器的postHandle—》全局拦截器的postHandle—》局部拦截器的afterComletion—》全局拦截器的afterCompletion
12. 异常处理(了解)
在springmvc异常处理2种方式:
@ExceptionHandler
public String handleException(Exception exception,Model model){
model.addAttribute("error_msg", exception.getMessage());
return "forward:error.jsp";
}
2.全局异常处理
@ControllerAdvice
public class TestGloableExceptionHandlerController {
@ExceptionHandler
public String handleException(Exception exception,Model model){
System.out.println("exception:"+exception.getMessage());
model.addAttribute("error_msg", exception.getMessage());
return "forward:error.jsp";
}
}
404、500错误处理,在web.xml文件增加404 500等错误处理配置:
404
/404.jsp
500
/500.jsp