目录
数据处理及跳转
1. 结果跳转方式
①.ModelAndView
设置ModelAndView对象 , 根据view的名称 , 和视图解析器跳到指定的页面 .
<bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/html/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5"/>
</bean>
对应的controller类
/**
* 返回ModelAndView对象的方式
* @return
*/
@RequestMapping("/save3")
public ModelAndView save3(){
System.out.println("执行了...");
// 创建mv对象
ModelAndView mv = new ModelAndView();
// 把一些数据,存储到mv对象中
mv.addObject("msg","用户名或者密码已经存在");
// 设置逻辑视图的名称
mv.setViewName("suc");
return mv;
}
②.ServletAPI
通过设置ServletAPI , 不需要视图解析器 .
1、通过HttpServletResponse进行输出
2、通过HttpServletResponse实现重定向
3、通过HttpServletResponse实现转发
@Controller
@RequestMapping(path = "/role") // 一级请求路径
public class RoleController {
@RequestMapping("/t1")
public void test1(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
rsp.getWriter().println("Hello,Spring BY servlet API");
}
@RequestMapping("/t2")
public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
rsp.sendRedirect("/SpringMVCDemo/html/suc.html");
}
@RequestMapping("/t3")
public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception {
//转发
req.setAttribute("msg","hello");
req.getRequestDispatcher("/html/suc.html").forward(req,rsp);
}
}
③.SpringMVC
通过SpringMVC来实现转发和重定向 - 无需视图解析器;
测试前,需要将视图解析器注释掉
@Controller
@RequestMapping(path = "/role") // 一级请求路径
public class RoleController {
@RequestMapping("/t1")
public String test1(){
//转发
return "/html/suc.html";
}
@RequestMapping("/t2")
public String test2(){
//转发二
return "forward:/html/suc.html";
}
@RequestMapping("/t3")
public String test3(){
//重定向
return "redirect:/html/suc.html";
}
}
2.ResponseBody响应json数据
json和JavaBean对象互相转换的过程中,需要使用jackson的jar包
<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>
DispatcherServlet会拦截到所有的资源,导致一个问题就是静态资源(img、css、js)也会被拦截到,从而不能被使用。解决问题就是需要配置静态资源不进行拦截,在springmvc.xml配置文件添加如下配置
标签配置不过滤
1. location元素表示webapp目录下的包下的所有文件
2. mapping元素表示以/static开头的所有请求路径,如/static/a 或者/static/a/b
<!--设置静态资源不过滤-->
<mvc:resources mapping="/css/**" location="/css/"/> <!--样式-->
<mvc:resources mapping="/images/**" location="/images/"/> <!--图片-->
<mvc:resources mapping="/js/**" location="/js/"/> <!--javascript-->
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
// 页面加载
$(function(){
// 单击事件
$("#btn").click(function(){
// 发送ajax的请求
$.ajax({
type: "post",
url: "/SpringMVCDemo/user/save6",
data:{username:"haha",age:"20"},
success:function(d){
// 编写很多代码
alert(d.username+" ‐ "+d.age);
}
});
});
});
</script>
</head>
<body>
<h3>异步的数据交互</h3>
<input type="button" value="ajax交互" id="btn">
</body>
</html>
controller
/**
* 异步的数据交互
* 重定向
* @return
*/
@RequestMapping("/save6")
public @ResponseBody User save6(User user){
System.out.println(user);
// 模拟,调用业务层代码
user.setUsername("hello");
user.setAge(100);
// 把user对象转换成json,字符串,再响应。使用@ResposeBody注解 response.getWriter().print()
return user;
}
在springMVC当中如果要实现页面跳转就不要使用ajax,如果要json数据的返回就用ajax
SpringMVC实现文件上传
导入文件上传的jar包
<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>
在Springmvc.xml配置文件上传解析器
<!--配置文件上传的解析器组件。id的名称是固定,不能乱写-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--设置上传文件的总大小 8M = 8 * 1024 * 1024 -->
<property name="maxUploadSize" value="8388608" />
</bean>
编写文件上传的html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>文件上传</h3>
<form id="addForm" action="/SpringMvc/file/upload" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="file" width="120px">
<input type="submit" value="上传">
</form>
<div id="upMenu" class="white_content">
<form id="downForm" lay-filter="updata" action="/SpringMvc/file/down" method="get">
<input type="text" id="filename" name="filename">
<input type="submit" value="下载">
</form>
<input type="button" value="完成"/>
</div>
</body>
</html>
controller层
@Controller
@RequestMapping("/file")
public class FileController {
/**
* 文件上传功能
* @param file
* @return
* @throws IOException
*/
@RequestMapping(value="/upload",method= RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
// uploads文件夹位置
String rootPath = request.getSession().getServletContext().getRealPath("WEB-INF/upload");
// 原始名称
String originalFileName = file.getOriginalFilename();
// 新文件
File newFile = new File(rootPath + File.separator + File.separator + originalFileName);
// 判断目标文件所在目录是否存在
if( !newFile.getParentFile().exists()) {
// 如果目标文件所在的目录不存在,则创建父目录
newFile.getParentFile().mkdirs();
}
System.out.println(newFile);
// 将内存中的数据写入磁盘
file.transferTo(newFile);
return "{\"data\":\"success\"}";
}
/**
* 文件下载功能
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/down")
public void down(HttpServletRequest request, HttpServletResponse response) throws Exception{
String filename = request.getParameter("filename");
System.out.println(filename);
//模拟文件,myfile.txt为需要下载的文件
String fileName = request.getSession().getServletContext().getRealPath("WEB-INF/upload")+"/"+filename;
//获取输入流
InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
//假如以中文名下载的话
// String filename = "下载文件.txt";
//转码,免得文件名中文乱码
filename = URLEncoder.encode(filename,"UTF-8");
//设置文件下载头
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
int len = 0;
while((len = bis.read()) != -1){
out.write(len);
out.flush();
}
out.close();
}
}
SpringMVC的异常处理
1. 异常处理思路
Controller调用service,service调用dao,异常都是向上抛出的,最终有DispatcherServlet找异常处理器进行异常的处理。
2. SpringMVC的异常处理
①:使用自己处理异常
controller代码
/**
* 自己处理异常
* @return
*/
@RequestMapping("/findAll")
public String findAll(Model model){
try {
System.out.println("执行了...");
// 模拟异常
int a = 10/0;
}catch (Exception e){
model.addAttribute("errorMsg","系统正在维护,请联系管理员");
return "404";
}
return "suc";
}
404页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>错误提示页面</title>
</head>
<body>
<h1>404 <b th:text="${errorMsg}"></b></h1>
</body>
</html>
②:使用处理器处理异常
controller代码
/**
* 使用异常处理器方式
* @return
*/
@RequestMapping("/findAll2")
public String findAll2(){
System.out.println("执行了...");
//模拟异常
int a = 10 / 0;
return "suc";
}
自定义异常类
public class SysException extends Exception{
// 提示消息
private String message;
public SysException(String message){
this.message = message;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "SysException{" +
"message='" + message + '\'' +
'}';
}
}
自定义异常处理器
/**
* 异常处理器
*/
public class SysExceptionResolver implements HandlerExceptionResolver {
/**
* 程序出现了异常,调用异常处理器中的方法
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @param e e是Throwable的实例异常对象,用在catch语句中,相当于一个形参,一旦try捕获到了异常,那么就将这个异常信息交给e
* @return
*/
public ModelAndView resolveException(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, Object o, Exception e) {
e.printStackTrace(); //在命令行打印异常信息在程序中出错的位置及原因。
// 做强转
SysException exception = null;
// 判断
if(e instanceof SysException){
exception = (SysException)e;
}else{
exception = new SysException("系统正在维护,请联系管理员");
}
// 存入异常提示信息
ModelAndView mv = new ModelAndView();
mv.addObject("errorMsg",exception.getMessage());
// 设置跳转的页面
mv.setViewName("404");
return mv;
}
}
配置异常处理器
<!--配置异常处理器-->
<bean id="sysExceptionResolver" class="com.qcby.conf.SysExceptionResolver" />