springmvc
一、什么是SpringMVC 首先创建项目SpringMVC,导入依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 <?xml version="1.0" encoding="UTF-8" ?> <project xmlns ="http://maven.apache.org/POM/4.0.0" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelVersion > 4.0.0</modelVersion > <groupId > org.example</groupId > <artifactId > SpringMVC</artifactId > <packaging > pom</packaging > <version > 1.0-SNAPSHOT</version > <modules > <module > springmvc-01-servlet</module > </modules > <properties > <maven.compiler.source > 8</maven.compiler.source > <maven.compiler.target > 8</maven.compiler.target > </properties > <dependencies > <dependency > <groupId > junit</groupId > <artifactId > junit</artifactId > <version > 4.12</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-webmvc</artifactId > <version > 5.1.9.RELEASE</version > </dependency > <dependency > <groupId > javax.servlet</groupId > <artifactId > servlet-api</artifactId > <version > 2.5</version > </dependency > <dependency > <groupId > javax.servlet.jsp</groupId > <artifactId > jsp-api</artifactId > <version > 2.2</version > </dependency > <dependency > <groupId > javax.servlet</groupId > <artifactId > jstl</artifactId > <version > 1.2</version > </dependency > </dependencies > </project >
1.1、springmvc-01-serlvet模块 1、模块 2、添加Web app的支持!
3、pom.xml (springmvc-01-serlvet) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 <?xml version="1.0" encoding="UTF-8" ?> <project xmlns ="http://maven.apache.org/POM/4.0.0" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > <parent > <artifactId > SpringMVC</artifactId > <groupId > org.example</groupId > <version > 1.0-SNAPSHOT</version > </parent > <modelVersion > 4.0.0</modelVersion > <artifactId > springmvc-01-servlet</artifactId > <properties > <maven.compiler.source > 8</maven.compiler.source > <maven.compiler.target > 8</maven.compiler.target > </properties > <dependencies > <dependency > <groupId > javax.servlet</groupId > <artifactId > servlet-api</artifactId > <version > 2.5</version > </dependency > <dependency > <groupId > javax.servlet.jsp</groupId > <artifactId > jsp-api</artifactId > <version > 2.2</version > </dependency > </dependencies > </project >
4、HelloServlet 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 package com.wu.servlet;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class HelloServlet extends HttpServlet { @Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getParameter("method" ); if (method.equals("add" )){ req.getSession().setAttribute("msg" ,"执行了add方法" ); } if (method.equals("delete" )){ req.getSession().setAttribute("msg" ,"执行了delete方法" ); } req.getRequestDispatcher("WEB-INF/jsp/test.jsp" ).forward(req,resp); } @Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
5、test 1 2 3 4 5 6 7 8 9 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > Title</title > </head > <body > ${msg} </body > </html >
6、web 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?xml version="1.0" encoding="UTF-8" ?> <web-app xmlns ="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version ="4.0" > <servlet > <servlet-name > hello</servlet-name > <servlet-class > com.wu.servlet.HelloServlet</servlet-class > </servlet > <servlet-mapping > <servlet-name > hello</servlet-name > <url-pattern > /hello</url-pattern > </servlet-mapping > <session-config > <session-timeout > 15</session-timeout > </session-config > <welcome-file-list > <welcome-file > /WEB-INF/jsp/form.jsp</welcome-file > </welcome-file-list > </web-app >
7、from 1 2 3 4 5 6 7 8 9 10 11 12 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="${pageContext.request.contextPath}/hello" method="post" > <input type="text" name="method" > <input type="submit" > </form> </body> </html>
8、结果
//、add
//、delete
1.2、MVC框架要做哪些事情
将url映射到java类或java类的方法
封装用户提交的数据 .
处理请求–调用相关的业务处理–封装响应数据
将响应的数据进行渲染 . jsp / html 等表示层数据
1.3、文档 4.3.24文档
1.4、注意 如果出现404问题,请查看
1、文件–>打开项目结构
添加lib目录必须在WEB-INF下,因为jar包需要上传tomcat
2、2、然后加入所有的包
3、全选后点击确定
注意:添加lib后,需要重启tomcat
二、第一个MVC程序 SpringMVC02:第一个MVC程序
1.1、springmvc-02-hellomvc 1、模块
2、web.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <?xml version="1.0" encoding="UTF-8" ?> <web-app xmlns ="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version ="4.0" > <servlet > <servlet-name > springmvc</servlet-name > <servlet-class > org.springframework.web.servlet.DispatcherServlet</servlet-class > <init-param > <param-name > contextConfigLocation</param-name > <param-value > classpath:springmvc-servlet.xml</param-value > </init-param > <load-on-startup > 1</load-on-startup > </servlet > <servlet-mapping > <servlet-name > springmvc</servlet-name > <url-pattern > /</url-pattern > </servlet-mapping > </web-app >
3、springmvc-servlet.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <?xml version="1.0" encoding="UTF8" ?> <beans xmlns ="http://www.springframework.org/schema/beans" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" > <bean class ="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" /> <bean class ="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" /> <bean class ="org.springframework.web.servlet.view.InternalResourceViewResolver" id ="InternalResourceViewResolver" > <property name ="prefix" value ="/WEB-INF/jsp/" /> <property name ="suffix" value =".jsp" /> </bean > <bean id ="/hello" class ="com.wu.controller.HelloController" /> </beans >
4、HelloController.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class HelloController implements Controller { @Override public ModelAndView handleRequest (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { ModelAndView mv = new ModelAndView (); mv.addObject("msg" ,"HelloSpringMVC!" ); mv.setViewName("hello" ); return mv; } }
5、hello.jsp 1 2 3 4 5 6 7 8 9 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > Title</title > </head > <body > ${msg} </body > </html >
6、TomCat配置
7、查看项目结构
7、结果
输入/hello
1.2、中心控制器 当发起请求时被前置的控制器拦截到请求,根据请求参数生成代理请求,找到请求对应的实际控制器,控制器处理请求,创建数据模型,访问数据库,将模型响应给中心控制器,控制器使用模型与视图渲染视图结果,将结果返回给中心控制器,再将结果返回给请求者。
HandlerMapping: 处理器映射器`
HandlerAdapter: 处理器适配器
viewResolver: 视图解析器
图为SpringMVC的一个较完整的流程图,实线表示SpringMVC框架提供的技术,不需要开发者实现,虚线表示需要开发者实现。
1.3、深入学习SpringMVC 1、web 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <?xml version="1.0" encoding="UTF-8" ?> <web-app xmlns ="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version ="4.0" > <servlet > <servlet-name > springmvc</servlet-name > <servlet-class > org.springframework.web.servlet.DispatcherServlet</servlet-class > <init-param > <param-name > contextConfigLocation</param-name > <param-value > classpath:springmvc-servlet.xml</param-value > </init-param > <load-on-startup > 1</load-on-startup > </servlet > <servlet-mapping > <servlet-name > springmvc</servlet-name > <url-pattern > /</url-pattern > </servlet-mapping > </web-app >
2、springmvc-servlet.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version="1.0" encoding="UTF8" ?> <beans xmlns ="http://www.springframework.org/schema/beans" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" > <bean class ="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" /> <bean class ="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" /> <bean class ="org.springframework.web.servlet.view.InternalResourceViewResolver" id ="InternalResourceViewResolver" > <property name ="prefix" value ="/WEB-INF/jsp/" /> <property name ="suffix" value =".jsp" /> </bean > <bean id ="/hello" class ="com.wu.controller.HelloController" /> </beans >
3、HelloController.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class HelloController implements Controller { @Override public ModelAndView handleRequest (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { ModelAndView mv = new ModelAndView (); String result="HelloSpringMVC!" ; mv.addObject("msg" ,result); mv.setViewName("hello" ); return mv; } }
1.4、使用注解开发SpringMVC 模块 1、web.jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 <?xml version="1.0" encoding="UTF-8" ?> <web-app xmlns ="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version ="4.0" > <servlet > <servlet-name > springmvc</servlet-name > <servlet-class > org.springframework.web.servlet.DispatcherServlet</servlet-class > <init-param > <param-name > contextConfigLocation</param-name > <param-value > classpath:springmvc-servlet.xml</param-value > </init-param > <load-on-startup > 1</load-on-startup > </servlet > <servlet-mapping > <servlet-name > springmvc</servlet-name > <url-pattern > /</url-pattern > </servlet-mapping > </web-app >
2、springmvc-servlet.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 <?xml version="1.0" encoding="UTF8" ?> <beans xmlns ="http://www.springframework.org/schema/beans" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xmlns:context ="http://www.springframework.org/schema/context" xmlns:mvc ="http://www.springframework.org/schema/mvc" xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd" > <context:component-scan base-package ="com.wu.controller" /> <mvc:default-servlet-handler /> <mvc:annotation-driven /> <bean class ="org.springframework.web.servlet.view.InternalResourceViewResolver" id ="internalResourceViewResolver" > <property name ="prefix" value ="/WEB-INF/jsp/" /> <property name ="suffix" value =".jsp" /> </bean > </beans >
3、HelloController 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 package com.wu.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;@Controller public class HelloController { @RequestMapping("/h1") public String sayHello (Model model) { model.addAttribute("msg" ,"hello,SpringMVCAnnotation!" ); return "hello" ; } }
在视图解析器中我们把所有的视图都存放在/WEB-INF/目录下,这样可以保证视图安全,因为这个目录下的文件,客户端不能直接访问。
1 2 3 4 5 6 7 8 9 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > Title</title > </head > <body > ${msg} </body > </html >
4、查看Tomcat配置
5、lib中加入所有包
6、结果
三、Controller及RestFul SpringMVC03:RestFul和控制器
第一种方法——实现Controller接口 springmvc-04-controller模块
1、web 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <?xml version="1.0" encoding="UTF-8" ?> <web-app xmlns ="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version ="4.0" > <servlet > <servlet-name > springmvc</servlet-name > <servlet-class > org.springframework.web.servlet.DispatcherServlet</servlet-class > <init-param > <param-name > contextConfigLocation</param-name > <param-value > classpath:springmvc-servlet.xml</param-value > </init-param > <load-on-startup > 1</load-on-startup > </servlet > <servlet-mapping > <servlet-name > springmvc</servlet-name > <url-pattern > /</url-pattern > </servlet-mapping > <filter > <filter-name > encoding</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 > encoding</filter-name > <url-pattern > /*</url-pattern > < !– "/" 代表过滤所有请求(除jsp), "/*" 代表过滤所有请求(包括jsp) – > </filter-mapping > </web-app >
2、springmvc-servlet.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?xml version="1.0" encoding="UTF8" ?> <beans xmlns ="http://www.springframework.org/schema/beans" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xmlns:context ="http://www.springframework.org/schema/context" xmlns:mvc ="http://www.springframework.org/schema/mvc" xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd" > <context:component-scan base-package ="com.wu.controller" /> <bean class ="org.springframework.web.servlet.view.InternalResourceViewResolver" id ="InternalResourceViewResolver" > <property name ="prefix" value ="/WEB-INF/jsp/" /> <property name ="suffix" value =".jsp" /> </bean > <bean id ="/t1" class ="com.wu.controller.controllerTest1" /> </beans >
3、ControllerTest1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 package com.wu.controller;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.mvc.Controller;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class controllerTest1 implements Controller { @Override public ModelAndView handleRequest (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { ModelAndView mv = new ModelAndView (); mv.addObject("msg" ,"controllerTest1" ); mv.setViewName("test" ); return mv; } }
4、test.jsp 1 2 3 4 5 6 7 8 9 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > SpringMVC</title > </head > <body > ${msg} </body > </html >
5、结果:
第二种——使用注解@Controller 1、ControllerTest2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 package com.wu.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;@Controller public class controllerTest2 { @RequestMapping("t1") public String test1 (Model model) { model.addAttribute("msg" ,"Hello,controllerTest2" ); return "test" ; } @RequestMapping("t3") public String test3 (Model model) { model.addAttribute("msg" ,"Hello,test3" ); return "test" ; } }
2、springmvc-servlet.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?xml version="1.0" encoding="UTF8" ?> <beans xmlns ="http://www.springframework.org/schema/beans" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xmlns:context ="http://www.springframework.org/schema/context" xmlns:mvc ="http://www.springframework.org/schema/mvc" xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd" > <context:component-scan base-package ="com.wu.controller" /> <bean class ="org.springframework.web.servlet.view.InternalResourceViewResolver" id ="InternalResourceViewResolver" > <property name ="prefix" value ="/WEB-INF/jsp/" /> <property name ="suffix" value =".jsp" /> </bean > </beans >
3、结果
RestFul 风格 Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。
功能
资源:互联网所有的事物都可以被抽象为资源 资源操作:使用POST、DELETE、PUT、GET,使用不同方法对资源进行操作。 分别对应 添加、 删除、修改、查询。
传统方式操作资源 : 通过不同的参数来实现不同的效果!方法单一,post 和 get
http://127.0.0.1/item/queryItem.action?id=1 查询,GET
http://127.0.0.1/item/saveItem.action 新增,POST
http://127.0.0.1/item/updateItem.action 更新,POST
http://127.0.0.1/item/deleteItem.action?id=1 删除,GET或POST
使用RESTful操作资源 : 可以通过不同的请求方式来实现不同的效果!如下:请求地址一样,但是功能可以不同!
http://127.0.0.1/item/1 查询,GET
http://127.0.0.1/item 新增,POST
http://127.0.0.1/item 更新,PUT
http://127.0.0.1/item/1 删除,DELETE
RestFulController 原来
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 package com.wu.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.*;@Controller public class RestFulController { @RequestMapping("/add") public String test1 (int a, int b, Model model) { int res = a + b; model.addAttribute("msg" ,"结果为" +res); return "test" ; } }
现在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 package com.wu.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.*;@Controller public class RestFulController { @RequestMapping("/add/{a}/{b}") public String test2 (@PathVariable int a,@PathVariable int b, Model model) { int res = a + b; model.addAttribute("msg" ,"结果为" +res); return "test" ; } }
结果
post方法 a.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > Title</title > </head > <body > <form action ="/add/1/2" method ="post" > <button > 提交</button > </form > </body > </html > package com.wu.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; @Controller public class RestFulController { //原来的: http://LocaLhost:8080/add?a=1&b=2 //RestFul: http://LocaLhost:8080/add/1/2 /* @RequestMapping(value = "/add/{a}/{b}", method = RequestMethod.GET) */ @PostMapping(value = "/add/{a}/{b}") public String Test1(@PathVariable int a, @PathVariable String b, Model model) { String rest = a + b; model.addAttribute("msg", "结果为1:" + rest + ""); return "test"; } @GetMapping("/add/{a}/{b}") public String Test2(@PathVariable int a, @PathVariable String b, Model model) { String rest = a + b; model.addAttribute("msg", "结果为2:" + rest + ""); return "test"; } }
结果:
四、数据处理及跳转 SpringMVC04:数据处理及跳转
4.1、结果跳转方式 ModelAndView
ModelTest1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package com.wu.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;@Controller public class ModelTest1 { @RequestMapping("m1/t1") public String test1 (HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); System.out.println(session.getId()); return "test" ; } }
修改
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 package com.wu.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;@Controller public class ModelTest1 { @RequestMapping("/m/t1") public String test1 (Model model) { model.addAttribute("msg" ,"ModelTest1" ); return "/test" ; } @RequestMapping("/m/t2") public String test2 (Model model) { model.addAttribute("msg" ,"ModelTest2" ); return "forward:/index.jsp" ; } @RequestMapping("/m/t3") public String test3 (Model model) { model.addAttribute("msg" ,"ModelTest3" ); return "redirect:/index.jsp" ; } }
4.2、数据处理 04——数据处理
正常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 package com.wu.controller;import com.sun.org.glassfish.gmbal.ParameterNames;import com.wu.pojo.User;import org.junit.Test;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.servlet.ModelAndView;@Controller @RequestMapping("/user") public class UserController { @GetMapping("/t1") public String test1 (String name, Model model) { System.out.println("接收到前端的参数为" +name); model.addAttribute("msg" ,name); return "test" ; } } }
添加注解@RequestParam(“xxxx”)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 package com.wu.controller;import com.sun.org.glassfish.gmbal.ParameterNames;import com.wu.pojo.User;import org.junit.Test;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.servlet.ModelAndView;@Controller @RequestMapping("/user") public class UserController { @GetMapping("/t1") public String Test1 (@RequestParam("username") String name, Model model) { System.out.println("接收到前端参数为:" + name); model.addAttribute("msg" ,name); return "test" ; } }
对象参数
创建pojo文件夹 —-> 新建user实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 package com.wu.pojo;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private int age; } @GetMapping("/t2") public String test2 (User user) { System.out.println(user); return "test" ; }
4.3、乱码问题
问题: form.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > Title</title > </head > <body > <form action ="/e/t1" method ="get" > <input type ="text" name ="name" > <input type ="submit" > </form > </body > </html >
EncodingController
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package com.wu.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;@Controller public class EncodingController { @RequestMapping("e/t1") public String Test1 (String name, Model model) { System.out.println(name); model.addAttribute("msg" ,name); return "test" ; } }
过滤器解决乱码 加上过滤器
EncodingFilter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 package com.wu.filter;import javax.servlet.*;import java.io.IOException;public class EncodingFilter implements Filter { @Override public void init (FilterConfig filterConfig) throws ServletException { } @Override public void doFilter (ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8" ); servletResponse.setCharacterEncoding("utf-8" ); filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy () { } }
web.xml
1 2 3 4 5 6 7 8 9 <filter > <filter-name > encoding</filter-name > <filter-class > com.wu.filter.EncodingFilter</filter-class > </filter > <filter-mapping > <filter-name > encoding</filter-name > <url-pattern > /*</url-pattern > </filter-mapping >
输入http://localhost:8080/form.jsp,输入,点击提交
大佬的过滤器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 package com.wu.filter;import javax.servlet.*;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.Map;public class GenericEncodingFilter implements Filter { @Override public void destroy () { } @Override public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse myResponse=(HttpServletResponse) response; myResponse.setContentType("text/html;charset=UTF-8" ); HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletRequest myrequest = new MyRequest (httpServletRequest); chain.doFilter(myrequest, response); } @Override public void init (FilterConfig filterConfig) throws ServletException { } } class MyRequest extends HttpServletRequestWrapper { private HttpServletRequest request; private boolean hasEncode; public MyRequest (HttpServletRequest request) { super (request); this .request = request; } @Override public Map getParameterMap () { String method = request.getMethod(); if (method.equalsIgnoreCase("post" )) { try { request.setCharacterEncoding("utf-8" ); return request.getParameterMap(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else if (method.equalsIgnoreCase("get" )) { Map<String, String[]> parameterMap = request.getParameterMap(); if (!hasEncode) { for (String parameterName : parameterMap.keySet()) { String[] values = parameterMap.get(parameterName); if (values != null ) { for (int i = 0 ; i < values.length; i++) { try { values[i] = new String (values[i] .getBytes("ISO-8859-1" ), "utf-8" ); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } } hasEncode = true ; } return parameterMap; } return super .getParameterMap(); } @Override public String getParameter (String name) { Map<String, String[]> parameterMap = getParameterMap(); String[] values = parameterMap.get(name); if (values == null ) { return null ; } return values[0 ]; } @Override public String[] getParameterValues(String name) { Map<String, String[]> parameterMap = getParameterMap(); String[] values = parameterMap.get(name); return values; } }
web
1 2 3 4 5 6 7 8 9 <filter > <filter-name > encoding</filter-name > <filter-class > com.wu.filter.GenericEncodingFilter</filter-class > </filter > <filter-mapping > <filter-name > encoding</filter-name > <url-pattern > /*</url-pattern > </filter-mapping >
注意:过滤器只能开一个,所以使用的话,尽量用自己喜欢的,其他的都注释
五、Json交互处理 SpringMVC06:Json交互处理
5.1、Jackson Databind 导入依赖 maven仓库地址
1 2 3 4 5 6 <dependency > <groupId > com.fasterxml.jackson.core</groupId > <artifactId > jackson-databind</artifactId > <version > 2.13.1</version > </dependency >
springmvc-servlet.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <?xml version="1.0" encoding="UTF8" ?> <beans xmlns ="http://www.springframework.org/schema/beans" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xmlns:context ="http://www.springframework.org/schema/context" xmlns:mvc ="http://www.springframework.org/schema/mvc" xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd" > <context:component-scan base-package ="com.wu.controller" /> <bean class ="org.springframework.web.servlet.view.InternalResourceViewResolver" id ="InternalResourceViewResolver" > <property name ="prefix" value ="/WEB-INF/jsp/" /> <property name ="suffix" value =".jsp" /> </bean > </beans >
web.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version="1.0" encoding="UTF-8" ?> <web-app xmlns ="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version ="4.0" > <servlet > <servlet-name > springmvc</servlet-name > <servlet-class > org.springframework.web.servlet.DispatcherServlet</servlet-class > <init-param > <param-name > contextConfigLocation</param-name > <param-value > classpath:springmvc-servlet.xml</param-value > </init-param > <load-on-startup > 1</load-on-startup > </servlet > <servlet-mapping > <servlet-name > springmvc</servlet-name > <url-pattern > /</url-pattern > </servlet-mapping > </web-app >
User
1 2 3 4 5 6 7 8 9 10 11 12 13 14 package com.wu.pojo;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data @AllArgsConstructor @NoArgsConstructor public class User { private String name; private int age; private String sex; }
UserController
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 package com.wu.controller;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.SerializationFeature;import com.wu.pojo.User;import com.wu.utils.JsonUtils;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestController;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List;@Controller public class UserController { @RequestMapping("/j1") @ResponseBody public String json1 () throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper (); User user = new User ("xiaowu" , 19 , "男" ); String str = mapper.writeValueAsString(user); return str; } }
结果:
5.2、解决json乱码问题 方法一 1 2 @RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
方法二 在springmvc-servlet.xml中添加下面代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <mvc:annotation-driven > <mvc:message-converters register-defaults ="true" > <bean class ="org.springframework.http.converter.StringHttpMessageConverter" > <constructor-arg value ="UTF-8" /> </bean > <bean class ="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" > <property name ="objectMapper" > <bean class ="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean" > <property name ="failOnEmptyBeans" value ="false" /> </bean > </property > </bean > </mvc:message-converters > </mvc:annotation-driven >
5.3、返回json字符串统一解决 @RestController
//它的作用相当于@Controller和@ResponseBody的结合体,可以直接返回JSON、XML等内容,而@Controller则需要在方法上添加@ResponseBody注解才能返回JSON等内容。
1、对象类型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @RequestMapping("/j2") public String json2 () throws JsonProcessingException { List<User> userList = new ArrayList <>(); User user1 = new User ("xiaowu" , 1 , "男" ); User user2 = new User ("xiaowu" , 1 , "男" ); User user3 = new User ("xiaowu" , 1 , "男" ); User user4 = new User ("xiaowu" , 1 , "男" ); userList.add(user1); userList.add(user2); userList.add(user3); userList.add(user4); return JsonUtils.getJson(userList); }
2、时间类型 1 2 3 4 5 6 7 8 9 @RequestMapping("/j3") public String json3 () throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper (); Date date = new Date (); return mapper.writeValueAsString(date); }
3、纯java解决—时间戳 1 2 3 4 5 6 7 8 9 10 11 12 @RequestMapping("/j3") public String json3 () throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper (); Date date = new Date (); SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss" ); return mapper.writeValueAsString(sdf.format(date)); }
4、不使用时间戳的方式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 @RequestMapping("/j3") public String json3 () throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper (); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false ); SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss" ); mapper.setDateFormat(sdf); Date date = new Date (); return mapper.writeValueAsString(date); }
5、工具类 JsonUtils
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 package com.wu.utils;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.SerializationFeature;import java.text.SimpleDateFormat;public class JsonUtils { public static String getJson (Object object) { return getJson(object,"yyyy-MM-dd HH:mm:ss" ); } public static String getJson (Object object,String dateFormat) { ObjectMapper mapper = new ObjectMapper (); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false ); SimpleDateFormat sdf=new SimpleDateFormat (dateFormat); mapper.setDateFormat(sdf); try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { e.printStackTrace(); } return "" ; } } @RequestMapping("/j3") public String json3 () throws JsonProcessingException { Date date = new Date (); return JsonUtils.getJson(date); }
5.4、FastJson fastjson.jar是阿里开发的一款专门用于Java开发的包,可以方便的实现json对象与JavaBean对象的转换,实现JavaBean对象与json字符串的转换,实现json对象与json字符串的转换。实现json的转换方法很多,最后的实现结果都是一样的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 @RequestMapping("/j4") public String json4 () throws JsonProcessingException { List<User> userList = new ArrayList <>(); User user1 = new User ("xiaowu1" , 1 , "男" ); User user2 = new User ("xiaowu2" , 2 , "女" ); User user3 = new User ("xiaowu3" , 3 , "男" ); User user4 = new User ("xiaowu4" , 4 , "男" ); userList.add(user1); userList.add(user2); userList.add(user3); userList.add(user4); System.out.println("*******Java对象 转 JSON字符串*******" ); String str1 = JSON.toJSONString(userList); System.out.println("JSON.toJSONString(list)==>" +str1); String str2 = JSON.toJSONString(user1); System.out.println("JSON.toJSONString(user1)==>" +str2); System.out.println("\n****** JSON字符串 转 Java对象*******" ); User jp_user1=JSON.parseObject(str2,User.class); System.out.println("JSON.parseObject(str2,User.class)==>" +jp_user1); System.out.println("\n****** Java对象 转 JSON对象 ******" ); JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2); System.out.println("(JSONObject) JSON.toJSON(user2)==>" +jsonObject1.getString("name" )); System.out.println("\n****** JSON对象 转 Java对象 ******" ); User to_java_user = JSON.toJavaObject(jsonObject1, User.class); System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>" +to_java_user); return "hello" ; }
六、SpringMVC:整合SSM 狂神说SpringMVC05:整合SSM框架
6.1、环境要求:
IDEA
MySQL 8.0.27
Tomcat 9.0.64
Maven 3.6.3
要求:
需要熟练掌握MySQL数据库,Spring,JavaWeb及MyBatis知识,简单的前端知识;
6.2、创建数据库 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 CREATE DATABASE `ssmbuild`;USE `ssmbuild`; DROP TABLE IF EXISTS `books`;CREATE TABLE `books` (`bookID` INT (10 ) NOT NULL AUTO_INCREMENT COMMENT '书id' , `bookName` VARCHAR (100 ) NOT NULL COMMENT '书名' , `bookCounts` INT (11 ) NOT NULL COMMENT '数量' , `detail` VARCHAR (200 ) NOT NULL COMMENT '描述' , KEY `bookID` (`bookID`) ) ENGINE= INNODB DEFAULT CHARSET= utf8 INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES (1 ,'Java' ,1 ,'从入门到放弃' ), (2 ,'MySQL' ,10 ,'从删库到跑路' ), (3 ,'Linux' ,5 ,'从进门到进牢' );
6.3、导入依赖 新建项目,导入依赖junit、mysql、c3p0、servlet、JSP 、Mybatis、Spring,连接数据库
1、pom文件依赖 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 <?xml version="1.0" encoding="UTF-8" ?> <project xmlns ="http://maven.apache.org/POM/4.0.0" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelVersion > 4.0.0</modelVersion > <groupId > org.example</groupId > <artifactId > ssmbuild</artifactId > <version > 1.0-SNAPSHOT</version > <properties > <maven.compiler.source > 8</maven.compiler.source > <maven.compiler.target > 8</maven.compiler.target > </properties > <dependencies > <dependency > <groupId > junit</groupId > <artifactId > junit</artifactId > <version > 4.12</version > </dependency > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <version > 8.0.27</version > </dependency > <dependency > <groupId > com.mchange</groupId > <artifactId > c3p0</artifactId > <version > 0.9.5.2</version > </dependency > <dependency > <groupId > javax.servlet</groupId > <artifactId > servlet-api</artifactId > <version > 2.5</version > </dependency > <dependency > <groupId > javax.servlet.jsp</groupId > <artifactId > jsp-api</artifactId > <version > 2.2</version > </dependency > <dependency > <groupId > javax.servlet</groupId > <artifactId > jstl</artifactId > <version > 1.2</version > </dependency > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis</artifactId > <version > 3.5.2</version > </dependency > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis-spring</artifactId > <version > 2.0.2</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-webmvc</artifactId > <version > 5.1.9.RELEASE</version > </dependency > <dependency > <groupId > org.springframework</groupId > <artifactId > spring-jdbc</artifactId > <version > 5.1.9.RELEASE</version > </dependency > <dependency > <groupId > org.projectlombok</groupId > <artifactId > lombok</artifactId > <version > 1.18.20</version > </dependency > </dependencies > </project >
2、数据库
3、maven资源过滤 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <build > <resources > <resource > <directory > src/main/java</directory > <includes > <include > **/*.properties</include > <include > **/*.xml</include > </includes > <filtering > false</filtering > </resource > <resource > <directory > src/main/resources</directory > <includes > <include > **/*.properties</include > <include > **/*.xml</include > </includes > <filtering > false</filtering > </resource > </resources > </build >
6.4、基本架构和配置文件
com.wu.pojo
com.wu.dao
com.wu.service
com.wu.controller
mybatis-config.xml
applicationContext.xml
database.properties
后面出现
spring-service
spring-mvc
spring-dao
mybatis-config.xml
1 2 3 4 5 6 7 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration > </configuration >
applicationContext.xml
1 2 3 4 5 6 7 8 9 10 11 <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns ="http://www.springframework.org/schema/beans" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" > <import resource ="classpath:spring-dao.xml" /> <import resource ="classpath:spring-mvc.xml" /> <import resource ="classpath:spring-service.xml" /> </beans >
database.properties
1 2 3 4 5 jdbc.driver=com.mysql.cj.jdbc.Driver # Mysql8.0+ adds "cj" and time zone to driver: "& serverTimezone=Asia/Shanghai"jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?& serverTimezone=Asia/Shanghai& useSSL=true& useUnicode=true& characterEncoding=utf8 jdbc.username=root jdbc.password=root
6.5、Mybatis层 实体类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 package com.wu.pojo;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data @NoArgsConstructor @AllArgsConstructor public class Books { private int bookID; private String bookName; private int bookCounts; private String detail; }
接口 BookMapper
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package com.wu.dao;import com.wu.pojo.Books;import org.apache.ibatis.annotations.Param;import java.util.List;public interface BookMapper { int addbook (Books books) ; int deleteBookById (@Param("bookID") int id) ; int updateBook (Books books) ; Books queryBookById (@Param("bookID") int id) ; List<Books> queryAllBook () ; }
BookMapper.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace ="com.wu.dao.BookMapper" > <insert id ="addbook" parameterType ="Books" > insert into ssmbuild.books(bookName, bookCounts, detail) values (#{bookName}, #{bookCounts}, #{detail}) </insert > <delete id ="deleteBookById" parameterType ="int" > delete from ssmbuild.books where bookID = #{bookID} </delete > <update id ="updateBook" parameterType ="Books" > update ssmbuild.books set bookName = #{bookName}, bookCounts = #{bookCounts}, detail = #{detail} where bookID = #{bookID} </update > <select id ="queryBookById" resultType ="Books" > select * from ssmbuild.books where bookID = #{bookID} </select > <select id ="queryAllBook" resultType ="Books" > SELECT * from ssmbuild.books </select > </mapper >
mybatis-config.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration > <typeAliases > <package name ="com.wu.pojo" /> </typeAliases > <mappers > <mapper class ="com.wu.dao.BookMapper" /> </mappers > </configuration >
service层 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package com.wu.service;import com.wu.pojo.Books;import org.apache.ibatis.annotations.Param;import java.util.List;public interface BookService { int addbook (Books books) ; int deleteBookById (int id) ; int updateBook (Books books) ; Books queryBookById (int id) ; List<Books> queryAllBook () ; }
BookServiceImpl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 package com.wu.service;import com.wu.dao.BookMapper;import com.wu.pojo.Books;import java.util.List;public class BookServiceImpl implements BookService { private BookMapper bookMapper; public void setBookMapper (BookMapper bookMapper) { this .bookMapper = bookMapper; } @Override public int addbook (Books books) { return bookMapper.addbook(books); } @Override public int deleteBookById (int id) { return bookMapper.deleteBookById(id); } @Override public int updateBook (Books books) { return bookMapper.updateBook(books); } @Override public Books queryBookById (int id) { return bookMapper.queryBookById(id); } @Override public List<Books> queryAllBook () { return bookMapper.queryAllBook(); } }
6.6、Spring层 spring-dao.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns ="http://www.springframework.org/schema/beans" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xmlns:context ="http://www.springframework.org/schema/context" xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd" > <context:property-placeholder location ="classpath:database.properties" /> <bean id ="dataSource" class ="com.mchange.v2.c3p0.ComboPooledDataSource" > <property name ="driverClass" value ="${jdbc.driver}" /> <property name ="jdbcUrl" value ="${jdbc.url}" /> <property name ="user" value ="${jdbc.username}" /> <property name ="password" value ="${jdbc.password}" /> <property name ="maxPoolSize" value ="30" /> <property name ="minPoolSize" value ="10" /> <property name ="autoCommitOnClose" value ="false" /> <property name ="checkoutTimeout" value ="10000" /> <property name ="acquireRetryAttempts" value ="2" /> </bean > <bean id ="sqlSessionFactory" class ="org.mybatis.spring.SqlSessionFactoryBean" > <property name ="dataSource" ref ="dataSource" /> <property name ="configLocation" value ="classpath:mybatis-config.xml" /> </bean > <bean class ="org.mybatis.spring.mapper.MapperScannerConfigurer" > <property name ="sqlSessionFactoryBeanName" value ="sqlSessionFactory" /> <property name ="basePackage" value ="com.wu.dao" /> </bean > </beans >
spring-service.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns ="http://www.springframework.org/schema/beans" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xmlns:context ="http://www.springframework.org/schema/context" xmlns:tx ="http://www.springframework.org/schema/tx" xmlns:aop ="http://www.springframework.org/schema/aop" xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd" > <context:component-scan base-package ="com.wu.service" /> <bean id ="BookServiceImpl" class ="com.wu.service.BookServiceImpl" > <property name ="bookMapper" ref ="bookMapper" /> </bean > <bean id ="transactionManager" class ="org.springframework.jdbc.datasource.DataSourceTransactionManager" > <property name ="dataSource" ref ="dataSource" /> </bean > </beans >
6.7、SpringMVC层 web.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 <?xml version="1.0" encoding="UTF-8" ?> <web-app xmlns ="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version ="4.0" > <servlet > <servlet-name > springmvc</servlet-name > <servlet-class > org.springframework.web.servlet.DispatcherServlet</servlet-class > <init-param > <param-name > contextConfigLocation</param-name > <param-value > classpath:applicationContext.xml</param-value > </init-param > <load-on-startup > 1</load-on-startup > </servlet > <servlet-mapping > <servlet-name > springmvc</servlet-name > <url-pattern > /</url-pattern > </servlet-mapping > <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 > /*</url-pattern > </filter-mapping > <session-config > <session-timeout > 15</session-timeout > </session-config > </web-app >
spring-mvc.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns ="http://www.springframework.org/schema/beans" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xmlns:context ="http://www.springframework.org/schema/context" xmlns:mvc ="http://www.springframework.org/schema/mvc" xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd" > <mvc:annotation-driven /> <mvc:default-servlet-handler /> <bean class ="org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name ="viewClass" value ="org.springframework.web.servlet.view.JstlView" /> <property name ="prefix" value ="/WEB-INF/jsp/" /> <property name ="suffix" value =".jsp" /> </bean > <context:component-scan base-package ="com.wu.controller" /> </beans >
BookController
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 package com.wu.controller;import com.wu.pojo.Books;import com.wu.service.BookService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import java.util.ArrayList;import java.util.Collections;import java.util.List;@Controller @RequestMapping("/book") public class BookController { private final BookService bookService; public BookController (@Qualifier("BookServiceImpl") BookService bookService) { this .bookService = bookService; } @RequestMapping("/allBook") public String list (Model model) { List<Books> list = bookService.queryAllBook(); model.addAttribute("list" , list); return "allBook" ; } }
allBook.jsp
1 2 3 4 5 6 7 8 9 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > 书籍展示</title > </head > <body > <h1 > 书籍展示</h1 > </body > </html >
index.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > 首页</title > </head > <body > <h3 > <a href ="${pageContext.request.contextPath}/book/allBook" > 进入书籍页面</a > </h3 > </body > </html >
排错思路 问题:bean不存在(500) 步骤:
1、查看这个bean注入是否成功! 2、Junit单元测试,看我们的代码是否能够查询出来结果! 3、问题,一定不在我们的底层,是spring出了问题! 4、SpringMVC,整合的时候没调用到我们的service.层的bean
applicationContext.xml没有注入bean
web.xml中,我们也绑定过配置文件!发现问题,我们配置的是Spring-mvc.Xml这里面确实没有service bean,所以报空指针
6.8、查询书籍 index.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > 首页</title > <style > a { text-decoration : none; color : white; font-size : 18px ; } h3 { width : 180px ; height : 38px ; margin : 100px auto; text-align : center; line-height : 38px ; background : pink; border-radius : 5px ; } </style > </head > <body > <h3 > <a href ="${pageContext.request.contextPath}/book/allBook" > 进入书籍页面</a > </h3 > </body > </html >
查找BootStrap CDN,搜索
1 2 3 4 5 6 7 8 9 10 11 <link href ="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel ="stylesheet" > <script src ="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js" > </script > <script src ="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js" > </script >
allbook.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > 书籍展示</title > <%-- BootStrap美化界面 --%> <link href ="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel ="stylesheet" > </head > <body > <div class ="container" > <div class ="row clearfix" > <div class ="col-md-12 column" > <div class ="page-header" > <h1 > <small > 书籍列表 —— 显示所有书籍</small > </h1 > </div > </div > </div > <div class ="row clearfix" > <div class ="col-md-12 column" > <table class ="table table-hover table-striped" > <thead > <tr > <th > 书籍编号</th > <th > 书籍名字</th > <th > 书籍数量</th > <th > 书籍详情</th > <th > 操作</th > </tr > </thead > <%-- 书籍从数据库中查询出来,从这个List中遍历出来:foreach --%> <tbody > <%--<c:forEach var ="book" items ="${requestScope.get('list')}" > --%> <c:forEach var ="book" items ="${requestScope.get('list')}" > <tr > <td > ${book.getBookID()}</td > <td > ${book.getBookName()}</td > <td > ${book.getBookCounts()}</td > <td > ${book.getDetail()}</td > </tr > </c:forEach > </tbody > </table > </div > </div > </div > </body > </html >
6.9、添加书籍 allBook.jsp
1 2 3 4 5 <div class ="row" > <div class ="col-md-4 column" > <a class ="btn btn-primary" href ="${pageContext.request.contextPath}/book/toAddBook" > 新增书籍</a > </div > </div >
BookController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 @RequestMapping("/toAddBook") public String toAddPaper () { return "addBook" ; } @RequestMapping("/addBook") public String addBook (Books books) { System.out.println("addBook=>" +books); bookService.addBook(books); return "redirect:/book/allBook" ; }
addBook.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > 添加书籍</title > <link href ="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel ="stylesheet" > </head > <body > <div class ="container" > <div class ="row clearfix" > <div class ="col-md-12 column" > <div class ="page-header" > <h1 > <small > 新增书籍</small > </h1 > </div > </div > </div > <form action ="${pageContext.request.contextPath}/book/addBook" method ="post" > <div class ="form-group" > <label > 书籍名称:</label > <input type ="text" name ="bookName" class ="form-control" required > </div > <div class ="form-group" > <label > 书籍数量:</label > <input type ="text" name ="bookCounts" class ="form-control" required > </div > <div class ="form-group" > <label > 书籍描述:</label > <input type ="text" name ="detail" class ="form-control" required > </div > <div class ="form-group" > <input type ="submit" class ="form-control" value ="添加" > </div > </form > </div > </body > </html >
结果
6.10、修改书籍 allBook.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 <tbody > <c:forEach var ="book" items ="${requestScope.get('list')}" > <tr > <td > ${book.getBookID()}</td > <td > ${book.getBookName()}</td > <td > ${book.getBookCounts()}</td > <td > ${book.getDetail()}</td > <td > <a href ="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}" > 修改</a > | </td > </tr > </c:forEach > </tbody >
BookController.java
1 2 3 4 5 6 7 @RequestMapping("/toUpdateBook") public String toUpdatePaper (int id, Model model) { Books books = bookService.queryBookById(id); model.addAttribute("books" , books); return "updateBook" ; }
updateBook.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > 修改书籍信息</title > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <link href ="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel ="stylesheet" > </head > <body > <div class ="container" > <div class ="row clearfix" > <div class ="col-md-12 column" > <div class ="page-header" > <h1 > <small > 修改书籍</small > </h1 > </div > </div > </div > <form action ="${pageContext.request.contextPath}/book/" method ="post" > <div class ="form-group" > <label > 书籍名称</label > <input type ="text" name ="bookName" class ="form-control" value ="${QBook.bookName}" required > </div > <div class ="form-group" > <label > 书籍数量</label > <input type ="text" name ="bookCounts" class ="form-control" value ="${QBook.bookCounts}" required > </div > <div class ="form-group" > <label > 书籍描述</label > <input type ="text" name ="detail" class ="form-control" value ="${QBook.detail}" required > </div > <div class ="form-group" > <input type ="submit" class ="form-control" value ="修改" > </div > <%-- <input type ="submit" value ="提交" /> --%> </form > </div >
结果
修改书籍页面 BookController
1 2 3 4 5 6 @RequestMapping("/updateBook") public String updateBook (Books books) { bookService.updateBook(books); return "redirect:/book/allBook" ; }
BookServiceImpl
1 2 3 4 5 @Override public int updateBook (Books books) { System.out.println("BookServiceImpl:updateBook=>" +books); return bookMapper.updateBook(books); }
导入jar包
1 2 3 4 5 <dependency > <groupId > org.aspectj</groupId > <artifactId > aspectjweaver</artifactId > <version > 1.8.14</version > </dependency >
加上事务
spring-service.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns ="http://www.springframework.org/schema/beans" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xmlns:context ="http://www.springframework.org/schema/context" xmlns:tx ="http://www.springframework.org/schema/tx" xmlns:aop ="http://www.springframework.org/schema/aop" xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd" > <context:component-scan base-package ="com.wu.service" /> <bean id ="BookServiceImpl" class ="com.wu.service.BookServiceImpl" > <property name ="bookMapper" ref ="bookMapper" /> </bean > <bean id ="transactionManager" class ="org.springframework.jdbc.datasource.DataSourceTransactionManager" > <property name ="dataSource" ref ="dataSource" /> </bean > <tx:advice id ="txAdvice" transaction-manager ="transactionManager" > <tx:attributes > <tx:method name ="*" propagation ="REQUIRED" /> </tx:attributes > </tx:advice > <aop:config > <aop:pointcut id ="txPointCut" expression ="execution(* com.wu.dao.*.*(..))" /> <aop:advisor advice-ref ="txAdvice" pointcut-ref ="txPointCut" /> </aop:config > </beans >
lib包导入
updateBook.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > 修改书籍信息</title > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <link href ="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel ="stylesheet" > </head > <body > <div class ="container" > <div class ="row clearfix" > <div class ="col-md-12 column" > <div class ="page-header" > <h1 > <small > 修改书籍</small > </h1 > </div > </div > </div > <%-- 出现的问题:我们提交了修改的SQ请求,但是修改失败,初次考虑,是事务问题,配置完华事务,依旧失败!--%> <%-- 看一下SQL语句,能否执行成功:SQL执行失败,修政未完成--%> <form action ="${pageContext.request.contextPath}/book/updateBook" method ="post" > <%--前端传递隐藏域--%> <input type ="hidden" name ="bookID" value ="${books.bookID}" > <div class ="form-group" > <label > 书籍名称</label > <input type ="text" name ="bookName" class ="form-control" value ="${books.bookName}" required > </div > <div class ="form-group" > <label > 书籍数量</label > <input type ="text" name ="bookCounts" class ="form-control" value ="${books.bookCounts}" required > </div > <div class ="form-group" > <label > 书籍描述</label > <input type ="text" name ="detail" class ="form-control" value ="${books.detail}" required > </div > <div class ="form-group" > <input type ="submit" class ="form-control" value ="修改" > </div > </form > </div >
手动添加日志
mybatis-config.xml
1 2 3 4 <settings > <setting name ="logImpl" value ="STDOUT_LOGGING" /> </settings >
6.11、删除书籍 1 2 3 4 5 6 @RequestMapping("/del/{bookId}") public String deleteBook (@PathVariable("bookId") int id) { bookService.deleteBookById(id); return "redirect:/book/allBook" ; }
service和dao层上面都写好了,所以不展示了,和上面修改一样
allBook.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <tbody > <c:forEach var ="book" items ="${requestScope.get('list')}" > <tr > <td > ${book.getBookID()}</td > <td > ${book.getBookName()}</td > <td > ${book.getBookCounts()}</td > <td > ${book.getDetail()}</td > <td > <a href ="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}" > 修改</a > | <a href ="${pageContext.request.contextPath}/book/del/${book.getBookID()}" > 删除</a > </td > </tr > </c:forEach > </tbody >
6.12、查询书籍 BookMapper
1 2 Books queryBookByName (@Param("bookName") String bookName) ;
BookMapper.xml
1 2 3 4 <select id ="queryBookByName" resultType ="Books" > select * from ssmbuild.books where bookName = #{bookName} </select >
BookService
1 2 Books queryBookByName (String bookName) ;
BookServiceImpl
1 2 3 4 @Override public Books queryBookByName (String bookName) { return bookMapper.queryBookByName(bookName); }
BookController
1 2 3 4 5 6 7 8 9 10 @RequestMapping("/queryBook") public String queryBook (String queryBookName,Model model) { Books books = bookService.queryBookByName(queryBookName); System.err.println("books=>" +books); List<Books> list = new ArrayList <Books>(); list.add(books); model.addAttribute("list" ,list); return "allBook" ; }
allBook.jsp
1 2 3 4 5 6 7 8 9 10 11 12 <div class ="row" > <div class ="col-md-4 column" > <a class ="btn btn-primary" href ="${pageContext.request.contextPath}/book/toAddBook" > 新增书籍</a > </div > <div class ="col-md-4 column" > <%-- 查询书籍--%> <form action ="${pageContext.request.contextPath}/book/queryBook" method ="post" style ="float: right" > <input type ="text" name ="queryBookName" class ="form-control" placeholder ="请输入要查询书籍的名称" > <input type ="submit" value ="查询" class ="btn btn-primary" > </form > </div > </div >
结果
报500错误,dao.BookMapper.xml查不到
加上maven资源过滤
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <build > <resources > <resource > <directory > src/main/java</directory > <includes > <include > **/*.properties</include > <include > **/*.xml</include > </includes > <filtering > false</filtering > </resource > <resource > <directory > src/main/resources</directory > <includes > <include > **/*.properties</include > <include > **/*.xml</include > </includes > <filtering > false</filtering > </resource > </resources > </build >
显示全部书籍 allBook.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <div class ="row" > <div class ="col-md-4 column" > <a class ="btn btn-primary" href ="${pageContext.request.contextPath}/book/toAddBook" > 新增书籍</a > <a class ="btn btn-primary" href ="${pageContext.request.contextPath}/book/allBook" > 显示全部书籍</a > </div > <div class ="col-md-8 column" > <%-- 查询书籍--%> <form class ="form-inline" action ="${pageContext.request.contextPath}/book/queryBook" method ="post" style ="float: right" > <span style ="color:red; font-weight:bold" > ${error}</span > <input type ="text" name ="queryBookName" class ="form-control" placeholder ="请输入要查询书籍的名称" required > <input type ="submit" value ="查询" class ="btn btn-primary" > </form > </div > </div >
BookController
1 2 3 4 5 6 7 8 9 10 11 12 13 14 @RequestMapping("/queryBook") public String queryBook (String queryBookName, Model model) { Books books = bookService.queryBookByName(queryBookName); List<Books> list = new ArrayList <>(); list.add(books); if (books == null ) { list=bookService.queryAllBook(); model.addAttribute("error" ,"“" +queryBookName+"”不存在" ); } model.addAttribute("list" , list); return "allBook" ; }
结果
七、Ajax研究 SpringMVC07:Ajax研究
7.1、简介
AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。
AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
Ajax 不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的Web应用程序的技术。
在 2005 年,Google 通过其 Google Suggest 使 AJAX 变得流行起来。Google Suggest能够自动帮你完成搜索单词。
Google Suggest 使用 AJAX 创造出动态性极强的 web 界面:当您在谷歌的搜索框输入关键字时,JavaScript 会把这些字符发送到服务器,然后服务器会返回一个搜索建议的列表。
就和国内百度的搜索框一样!
传统的网页(即不用ajax技术的网页),想要更新内容或者提交一个表单,都需要重新加载整个网页。
使用ajax技术的网页,通过在后台服务器进行少量的数据交换,就可以实现异步局部更新。
使用Ajax,用户可以创建接近本地桌面应用的直接、高可用、更丰富、更动态的Web用户界面。
7.2、伪造Ajax 我们可以使用前端的一个标签来伪造一个ajax的样子。iframe标签
新建一个module :sspringmvc-06-ajax , 导入web支持!
编写一个 ajax-frame.html 使用 iframe 测试,感受下效果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <!DOCTYPE html > <html > <head lang ="en" > <meta charset ="UTF-8" > <title > xiaowu</title > </head > <body > <script type ="text/javascript" > window .onload = function ( ){ var myDate = new Date (); document .getElementById ('currentTime' ).innerText = myDate.getTime (); }; function LoadPage ( ){ var targetUrl = document .getElementById ('url' ).value ; console .log (targetUrl); document .getElementById ("iframePosition" ).src = targetUrl; } </script > <div > <p > 请输入要加载的地址:<span id ="currentTime" > </span > </p > <p > <input id ="url" type ="text" value ="https://www.baidu.com/" /> <input type ="button" value ="提交" onclick ="LoadPage()" > </p > </div > <div > <h3 > 加载页面位置:</h3 > <iframe id ="iframePosition" style ="width: 100%;height: 500px;" > </iframe > </div > </body > </html >
使用IDEA开浏览器测试一下!
利用AJAX可以做:
注册时,输入用户名自动检测用户是否已经存在。
登陆时,提示用户名密码错误
删除数据行时,将行ID发送到后台,后台在数据库中删除,数据库删除成功后,在页面DOM中将数据行也删除。
…等等
7.3、jQuery.ajax
纯JS原生实现Ajax我们不去讲解这里,直接使用jquery提供的,方便学习和使用,避免重复造轮子,有兴趣的同学可以去了解下JS原生XMLHttpRequest !
Ajax的核心是XMLHttpRequest对象(XHR)。XHR为向服务器发送请求和解析服务器响应提供了接口。能够以异步方式从服务器获取新数据。
jQuery 提供多个与 AJAX 有关的方法。
通过 jQuery AJAX 方法,您能够使用 HTTP Get 和 HTTP Post 从远程服务器上请求文本、HTML、XML 或 JSON – 同时您能够把这些外部数据直接载入网页的被选元素中。
jQuery 不是生产者,而是大自然搬运工。
jQuery Ajax本质就是 XMLHttpRequest,对他进行了封装,方便调用!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 jQuery.ajax(...) 部分参数: url:请求地址 type:请求方式,GET、POST(1.9.0之后用method) headers:请求头 data:要发送的数据 contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8") async:是否异步 timeout:设置请求超时时间(毫秒) beforeSend:发送请求前执行的函数(全局) complete:完成之后执行的回调函数(全局) success:成功之后执行的回调函数(全局) error:失败之后执行的回调函数(全局) accepts:通过请求头发送给服务器,告诉服务器当前客户端可接受的数据类型 dataType:将服务器端返回的数据转换成指定类型 "xml": 将服务器端返回的内容转换成xml格式 "text": 将服务器端返回的内容转换成普通文本格式 "html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。 "script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式 "json": 将服务器端返回的内容转换成相应的JavaScript对象 "jsonp": JSONP 格式使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数
我们来个简单的测试,使用最原始的HttpServletResponse处理 , .最简单 , 最通用
配置web.xml 和 springmvc的配置文件【记得静态资源过滤和注解驱动配置上】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 <?xml version="1.0" encoding="UTF8" ?> <beans xmlns ="http://www.springframework.org/schema/beans" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xmlns:context ="http://www.springframework.org/schema/context" xmlns:mvc ="http://www.springframework.org/schema/mvc" xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd" > <context:component-scan base-package ="com.wu.controller" /> <mvc:default-servlet-handler /> <mvc:annotation-driven > <mvc:message-converters register-defaults ="true" > <bean class ="org.springframework.http.converter.StringHttpMessageConverter" > <constructor-arg value ="UTF-8" /> </bean > <bean class ="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" > <property name ="objectMapper" > <bean class ="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean" > <property name ="failOnEmptyBeans" value ="false" /> </bean > </property > </bean > </mvc:message-converters > </mvc:annotation-driven > <bean class ="org.springframework.web.servlet.view.InternalResourceViewResolver" id ="InternalResourceViewResolver" > <property name ="prefix" value ="/WEB-INF/jsp/" /> <property name ="suffix" value =".jsp" /> </bean > </beans >
编写一个AjaxController
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 package com.wu.controller;import com.sun.deploy.net.HttpResponse;import com.sun.org.glassfish.gmbal.ParameterNames;import lombok.SneakyThrows;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@RestController public class AjaxController { @RequestMapping("/t1") public String test () { System.out.println("进入" ); return "hello" ; } @RequestMapping("/a1") public void a1 (String name, HttpServletResponse response) throws IOException { System.out.println("a1:param=>" +name); if ("xiaowu" .equals(name)) { response.getWriter().print("true" ); } else { response.getWriter().print("false" ); } } }
导入jquery , 可以使用在线的CDN , 也可以下载导入
1 2 <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script src="$ {pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>
编写index.jsp测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > Login</title > </head > <script src ="${pageContext.request.contextPath}/statics/js/jquery-3.6.4.js" > </script > <script > function a ( ) { $.post ({ url : "${pageContext.request.contextPath}/a1" , data : {"name" : $("username" ).val ()}, success :function (data,status ){ console .log ("data=" +data); console .log ("status=" +status); } }); } </script > <body > <%--失去焦点的时候,发起一个请求(携带信息)到后台--%> 用户名:<input type ="text" id ="username" onblur ="a()" > </body > </html >
启动tomcat测试!打开浏览器的控制台,当我们鼠标离开输入框的时候,可以看到发出了一个ajax的请求!是后台返回给我们的结果!测试成功!
7.4、Springmvc实现
实体类user(使用了lombok插件,可以自己写实现类方法
1 2 3 4 5 6 7 8 9 10 @Data @AllArgsConstructor @NoArgsConstructor public class User { private String name; private int age; private String sex; }
我们来获取一个集合对象,展示到前端页面
1 2 3 4 5 6 7 8 @RequestMapping("/a2") public List<User> ajax2 () { List<User> list = new ArrayList <User>(); list.add(new User ("xiaowu1" ,3 ,"男" )); list.add(new User ("xiaowu2" ,3 ,"男" )); list.add(new User ("xiaowu3" ,3 ,"男" )); return list; }
前端页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > Title</title > <script src ="https://code.jquery.com/jquery-3.1.1.min.js" > </script > </head > <body > <input type ="button" value ="加载数据" id ="btn" > <table > <thead > <tr > <td > 姓名</td > <td > 年龄</td > <td > 性别</td > </tr > </thead > <tbody id ="content" > <%--数据:后台--%> </tbody > </table > </body > <script > $(function ( ) { $("#btn" ).click (function ( ) { $.post ("${pageContext.request.contextPath}/a2" , function (data ) { console .log (data[0 ].name ); let html = "" ; for (let i = 0 ; i < data.length ; i++) { html += `<tr> <td>${"${data[i].name}" } </td> <td>${"${data[i].age}" } </td> <td>${"${data[i].sex}" } </td> </tr>` } $("#content" ).html (html) console .log (html) }) }) }) </script > </html >
成功实现了数据回显!可以体会一下Ajax的好处!
7.5、注册提示效果
我们写一个Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 @RequestMapping("/a3") public String ajax3 (String name,String pwd) { String msg = "" ; if (name!=null ){ if ("admin" .equals(name)){ msg = "OK" ; }else { msg = "用户名输入错误" ; } } if (pwd!=null ){ if ("123456" .equals(pwd)){ msg = "OK" ; }else { msg = "密码输入有误" ; } } return msg; }
前端页面 login.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > ajax</title > <script src ="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js" > </script > <script > function a1 ( ){ $.post ({ url :"${pageContext.request.contextPath}/a3" , data :{'name' :$("#name" ).val ()}, success :function (data ) { if (data.toString ()=='OK' ){ $("#userInfo" ).css ("color" ,"green" ); }else { $("#userInfo" ).css ("color" ,"red" ); } $("#userInfo" ).html (data); } }); } function a2 ( ){ $.post ({ url :"${pageContext.request.contextPath}/a3" , data :{'pwd' :$("#pwd" ).val ()}, success :function (data ) { if (data.toString ()=='OK' ){ $("#pwdInfo" ).css ("color" ,"green" ); }else { $("#pwdInfo" ).css ("color" ,"red" ); } $("#pwdInfo" ).html (data); } }); } </script > </head > <body > <p > 用户名:<input type ="text" id ="name" onblur ="a1()" /> <span id ="userInfo" > </span > </p > <p > 密码:<input type ="text" id ="pwd" onblur ="a2()" /> <span id ="pwdInfo" > </span > </p > </body > </html >
记得处理json乱码问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <mvc:annotation-driven > <mvc:message-converters register-defaults ="true" > <bean class ="org.springframework.http.converter.StringHttpMessageConverter" > <constructor-arg value ="UTF-8" /> </bean > <bean class ="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" > <property name ="objectMapper" > <bean class ="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean" > <property name ="failOnEmptyBeans" value ="false" /> </bean > </property > </bean > </mvc:message-converters > </mvc:annotation-driven >
效果:
测试一下效果,动态请求响应,局部刷新,就是如此!
7.6、获取baidu接口Demo
JSONP.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 <!DOCTYPE HTML > <html > <head > <meta http-equiv ="Content-Type" content ="text/html; charset=utf-8" > <title > JSONP百度搜索</title > <style > #q { width : 500px ; height : 30px ; border :1px solid #ddd ; line-height : 30px ; display : block; margin : 0 auto; padding : 0 10px ; font-size : 14px ; } #ul { width : 520px ; list-style : none; margin : 0 auto; padding : 0 ; border :1px solid #ddd ; margin-top : -1px ; display : none; } #ul li { line-height : 30px ; padding : 0 10px ; } #ul li :hover { background-color : #f60 ; color : #fff ; } </style > <script > function demo (data ){ var Ul = document .getElementById ('ul' ); var html = '' ; if (data.s .length ) { Ul .style .display = 'block' ; for (var i = 0 ;i<data.s .length ;i++){ html += '<li>' +data.s [i]+'</li>' ; } Ul .innerHTML = html; } } window .onload = function ( ){ var Q = document .getElementById ('q' ); var Ul = document .getElementById ('ul' ); Q.onkeyup = function ( ){ if (this .value != '' ) { var script = document .createElement ('script' ); script.src = 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=' +this .value +'&cb=demo' ; document .body .appendChild (script); } } } </script > </head > <body > <input type ="text" id ="q" /> <ul id ="ul" > </ul > </body > </html >
测试
八、拦截器 8.1、概述
SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。
开发者可以自己定义一些拦截器来实现特定的功能。
过滤器与拦截器的区别: 拦截器是AOP思想的具体应用。
过滤器
servlet规范中的一部分,任何javaweb工程都可以使用
在url-pattern中配置了/*之后,可以对所有要访问的资源进行拦截
拦截器
拦截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用
拦截器只会拦截访问的控制器方法, 如果访问的是jsp/html/css/image/js是不会进行拦截的
8.2、自定义拦截器
新建一个Moudule , springmvc-Interceptor , 添加web支持
配置web.xml 和 springmvc-servlet.xml 文件
编写一个拦截器(必须实现 HandlerInterceptor 接口)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 package com.wu.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 MyInterceptor implements HandlerInterceptor { public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("===========处理前===========" ); return true ; } public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("===========处理后===========" ); } public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("===========清理===========" ); } }
在springmvc的配置文件中配置拦截器
1 2 3 4 5 6 7 8 9 <mvc:interceptors > <mvc:interceptor > <mvc:mapping path ="/**" /> <bean class ="com.wu.Interceptor.MyInterceptor" /> </mvc:interceptor > </mvc:interceptors >
编写一个Controller,接收请求
1 2 3 4 5 6 7 8 9 10 11 12 13 package com.wu.controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestController public class TestController { @GetMapping("/t1") public String test () { System.out.println("TestController.test" ); return "ok" ; } }
启动tomcat 测试一下!(http://localhost:8888/t1 )
8.3、验证用户是否登录 (认证用户) 实现思路
有一个登陆页面,需要写一个controller访问页面。
登陆页面有一提交表单的动作。需要在controller中处理。判断用户名密码是否正确。如果正确,向session中写入用户信息。返回登陆成功。
拦截用户请求,判断用户是否登陆。如果用户已经登陆。放行, 如果用户未登陆,跳转到登陆页面
测试:
编写一个登陆页面 login.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > 登录</title > </head > <body > <%--在web-inf下面的所有页面或者资源,只能通过controller或者Servlet进行访问--%> <h1 > 登录页面</h1 > <form action ="${pageContext.request.contextPath}/user/login" method ="post" > 用户名:<input type ="text" name ="username" > 密码:<input type ="text" name ="password" > <input type ="submit" value ="提交" > </form > </body > </html >
编写一个Controller处理请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 package com.wu.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import javax.servlet.http.HttpSession;@Controller @RequestMapping("/user") public class LoginController { @RequestMapping("/main") public String main () { return "main" ; } @RequestMapping("/goLogin") public String login () { return "login" ; } @RequestMapping("/login") public String login (HttpSession session, String username, String password, Model model) { session.setAttribute("userLoginInfo" ,username); model.addAttribute("password" ,password); model.addAttribute("username" ,username); return "main" ; } @RequestMapping("/goOut") public String goOut (HttpSession sessionl) { sessionl.removeAttribute("userLoginInfo" ); return "login" ; } }
编写一个登陆成功的页面 main.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > 首页</title > </head > <body > <h1 > 首页</h1 > <span > ${password}</span > <span > ${username}</span > <p > <a href ="${pageContext.request.contextPath}/user/goOut" > 注销</a > </p > </body > </html >
在 index 页面上测试跳转!启动Tomcat 测试,未登录也可以进入主页!
1 2 3 4 5 6 7 8 9 10 11 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html > <head > <title > index</title > </head > <body > <h1 > <a href ="${pageContext.request.contextPath}/user/goLogin" > 登录页面</a > </h1 > <h1 > <a href ="${pageContext.request.contextPath}/user/main" > 首页</a > </h1 > </body > </html >
编写用户登录拦截器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 package com.wu.Interceptor;import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;public class LoginInterceptor implements HandlerInterceptor { public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); if (request.getRequestURI().contains("goLogin" )) { return true ; } if (request.getRequestURI().contains("login" )) { return true ; } if (session.getAttribute("userLoginInfo" ) != null ) { return true ; } request.getRequestDispatcher("/WEB-INF/jsp/login.jsp" ).forward(request,response); return false ; } }
在Springmvc的配置文件中注册拦截器
1 2 3 4 5 6 7 <mvc:interceptors > <mvc:interceptor > <mvc:mapping path ="/user/**" /> <bean id ="loginInterceptor" class ="com.wu.Interceptor.LoginInterceptor" /> </mvc:interceptor > </mvc:interceptors >
再次重启Tomcat测试!
OK,测试登录拦截功能无误.
九、文件上传和下载 9.1、准备工作
文件上传是项目开发中最常见的功能之一 ,springMVC 可以很好的支持文件上传。
SpringMVC上下文中默认没有装配MultipartResolver,因此默认情况下其不能处理文件上传工作。如果想使用Spring的文件上传功能,则需要在上下文中配置MultipartResolver。
前端表单要求:为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data。只有在这样的情况下,浏览器才会把用户选择的文件以二进制数据发送给服务器;
对表单中的 enctype 属性做个详细的说明:
application/x-www=form-urlencoded:默认方式,只处理表单域中的 value 属性值,采用这种编码方式的表单会将表单域中的值处理成 URL 编码方式。
multipart/form-data:这种编码方式会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数中,不会对字符编码。
text/plain:除了把空格转换为 “+” 号外,其他字符都不做编码处理,这种方式适用直接通过表单发送邮件。
1 2 3 4 <form action ="" enctype ="multipart/form-data" method ="post" > <input type ="file" name ="file" /> <input type ="submit" > </form >
一旦设置了enctype为multipart/form-data,浏览器即会采用二进制流的方式来处理表单数据,而对于文件上传的处理则涉及在服务器端解析原始的HTTP响应。在2003年,Apache Software Foundation发布了开源的Commons FileUpload组件,其很快成为Servlet/JSP程序员上传文件的最佳选择
Servlet3.0规范已经提供方法来处理文件上传,但这种上传需要在Servlet中完成。
而Spring MVC则提供了更简单的封装。
Spring MVC为文件上传提供了直接的支持,这种支持是用即插即用的MultipartResolver实现的。
Spring MVC使用Apache Commons FileUpload技术实现了一个MultipartResolver实现类:
CommonsMultipartResolver。因此,SpringMVC的文件上传还需要依赖Apache Commons FileUpload的组件。
9.2、文件上传
导入文件上传的jar包,commons-fileupload , Maven会自动帮我们导入他的依赖包 commons-io包;
1 2 3 4 5 6 7 8 9 10 11 12 <dependency > <groupId > commons-fileupload</groupId > <artifactId > commons-fileupload</artifactId > <version > 1.3.3</version > </dependency > <dependency > <groupId > javax.servlet</groupId > <artifactId > javax.servlet-api</artifactId > <version > 4.0.1</version > </dependency >
配置bean:multipartResolver
1 2 3 4 5 6 7 8 <bean id ="multipartResolver" class ="org.springframework.web.multipart.commons.CommonsMultipartResolver" > <property name ="defaultEncoding" value ="utf-8" /> <property name ="maxUploadSize" value ="10485760" /> <property name ="maxInMemorySize" value ="40960" /> </bean >
【注意!!!这个bena的id必须为:multipartResolver , 否则上传文件会报400的错误!在这里栽过坑,教训! 】
CommonsMultipartFile 的 常用方法:
String getOriginalFilename():获取上传文件的原名
InputStream getInputStream():获取文件流
void transferTo(File dest):将上传文件保存到一个目录文件中
我们去实际测试一下
编写前端页面
1 2 3 4 <form action ="/upload" enctype ="multipart/form-data" method ="post" > <input type ="file" name ="file" /> <input type ="submit" value ="upload" > </form >
Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 package com.wu.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.multipart.commons.CommonsMultipartFile;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.*;import java.net.URLEncoder;@RestController public class FileController { @RequestMapping("/upload") public String fileUpload (@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException { String uploadFileName = file.getOriginalFilename(); if ("" .equals(uploadFileName)){ return "redirect:/index.jsp" ; } System.out.println("上传文件名 : " +uploadFileName); String path = request.getServletContext().getRealPath("/upload" ); File realPath = new File (path); if (!realPath.exists()){ realPath.mkdir(); } System.out.println("上传文件保存地址:" +realPath); InputStream is = file.getInputStream(); OutputStream os = new FileOutputStream (new File (realPath,uploadFileName)); int len=0 ; byte [] buffer = new byte [1024 ]; while ((len=is.read(buffer))!=-1 ){ os.write(buffer,0 ,len); os.flush(); } os.close(); is.close(); return "redirect:/index.jsp" ; } }
测试上传文件
采用file.Transto 来保存上传的文件
编写Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 @RequestMapping("/upload2") public String fileUpload2 (@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException { String path = request.getServletContext().getRealPath("/upload" ); File realPath = new File (path); if (!realPath.exists()){ realPath.mkdir(); } System.out.println("上传文件保存地址:" +realPath); file.transferTo(new File (realPath +"/" + file.getOriginalFilename())); return "redirect:/index.jsp" ; }
前端表单提交地址修改
访问提交测试
9.3、文件下载 文件下载步骤:
设置 response 响应头
读取文件 – InputStream
写出文件 – OutputStream
执行操作
关闭流 (先开后关)
代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 @RequestMapping(value="/download") public String downloads (HttpServletResponse response ,HttpServletRequest request) throws Exception{ String path = request.getServletContext().getRealPath("/upload" ); String fileName = "基础语法.jpg" ; response.reset(); response.setCharacterEncoding("UTF-8" ); response.setContentType("multipart/form-data" ); response.setHeader("Content-Disposition" , "attachment;fileName=" +URLEncoder.encode(fileName, "UTF-8" )); File file = new File (path,fileName); InputStream input=new FileInputStream (file); OutputStream out = response.getOutputStream(); byte [] buff =new byte [1024 ]; int index=0 ; while ((index= input.read(buff))!= -1 ){ out.write(buff, 0 , index); out.flush(); } out.close(); input.close(); return null ; }
前端
1 <a href ="/download" > 点击下载</a >
测试,文件下载OK