一、SpringMVC数据响应:
1)字符串响应:
jsp
<a href="/user/test" >testString</a>
Controller
@RequestMapping("/test")
public String testUser(Model model){
System.out.println("testUser。。。");
User user = new User();
user.setUsername("张三");
user.setAge(55);
user.setMoney(999d);
model.addAttribute("user",user);
return "success";
}
2)void响应:
jsp:
<a href="/user/testVoid" >testVoid</a>
Controller:
@RequestMapping("/testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("testVoid。。。");
//请求转发
//request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
//重定向
//response.sendRedirect(request.getContextPath()+"/index.jsp");
//直接响应
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("你好啊...");
}
3)ModelAndView响应:
存到了request域中
访问jsp
<a href="/user/testModelAndView" >testModelAndView</a>
Controller
@RequestMapping("/testModelAndView")
public ModelAndView testUser(){
System.out.println("testModelAndView。。。");
ModelAndView mv = new ModelAndView();
User user = new User();
user.setUsername("李四");
user.setAge(11);
user.setMoney(222d);
mv.addObject("user",user);
mv.setViewName("success");
return mv;
}
结果jsp
${requestScope.username}
4)关键字forward/redirect转发:
jsp
<a href="/user/testForwardOrRedirect" >测试关键字转发/重定向</a>
Controller
@RequestMapping("/testForwardOrRedirect")
public String testForwardOrRedirect(){
System.out.println("testForwardOrRedirect。。。");
//return "forward:/WEB-INF/pages/success.jsp";
return "redirect:/index.jsp";
}
5)ResponseBody注解响应json数据
作用: 该注解用于将Controller的方法返回的对象,通过HttpMessageConverter接口转换为指定格式的数据如:json,xml等,通过Response响应给客户端
Springmvc默认用MappingJacksonHttpMessageConverter对json数据进行转换,需要加入jackson的包。
<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-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
jsp
<script src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btn").click(function () {
$.ajax({
url:"user/testAjax",
dataType:"json",
contentType:"application/json;charset=UTF-8",
data:'{"username":"王丽丽","age":18,"money":200}',
type:"post",
success:function (data) {
alert(data.username+"---"+data.money);
}
});
});
});
</script>
Controller
@RequestMapping("/testAjax")
public @ResponseBody User testAjax(@RequestBody User user){
System.out.println("testAjax。。。");
System.out.println(user);
user.setUsername("周XX");
user.setMoney(99999d);
return user;
}
二、文件上传:
需要导入依赖:
<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.4</version>
</dependency>
1)传统方式上传文件:
jsp
<form action="/fileupload/upload1" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"><br />
<input type="submit" value="上传">
</form>
Controller:
/**
* 传统方式上传文件
* @return
*/
@RequestMapping("upload1")
public String testUpload1(HttpServletRequest request){
System.out.println("upload1");
//上传的路径
String path = request.getSession().getServletContext().getRealPath("/uploads/");
//判断文件夹是否存在
File file = new File(path);
if(!file.exists()){
//新建文件夹
file.mkdirs();
}
//解析request对象,获取上传文件项
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//解析request
List<FileItem> items = null;
try {
items = upload.parseRequest(request);
//遍历items
for (FileItem item:items) {
//进行判断,当前item对象是否是上传文件项
if(item.isFormField()){
//普通表单项
}else{
//上传文件项
//获取上传文件的名称
String fileName = item.getName();
String uuid = UUID.randomUUID().toString().replace("-", "");
fileName = uuid+"_"+fileName;
//上传文件
item.write(new File(path,fileName));
//删除临时文件
item.delete();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return "success2";
}
配置文件解析器
在springmvc中配置:
<!-- 配置文件解析器 : id的值是固定的-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize"> <value>5242880</value> </property>
</bean>
2)spingmvc方式上传文件:
jsp
<form action="/fileupload/upload2" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"><br />
<input type="submit" value="上传">
</form>
Controller:
/**
* SpringMVC方式上传文件
* @return
*/
@RequestMapping("upload2")
public String testUpload2(HttpServletRequest request, MultipartFile upload){
System.out.println("upload2");
//上传的路径
String path = request.getSession().getServletContext().getRealPath("/uploads/");
//判断文件夹是否存在
File file = new File(path);
if(!file.exists()){
//新建文件夹
file.mkdirs();
}
String fileName = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-", "");
fileName = uuid+"_"+fileName;
//上传文件
try {
upload.transferTo(new File(path,fileName));
} catch (IOException e) {
e.printStackTrace();
}
return "success2";
}
3)springmvc方式实现跨服务器上传:
需要在文件上传的依赖基础之上,再导入另外两个依赖:
这两个依赖是sun公司提供的。
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18.1</version>
</dependency>
jsp
<form action="/fileupload/upload3" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"><br />
<input type="submit" value="上传">
</form>
Controller:
/**
* SpringMVC方式上传文件
* @return
*/
@RequestMapping("upload3")
public String testUpload3(MultipartFile upload){
System.out.println("upload3");
//上传的路径
String path = "http://localhost:9090/uploads/";
String fileName = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-", "");
fileName = uuid+"_"+fileName;
//创建客户端对象
Client client = Client.create();
//和文件服务器进行连接
WebResource webResource = client.resource(path + fileName);
try {
//上传文件
webResource.put(upload.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
return "success2";
}
三、异常处理:
- 系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
- 系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:
实现步骤:
1)编写异常类和错误页面
异常类:
package com.zl.except;
public class SysException extends Exception{
private String exceptionMsg;
public SysException(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
public String getExceptionMsg() {
return exceptionMsg;
}
public void setExceptionMsg(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
}
错误页面error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>错误页面...</h3>
${errorMsg}
</body>
</html>
2)自定义异常处理器
package com.zl.except;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SysExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
SysException ex = null;
if(e instanceof SysException){
ex = (SysException) e;
}else{
ex = new SysException("系统正在维护中....");
}
ModelAndView mv = new ModelAndView();
mv.addObject("errorMsg",ex.getExceptionMsg());
mv.setViewName("error");
return mv;
}
}
3)配置异常处理器
在springmvc.xml中配置异常处理器:
<!--配置异常处理器-->
<bean id="sysExceptionResolver" class="com.zl.except.SysExceptionResolver"></bean>
4)编写Controller类:
package com.zl.controller;
import com.zl.except.SysException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("exception")
public class ExceptionController {
@RequestMapping("testException")
public String testException() throws SysException {
System.out.println("testException");
try {
int i = 10/0;
} catch (Exception e) {
e.printStackTrace();
throw new SysException("查找用户出错...");
}
return "success";
}
}
四、SpingMVC拦截器:
1)自定义拦截器,实现HandlerInterceptor接口
MyInterceptor1
package com.zl.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor1 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("MyInterceptor1....前111");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("MyInterceptor1....后111");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("MyInterceptor1....最后111");
}
}
MyInterceptor2
package com.zl.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor2 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("MyInterceptor1....前222");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("MyInterceptor1....后222");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("MyInterceptor1....最后222");
}
}
2)配置拦截器
在springmvc.xml中配置
<!--配置拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/interceptor/*"/>
<bean class="com.zl.interceptor.MyInterceptor1"/>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.zl.interceptor.MyInterceptor2"/>
</mvc:interceptor>
</mvc:interceptors>
interceptor.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="/interceptor/testInterceptor">测试拦截器</a>
</body>
</html>
Controller
package com.zl.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("interceptor")
public class InterceptorController {
@RequestMapping("testInterceptor")
public String testInterceptor(){
System.out.println("testInterceptor...");
return "success";
}
}
需要注意的是:如果配置了多个拦截器,执行顺序如下: