springmvc_day02_01_response
1. response.jsp
<a href="user/testString">testString</a>
2. UserController
3.执行response.jsp
返回String类型
1. User
package cn.itcast.domain;
public class User {
private String username;
private String password;
private Integer age;
2. UserController
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testString")
public String testString(Model model) {
System.out.println("testString方法执行了...");
User user = new User();
user.setUsername("美美");
user.setPassword("123");
user.setAge(30);
model.addAttribute("user", user);
return "success";
}
}
3. success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
${user.username}
${user.password}
返回void
1. response.jsp
<a href="user/testVoid">testVoid</a>
2. UserController
请求转发
@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);
return;
}
重定向
/*设置中文乱码*/
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
/*重定向*/
response.sendRedirect(request.getContextPath() + "index.jsp");
return;
关键字实现请求转发和重定向
请求转发
@RequestMapping("/testForwardOrRedirect")
public String testForwardOrRedirect() {
System.out.println("testForwardOrRedirect方法执行了...");
return "forward:/WEB-INF/pages/success.jsp";
}
重定向
@RequestMapping("/testForwardOrRedirect")
public String testForwardOrRedirect() {
System.out.println("testForwardOrRedirect方法执行了...");
// return "forward:/WEB-INF/pages/success.jsp";
return "redirect:/index.jsp";
}
返回ModelAndView对象
- response.jsp
<a href="user/testModelAndView">testModelAndView</a> <br/>
- UserController
@RequestMapping("testModelAndView")
public ModelAndView testModelAndView() {
ModelAndView mv = new ModelAndView();
System.out.println("testModelAndView方法执行了...");
User user = new User();
user.setUsername("小芬");
user.setPassword("456");
user.setAge(30);
mv.addObject("user", user);
mv.setViewName("success");
return mv;
}
设置DispatcherServlet不拦截静态资源
1. 导入js
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
/*页面加载绑定单击事件*/
$(function () {
$("#btn").click(function () {
alert("hello btn");
});
});
</script>
2. springmvc.xml配置那些静态资源不被拦截
<!--设置静态资源不过滤-->
<mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
<mvc:resources mapping="/css/**" location="/css/"></mvc:resources>
<mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
Ajax请求
1. response.jsp
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
/*页面加载绑定单击事件*/
$(function () {
$("#btn").click(function () {
// alert("hello btn");
$.ajax({
url:"user/testAjax",
type:"post",
data:'{"username":"hehe", "password":"123", "age":12}',
dataType:"json",
success:function (data) {
}
});
});
});
</script>
2. UserController
@RequestMapping("testAjax")
public void testAjax(@RequestBody String body) {
System.out.println("testAjax方法执行了...");
System.out.println(body);
}
Json自动封装
1. 导入依赖
<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>
2. UserController
@RequestMapping("testAjax")
public @ResponseBody User testAjax(@RequestBody User user) {
System.out.println("testAjax方法执行了...");
/*后端把字符串封装到User中*/
System.out.println(user);
/*模拟查询*/
user.setUsername("haha");
user.setAge(10);
return user;
}
3. response.jsp
/*页面加载绑定单击事件*/
$(function () {
$("#btn").click(function () {
// alert("hello btn");
$.ajax({
url:"user/testAjax",
type:"post",
contentType:"application/json; charset=UTF-8",
data:'{"username":"hehe", "password":"123", "age":12}',
dataType:"json",
success:function (data) {
alert(data);
alert(data.username);
alert(data.password);
alert(data.age);
}
});
});
});
springmvc_day02_02_fileupload
1. UserController
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/fileupload1")
public String fileupload1(){
System.out.println("文件上传...");
return "success";
}
}
2. success.jsp
<h3>文件上传成功</h3>
传统方式文件上传
1. 导入依赖
<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>
2. index.jsp
<form action="/user/fileupload1" method="post" enctype="multipart/form-data">
选择上传文件:<input type="file" name="upload">
<input type="submit" value="上传">
</form>
3. UserController
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/fileupload1")
public String fileupload1(HttpServletRequest request) throws Exception {
System.out.println("文件上传...");
/*使用fileupload组件完成文件上传*/
/*上传的位置*/
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 = upload.parseRequest(request);
/*遍历*/
for (FileItem item : items) {
if (item.isFormField()) {
/*说明普通表单项*/
}else {
/*说明上传文件项*/
/*获取上传文件名称*/
String filename= item.getName();
/*把文件的名称设置为唯一值,uuid*/
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid + "_" + filename;
/*完成文件上传*/
item.write(new File(path, filename));
/*删除临时文件*/
item.delete();
}
}
return "success";
}
}
SpringMVC文件上传
1. index.jsp
<h3>SpringMVC文件上传</h3>
<form action="user/fileupload2" method="post" enctype="multipart/form-data">
选择上传文件:<input type="file" name="upload"> <br/>
<input type="submit" value="上传">
</form>
2. springmvc.xml配置文件解析器对象
<!--配置文件解析器对象-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"></property>
</bean>
3. UserController编写函数
@RequestMapping("/fileupload2")
public String fileupload2(HttpServletRequest request, MultipartFile upload) throws Exception {
System.out.println("springmvc文件上传...");
/*使用fileupload组件完成文件上传*/
/*上传的位置*/
String path = request.getSession().getServletContext().getRealPath("/uploads/");
/*判断,该路径是否存在*/
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
/*说明上传文件项*/
/*获取上传文件名称*/
String filename= upload.getOriginalFilename();
/*把文件的名称设置为唯一值,uuid*/
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid + "_" + filename;
/*完成文件上传*/
upload.transferTo(new File(path, filename));
return "success";
}
springMVC跨服务器上传文件
1. 添加fileupload服务器
2. 新建模块fileuploadserver
index.jsp
<html>
<body>
<h2>Hello fileupload server!</h2>
</body>
</html>
3. 新建uploads文件夹
4. 配置服务器,添加模块
5. index.jsp
<h3>跨服务器文件上传</h3>
<form action="user/fileupload3" method="post" enctype="multipart/form-data">
选择上传文件:<input type="file" name="upload"> <br/>
<input type="submit" value="上传">
</form>
6. 导入依赖
<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>
7. UserController编写函数
@RequestMapping("/fileupload3")
public String fileupload3( MultipartFile upload) throws Exception {
System.out.println("跨服务器文件上传...");
/*定义文件上传路径*/
String path = "http://localhost:9091/uploads/";
/*说明上传文件项*/
/*获取上传文件名称*/
String filename= upload.getOriginalFilename();
System.out.println(filename);
/*把文件的名称设置为唯一值,uuid*/
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid + "_" + filename;
/*完成文件上传,跨服务器*/
/*创建客户端对象*/
Client client = Client.create();
/*和图片服务器进行连接*/
WebResource webResource = client.resource(path+filename);
/*上传文件*/
webResource.put(upload.getBytes());
return "success";
}
出现403,409
如果403,修改tomcat的web.xml配置文件;
如果409,在项目target/项目名 目录下创建uploads文件夹
springmvc_day02_03_exception
SpringMVC异常处理
1. index.jsp
<h3>异常处理</h3>
<a href="user/testException">异常处理</a>
2. UserController
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testException")
public String testException() {
System.out.println("testException执行了...");
return "success";
}
}
3. success.jsp
<h3>执行成功</h3>
4. 模拟异常int a = 10/0;
int a = 10/0;
5. 自定义异常类SysException
package cn.itcast.exception;
/*自定义异常类*/
public class SysException extends Exception{
/*存储提示信息*/
private String message;
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SysException(String message) {
this.message = message;
}
}
6. UserController抛出SysException
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testException")
public String testException() throws SysException{
System.out.println("testException执行了...");
try {
int a = 10/0;
} catch (Exception e) {
/*打印异常信息*/
e.printStackTrace();
/*抛出自定义异常信息*/
throw new SysException("查询所有用户出现了错误...");
}
return "success";
}
}
7. 自定义异常处理器SysExceptionResolver
public class SysExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
SysException e = null;
if (ex instanceof SysException) {
e = (SysException) ex;
}else {
e = new SysException("系统正在维护中");
}
/*创建ModelAndView对象*/
ModelAndView mv = new ModelAndView();
mv.addObject("errorMsg", e.getMessage());
mv.setViewName("error");
return mv;
}
}
8. springmvc.xml中配置异常处理器
<!--配置自定义异常处理器-->
<bean id="sysExceptionResolver" class="cn.itcast.exception.SysExceptionResolver"></bean>
9. error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${errorMsg}
</body>
</html>
效果
SpringMVC中的拦截器
1. index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>拦截器</h3>
<a href="user/testInterceptor">拦截器</a>
</body>
</html>
2. UserController
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testInterceptor")
public String testInterceptor(){
System.out.println("testInterceptor执行了...");
return "success";
}
}
3. 自定义拦截器MyInterceptor
public class MyInterceptor1 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截器执行了...");
return true;
}
}
4. 在springmvc.xml中配置拦截器
<!--配置拦截器-->
<mvc:interceptors>
<!--配置拦截器-->
<mvc:interceptor>
<!--拦截那些方法-->
<mvc:mapping path="/user/*"/>
<!--配置拦截器对象-->
<bean class="cn.itcast.interceptor.MyInterceptor1"></bean>
</mvc:interceptor>
</mvc:interceptors>