第一章:响应数据和结果视图1. 返回值分类 1. 返回字符串 1. Controller方法返回字符串可以指定逻辑视图的名称,根据视图解析器为物理视图的地址。
- @RequestMapping(value="/hello")
- public String sayHello() {
- System.out.println("Hello SpringMVC!!");
- // 跳转到XX页面
- return "success";
- }
2. 具体的应用场景
- @Controller
- @RequestMapping("/user")
- public class UserController {
- /**
- * 请求参数的绑定
- */
- @RequestMapping(value="/initUpdate")
- public String initUpdate(Model model) {
- // 模拟从数据库中查询的数据
- User user = new User();
- user.setUsername("张三");
- user.setPassword("123");
- user.setMoney(100d);
- user.setBirthday(new Date());
- model.addAttribute("user", user);
- return "update";
- }
- }
- <h3>修改用户</h3>
- ${ requestScope }
- <form action="user/update" method="post">
- 姓名:<input type="text" name="username" value="${ user.username }"><br>
- 密码:<input type="text" name="password" value="${ user.password }"><br>
- 金额:<input type="text" name="money" value="${ user.money }"><br>
- <input type="submit" value="提交">
- </form>
2. 返回值是void
1. 如果控制器的方法返回值编写成void,执行程序报404的异常,默认查找JSP页面没有找到。 1. 默认会跳转到@RequestMapping(value="/initUpdate") initUpdate的页面。 2. 可以使用请求转发或者重定向跳转到指定的页面
- @RequestMapping(value="/initAdd")
- public void initAdd(HttpServletRequest request,HttpServletResponse response) throws
- Exception {
- System.out.println("请求转发或者重定向");
- // 请求转发
- // request.getRequestDispatcher("/WEB-INF/pages/add.jsp").forward(request,
- response);
- // 重定向
- // response.sendRedirect(request.getContextPath()+"/add2.jsp");
- response.setCharacterEncoding("UTF-8");
- response.setContentType("text/html;charset=UTF-8");
- // 直接响应数据
- response.getWriter().print("你好");
- return;
- }
3. 返回值是ModelAndView对象
1. ModelAndView对象是Spring提供的一个对象,可以用来调整具体的JSP视图 2. 具体的代码如下
- /
- **
- * 返回ModelAndView对象
- * 可以传入视图的名称(即跳转的页面),还可以传入对象。
- * @return
- * @throws Exception
- */
- @RequestMapping(value="/findAll")
- public ModelAndView findAll() throws Exception {
- ModelAndView mv = new ModelAndView();
- // 跳转到list.jsp的页面
- mv.setViewName("list");
- // 模拟从数据库中查询所有的用户信息
- List<User> users = new ArrayList<>();
- User user1 = new User();
- user1.setUsername("张三");
- user1.setPassword("123");
- User user2 = new User();
- user2.setUsername("赵四");
- user2.setPassword("456");users.add(user1);users.add(user2);// 添加对象mv.addObject("users", users);return mv;}
- <
- %@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
- <!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>
- <h3>查询所有的数据</h3>
- <c:forEach items="${ users }" var="user">
- ${ user.username }
- </c:forEach>
- </body>
- </html>
2. SpringMVC框架提供的转发和重定向1. forward请求转发 1. controller方法返回String类型,想进行请求转发也可以编写成
- /**
- * 使用forward关键字进行请求转发
- * "forward:转发的JSP路径",不走视图解析器了,所以需要编写完整的路径
- * @return
- * @throws Exception
- */
- @RequestMapping("/delete")
- public String delete() throws Exception {
- System.out.println("delete方法执行了...");
- // return "forward:/WEB-INF/pages/success.jsp";
- return "forward:/user/findAll";
- }
2. redirect重定向 1. controller方法返回String类型,想进行重定向也可以编写成
- /**
- * 重定向
- * @return
- * @throws Exception
- */
- @RequestMapping("/count")
- public String count() throws Exception {
- System.out.println("count方法执行了...");
- return "redirect:/add.jsp";
- // return "redirect:/user/findAll";
- }
3. ResponseBody响应json数据 1. DispatcherServlet会拦截到所有的资源,导致一个问题就是静态资源(img、css、js)也会被拦截到,从而
不能被使用。解决问题就是需要配置静态资源不进行拦截,在springmvc.xml配置文件添加如下配置 1. mvc:resources标签配置不过滤 1. location元素表示webapp目录下的包下的所有文件 2. mapping元素表示以/static开头的所有请求路径,如/static/a 或者/static/a/b
- <mvc:resources location="/css/" mapping="/css/**"/>
- <mvc:resources location="/images/" mapping="/images/**"/>
- <mvc:resources location="/js/" mapping="/js/**"/>
2. 使用@RequestBody获取请求体数据
- // 页面加载
- // 页面加载
- $(function(){
- // 绑定点击事件
- $("#btn").click(function(){
- $.ajax({
- url:"user/testJson",
- contentType:"application/json;charset=UTF-8",
- data:'{"addressName":"aa","addressNum":100}',
- dataType:"json",
- type:"post",
- success:function(data){
- alert(data);
- alert(data.addressName);
- }
- });
- });
- });
- /**
- *获取请求体的数据
- * @param body
- */
- @RequestMapping("/testJson")
- public void testJson(@RequestBody String body) {
- System.out.println(body);
- } /
3. 使用@RequestBody注解把json的字符串转换成JavaBean的对象
- /*
- / 页面加载
- // 页面加载
- $(function(){
- // 绑定点击事件
- $("#btn").click(function(){
- $.ajax({
- url:"user/testJson",
- contentType:"application/json;charset=UTF-8",
- data:'{"addressName":"aa","addressNum":100}',
- dataType:"json",
- type:"post",
- success:function(data){
- alert(data);
- alert(data.addressName);
- }
- });
- });
- });
- /**
- * 获取请求体的数据
- * @param body
- */
- @RequestMapping("/testJson")
- public void testJson(@RequestBody Address address) {
- System.out.println(address);
- }
4. 使用@ResponseBody注解把JavaBean对象转换成json字符串,直接响应 1. 要求方法需要返回JavaBean的对象
- // 页面加载
- $(function(){
- // 绑定点击事件
- $("#btn").click(function(){
- $.ajax({
- url:"user/testJson",
- contentType:"application/json;charset=UTF-8",
- data:'{"addressName":"哈哈","addressNum":100}',dataType:"json",type:"post",success:function(data){alert(data);alert(data.addressName);}});});});
- @RequestMapping("/testJson")
- public @ResponseBody Address testJson(@RequestBody Address address) {
- System.out.println(address);
- address.setAddressName("上海");
- return address;
- }
5. 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>
第二章:SpringMVC实现文件上传1. 文件上传的回顾 1. 导入文件上传的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>
2. 编写文件上传的JSP页面
- <h3>文件上传</h3>
- <form action="user/fileupload" method="post" enctype="multipart/form-data">
- 选择文件:<input type="file" name="upload"/><br/>
- <input type="submit" value="上传文件"/>
- </form>
3. 编写文件上传的Controller控制器
- /**
- * 文件上传
- * @throws Exception
- */
- @RequestMapping(value="/fileupload")
- public String fileupload(HttpServletRequest request) throws Exception {
- // 先获取到要上传的文件目录
- String path = request.getSession().getServletContext().getRealPath("/uploads");
- // 创建File对象,一会向该路径下上传文件
- File file = new File(path);
- // 判断路径是否存在,如果不存在,创建该路径
- if(!file.exists()) {
- file.mkdirs();
- } /
- / 创建磁盘文件项工厂
- DiskFileItemFactory factory = new DiskFileItemFactory();
- ServletFileUpload fileUpload = new ServletFileUpload(factory);
- // 解析request对象
- List<FileItem> list = fileUpload.parseRequest(request);
- // 遍历
- for (FileItem fileItem : list) {
- // 判断文件项是普通字段,还是上传的文件
- if(fileItem.isFormField()) {
- }else {
- // 上传文件项
- 2. SpringMVC传统方式文件上传
- 1. SpringMVC框架提供了MultipartFile对象,该对象表示上传的文件,要求变量名称必须和表单file标签的
- name属性名称相同。
- 2. 代码如下
- 3. 配置文件解析器对象
- // 获取到上传文件的名称
- String filename = fileItem.getName();
- // 上传文件
- fileItem.write(new File(file, filename));
- // 删除临时文件
- fileItem.delete();
- }
- } return "success";
- }
2.SpringMVC传统方式文件上传
