SpringMVC使用手册
本文最后更新于:2021年1月8日 下午
一、回顾MVC
- 用户发请求;
- Servlet接收请求数据,并调用响应的业务逻辑方法;
- 业务处理完毕后,service层返回更新后的数据给Servlet层;
- Servlet转向JSP,由JSP来渲染页面;
- 响应给前端更新后的页面
MVC:指Model模型、View视图和Controller控制器的缩写
Model
:dao、service层等,业务逻辑,保存数据状态View
:html、jsp等,显示页面Controller
:Servlet等,取得表单数据,调用业务逻辑,转向指定页面
dao层连接数据库;service层调用dao层去执行一些具体的业务;Servlet接收jsp/html等前端的数据,并将数据交给service层处理,之后service层将处理结果返回给servlet层,由servlet控制跳转到哪个界面。
二、回顾Servlet
新建maven工程当父工程,添加pom依赖,之后新建maven module,右键添加框架支持,选择web application 4.0版本,即可获得一个web-app应用module了。
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.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>
- 编写Servlet类,处理用户请求
package com.gaowl.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 {
// 1.获取前端参数
String method = req.getParameter("method"); // 前端的表单中,有一个字段为method,此处我们获取method,并根据其内容做对应的处理
if (method.equals("add")){
req.getSession().setAttribute("msg","执行了add方法");
}
if (method.equals("delete")){
req.getSession().setAttribute("msg","执行了delete方法");
}
// 2.调用业务层
// 3.视图转发或者重定向
req.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
- 编写前端文件
WEB-INF/jsp/hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>正在学习Spring和Servlet...2021.1.4</title>
</head>
<body>
${msg}
</body>
</html>
- 在web.xml中注册Servlet
<?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>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.gaowl.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name> <!--和上面名称对应-->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
- 配置tomcat,测试即可
http://localhost:8080/SpringMVC_01_Servlet_war_exploded/hello?method=add
三、SpringMVC介绍
1)优点
- 轻量级,简单易学
- 高效 , 基于请求响应的MVC框架
- 与Spring兼容性好,无缝结合
- 约定优于配置
- 功能强大:支持RESTful、数据验证、格式化、拦截器、主题等等
2)执行原理
Spring MVC框架像许多其他MVC框架一样, 以请求为驱动 , 围绕一个中心Servlet分派请求及提供其他功能。
这个中心Servlet指的是DispatcherServlet
,它继承自HttpServlet 基类,并将请求分发到不同的处理器。
上图为SpringMVC的一个较完整的流程图,实线表示SpringMVC框架提供的技术,不需要开发者实现,虚线表示需要开发者自己实现。
DispatcherServlet
表示前置控制器,是整个SpringMVC的控制中心。用户发出请求,DispatcherServlet接收并拦截请求HandlerMapping
:处理器映射。DispatcherServlet调用HandlerMapping,根据请求url查找Handler。HandlerExecution
:具体的Handler,其根据请求url查找控制器,如上述url中被查找控制器为:hello。HandlerExecution
将解析后的信息传递给DispatcherServlet。HandlerAdapter
处理器适配器,按照特定的规则去执行Handler。Handler
让具体的Controller执行。Controller
将具体的执行信息返回给HandlerAdapter,如ModelAndView
。HandlerAdapter
将 视图逻辑名或模型 传递给DispatcherServlet。DispatcherServlet
调用视图解析器(ViewResolver
)来解析HandlerAdapter传递的逻辑视图名。ViewResolver
视图解析器,将解析的逻辑视图名传给DispatcherServlet。DispatcherServlet
根据视图解析器解析的视图结果,调用具体的视图。- 将最终视图呈现给用户。
四、使用注解开发
1)初始化
导入pom依赖,创建lib文件夹并导入相关库,通过build防止资源过滤
<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>
2)配置 web.xml
<?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>
<!-- 1.注册DispatcherServlet -->
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 2.通过初始化参数关联 SpringMVC配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!-- 3.设定启动顺序,数字越小,启动越早 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern> <!--所有请求都会被springmvc拦截 -->
</servlet-mapping>
</web-app>
<url-pattern>/</url-pattern>
:匹配所有的请求;(不包括.jsp,即.jsp 不会进入spring的 DispatcherServlet类)<url-pattern>/*</url-pattern>
:匹配所有的请求;(包括.jsp)
3)编写SpringMVC配置文件
springmvc-servlet.xml
<?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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 1.自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
<!-- 2.让Spring MVC不处理静态资源(.css .js .html .mp4等) -->
<!-- 3.通过mvc注解驱动自动配置DefaultAnnotationHandlerMapping 和AnnotationMethodHandlerAdapter实例 -->
<context:component-scan base-package="com.gaowl.controller"/>
<mvc:default-servlet-handler />
<mvc:annotation-driven />
<!--使用SpringMVC必须配置 处理器映射器、处理器适配器和视图解析器,
前两者通过 开启注解驱动 后自动配置,因此,只需要配置视图解析器即可-->
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀和后缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
4)创建控制器类
package com.gaowl.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/HelloController")
public class HelloController {
//真实访问地址 : 项目名/HelloController/hello
@RequestMapping("/hello")
public String sayHello(Model model){
model.addAttribute("msg","hello,this is SpringMVC"); // 封装数据
return "hello"; // 视图名,其会被视图解析器拼接为web-inf/jsp/hello.jsp
}
@RequestMapping("tv")
public String testView(Model model){
model.addAttribute("msg","测试多个路径指向同一个视图");
return "hello";
}
}
@Controller
注解可以使Spring IOC容器初始化时自动扫描到该控制器类@RequestMapping
注解为映射请求路径,这里类与方法上都有映射注解,所以访问路径应该是/HelloController/hello
;方法中声明Model类型的参数是为了把Action中的数据带到视图中;
- 方法返回的结果是视图名hello,加上配置文件中的前后缀变成
WEB-INF/jsp/hello.jsp
。
5)创建视图并测试
在WEB-INF/ jsp目录下创建hello.jsp
视图文件, 其可以直接取出并展示从Controller带回的信息;
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
五、RESTFul风格
采用传统方法操作资源时,url一般为http://127.0.0.1/item/queryItem.action?id=1
这种;
RestFul风格隐藏了变量名称,如http://127.0.0.1/item/1
,同一个请求地址可以实现不同的功能
- 在
@RequestMapping
中通过{}
指定变量,之后再通过@PathVariable
获取到具体的数据; - 当地址栏请求提供的数据 和 限定数据类型不一致时,会报400错误。
- 此外,可以通过
method
属性指定请求的类型,如GET、POST、DELETE等。@RequestMapping(value = "/hello",method = {RequestMethod.GET})
- 所有的地址栏请求 默认为HTTP GET 类型
- 方法级别的注解,除了RequestMapping外,还有@GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping等,其中GetMapping用的比较多,其等价于
@RequestMapping(value = "/hello",method = {RequestMethod.GET})
package com.gaowl.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RestFulController {
//映射访问路径
@RequestMapping("/commit/{p1}/{p2}")
public String index(@PathVariable int p1, @PathVariable int p2, Model model){
int result = p1+p2;
//Spring MVC会自动实例化一个Model对象用于向视图中传值
model.addAttribute("msg", "结果:"+result);
//返回视图位置
return "hello";
}
}
六、结果跳转和数据处理
1)结果转发和重定向
ModelAndVIew
:最终跳转的视图页面为{视图解析器中前缀} + viewName +{视图解析器中后缀}
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀、后缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//返回一个模型视图对象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
ServletAPI
:其可以不需要视图解析器
@Controller
public class ResultGo {
// 输出信息
@RequestMapping("/result/t1")
public void test1(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
rsp.getWriter().println("Hello,Spring BY servlet API");
}
// 转发
@RequestMapping("/result/t2")
public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception {
req.setAttribute("msg","测试转发请求/result/t2");
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp);
}
// 重定向
@RequestMapping("/result/t3")
public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
rsp.sendRedirect("/index.jsp");
}
}
SpringMVC
:重定向无需视图解析器;转发时,若无视图解析器,需保证文件可以访问到
// 有视图解析器
@Controller
public class ResultSpringMVC2 {
@RequestMapping("/rsm2/t1")
public String test1(){
//转发
return "test";
}
@RequestMapping("/rsm2/t2")
public String test2(){
//重定向
return "redirect:/index.jsp";
//return "redirect:hello.do"; //hello.do为另一个请求/
}
}
// 无视图解析器的控制器类实现
@Controller
public class ResultSpringMVC {
@RequestMapping("/rsm/t1")
public String test1(){
//转发
return "/index.jsp";
}
@RequestMapping("/rsm/t2")
public String test2(){
//转发二
return "forward:/index.jsp";
}
@RequestMapping("/rsm/t3")
public String test3(){
//重定向
return "redirect:/index.jsp";
}
}
2)处理提交数据
- 当提交的域名称和处理方法的参数名不一致时,手动指定参数名
@RequestParam("username")
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
System.out.println(name);
return "hello";
}
- 当提交的数据是一个对象时,接收方法的参数直接也设置成对象即可。
- 前端传递的参数名和对象名必须一致,否则会为null
@RequestMapping("/user")
public String user(User user){
System.out.println(user);
return "hello";
}
3)数据显示到前端
- ModelAndView
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//返回一个模型视图对象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
- ModelMap:继承了 LinkedMap ,除了实现了自身的一些方法外,同时还有 LinkedMap 的方法和特性;
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap model){
model.addAttribute("name",name); //相当于req.setAttribute("name",name);
return "hello";
}
- Model:方法较少,但简单好用啊!
@RequestMapping("/ct2/hello")
public String hello(@RequestParam("username") String name, Model model){
model.addAttribute("msg",name);
return "test";
}
4)中文乱码问题
- 在首页 提交表单,
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
$END$
<form action="e/t" method="post">
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
- 编写其控制器类
package com.gaowl.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class EncodingController {
@RequestMapping("/e/t")
public String test(Model model, String name){
model.addAttribute("msg",name);
return "hello";
}
}
- 此时,测试提交请求会出现中文乱码问题。解决方案非常简单,在web.xml中导入Spring自带的拦截器即可
<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文件然后对其进行相应的处理,不带的话就不会拦截-->
</filter-mapping>
- 若还是乱码(比如get请求等),可尝试下述代码(没试过,占个坑,但愿这辈子都用不到)
package com.kuang.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;
/**
* 解决get和post请求 全部乱码的过滤器
*/
public class GenericEncodingFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//处理response的字符编码
HttpServletResponse myResponse=(HttpServletResponse) response;
myResponse.setContentType("text/html;charset=UTF-8");
// 转型为与协议相关对象
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
// 对request包装增强
HttpServletRequest myrequest = new MyRequest(httpServletRequest);
chain.doFilter(myrequest, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
//自定义request对象,HttpServletRequest的包装类
class MyRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
//是否编码的标记
private boolean hasEncode;
//定义一个可以传入HttpServletRequest对象的构造函数,以便对其进行装饰
public MyRequest(HttpServletRequest request) {
super(request);// super必须写
this.request = request;
}
// 对需要增强方法 进行覆盖
@Override
public Map getParameterMap() {
// 先获得请求方式
String method = request.getMethod();
if (method.equalsIgnoreCase("post")) {
// post请求
try {
// 处理post乱码
request.setCharacterEncoding("utf-8");
return request.getParameterMap();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else if (method.equalsIgnoreCase("get")) {
// get请求
Map<String, String[]> parameterMap = request.getParameterMap();
if (!hasEncode) { // 确保get手动编码逻辑只运行一次
for (String parameterName : parameterMap.keySet()) {
String[] values = parameterMap.get(parameterName);
if (values != null) {
for (int i = 0; i < values.length; i++) {
try {
// 处理get乱码
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;
}
}
七、JSON交互处理
后端:提供接口和数据
前端:独立部署,对前端数据进行渲染
JSON 是 JavaScript 对象的字符串表示法,它使用文本表示一个 JS 对象的信息,本质是一个字符串。
// javaScript对象
var obj = {a: 'Hello', b: 'World'}; //这是一个对象,注意键名也是可以使用引号包裹的
// json字符串
var json = '{"a": "Hello", "b": "World"}';
1)JSON字符串和对象转换
<script type="text/javascript">
//编写一个js的对象
var user = {
name:"秦疆",
age:3,
sex:"男"
};
//将js对象转换成json字符串
var str = JSON.stringify(user);
console.log(str);
//将json字符串转换为js对象
var user2 = JSON.parse(str);
console.log(user2.age,user2.name,user2.sex);
</script>
2)代码测试
- 导入库文件
<?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_Kuang</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>SpringMVC-05-json</artifactId>
<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>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
- 配置web.xml文件
<?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">
<!--1.注册servlet-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--通过初始化参数指定SpringMVC配置文件的位置,进行关联-->
<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>
<!--所有请求都会被springmvc拦截 -->
<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>
</filter-mapping>
</web-app>
- 配置Spring的核心配置文件
<?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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
<context:component-scan base-package="com.gaowl.controller"/>
<!-- 统一解决json中文乱码问题 -->
<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>
- 编写实体类User
package com.gaowl.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;
}
- 编写Controller
- 若有Controller注释,且web.xml中配置了视图解析器,当访问RequestMappering所对应的地址时,所调用的方法返回视图名,跳转到相应的视图
- 若想不跳转视图,仅返回字符串,可以在方法上加
@ResponseBody
注解,或者在类上面通过@RestController
替换掉原先的@Controller
- jackson库:
- 将java对象转换为字符串:
new ObjectMapper().writeValueAsString(user)
- 将java对象转换为字符串:
- FastJSON库:
- java对象 和 JSON字符串 互转:
JSON.toJSONString(user1)
、JSON.parseObject(s2, User.class)
- Java对象 和 JSON对象 互转:
(JSONObject) JSON.toJSON(user1)
、JSON.toJavaObject(jsonObject, User.class)
- java对象 和 JSON字符串 互转:
package com.gaowl.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gaowl.pojo.User;
import org.junit.Test;
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.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
@RestController
// @Controller
public class UserController {
// 通过指定produces属性解决中文乱码问题
// @RequestMapping(value = "/json1",produces = "application/json;charset=utf-8")
@RequestMapping("/j1")
// @ResponseBody
public String json1() throws JsonProcessingException {
//创建一个jackson的对象映射器,用来解析数据
ObjectMapper mapper = new ObjectMapper();
User user = new User("阿龙1号", 23, "男");
String str = mapper.writeValueAsString(user); // 通过jackson库将 User对象 解析为 json字符串
//由于@ResponseBody注解,不再返回视图,这里会将str转成json格式返回;十分方便
return str;
}
@RequestMapping("/j2")
public String json2() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
User user1 = new User("阿龙1号", 23, "男");
User user2 = new User("阿龙2号", 23, "男");
User user3 = new User("阿龙3号", 23, "男");
User user4 = new User("阿龙4号", 23, "男");
ArrayList<User> list = new ArrayList<>();
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
String str = mapper.writeValueAsString(list);
return str;
}
@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");
String str = mapper.writeValueAsString(sdf.format(date));
return str;
}
@Test
public void FastJsonDemo(){
User user1 = new User("1号", 3, "男");
User user2 = new User("2号", 3, "男");
User user3 = new User("3号", 3, "男");
User user4 = new User("4号", 3, "男");
ArrayList<User> list = new ArrayList<>();
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
System.out.println(list+"\n");
// java对象 转 JSON字符串
String s1 = JSON.toJSONString(list);
String s2 = JSON.toJSONString(user1);
System.out.println(s1+"\n"+s2+"\n");
// JSON字符串 转 Java对象
ArrayList<User> array_parse = JSON.parseObject(s1, ArrayList.class);
User user_parse = JSON.parseObject(s2, User.class);
System.out.println(array_parse); // TODO列表内部不是User类型的数据....
System.out.println(user_parse+"\n");
// Java对象 转 JSON对象
JSONObject jsonObject = (JSONObject) JSON.toJSON(user1);
System.out.println(jsonObject+"\n");
// JSON对象 转 Java对象
User user = JSON.toJavaObject(jsonObject, User.class);
System.out.println(user);
}
}
八、整合SSM框架(!!!重点掌握)
1)构建MySQL数据库
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,'从进门到进牢');
2)基本环境配置
- 新建maven空项目,添加web支持,导入相关pom依赖,并配置静态资源过滤,添加lib文件夹
<?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_kuang</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 安装依赖项:Junit、mysql数据库驱动、连接池、servlet、jsp、mybatis、spring等等 -->
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- Servlet - JSP -->
<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>
<!--Mybatis-->
<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.6</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.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.16</version>
</dependency>
</dependencies>
<!-- 静态资源导出 -->
<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>
</project>
建立基本结构和框架
com.gaowl.pojo
com.gaowl.dao
com.gaowl.service
com.gaowl.controller
mybatis.xml
<?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
<?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"> </beans>
3)编写Mybatis底层文件
编写MysqL数据库配置database.properties
jdbc.driver=com.mysql.jdbc.Driver # 如果MySQL版本为8.0+,需要还需要通过serverTimezone=UTC设置时区 jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&useUnicode=true&characterEncoding=utf8 jdbc.username=root jdbc.password=root
编写mybatis核心配置文件mybatis-config.xml
<?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.gaowl.pojo"/> </typeAliases> <mappers> <!-- <mapper resource="com/gaowl/dao/BookMapper.xml"/>--> <mapper class="com.gaowl.dao.BookMapper"/> </mappers> </configuration>
编写数据库对应的实体类Book、其Dao层的Mapper接口、接口实现Mapper.xml
package com.gaowl.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Books { private int bookID; private String bookName; private int bookCounts; private String detail; }
package com.gaowl.dao; import com.gaowl.pojo.Books; import org.apache.ibatis.annotations.Param; import java.util.List; public interface BookMapper { // 增加一本Book int addBook(Books book); // 根据id删除一本Book int deleteBookById(@Param("bookID") int id); // 更新Book int updateBook(Books books); // 根据id查询,返回一本Book Books queryBookById(@Param("bookID") int id); // 查询全部Book,返回list集合 List<Books> queryAllBook(); }
<?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.gaowl.dao.BookMapper"> <!--增加一个Book--> <insert id="addBook" parameterType="Books"> insert into ssmbuild.books(bookName,bookCounts,detail) values (#{bookName}, #{bookCounts}, #{detail}) </insert> <!--根据id删除一个Book--> <delete id="deleteBookById" parameterType="int"> delete from ssmbuild.books where bookID=#{bookID} </delete> <!--更新Book--> <update id="updateBook" parameterType="Books"> update ssmbuild.books set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail} where bookID = #{bookID} </update> <!--根据id查询,返回一个Book--> <select id="queryBookById" resultType="Books"> select * from ssmbuild.books where bookID = #{bookID} </select> <!--查询全部Book--> <select id="queryAllBook" resultType="Books"> SELECT * from ssmbuild.books </select> </mapper>
编写service层的接口和实现类,其调用dao层
package com.gaowl.service; import com.gaowl.pojo.Books; import java.util.List; //BookService:接口中的方法和dao中方法名一致,因此,其可以通过调用dao层的方法实现这些业务 public interface BookService { //增加一个Book int addBook(Books book); //根据id删除一个Book int deleteBookById(int id); //更新Book int updateBook(Books books); //根据id查询,返回一个Book Books queryBookById(int id); //查询全部Book,返回list集合 List<Books> queryAllBook(); }
package com.gaowl.service; import com.gaowl.dao.BookMapper; import com.gaowl.pojo.Books; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; //@Service public class BookServiceImpl implements BookService { // service层调用dao层:通过set方法指定具体的业务,便于spring管理 private BookMapper bookMapper; //@Autowired public void setBookMapper(BookMapper bookMapper) { this.bookMapper = bookMapper; } @Override public int addBook(Books book) { return bookMapper.addBook(book); } @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(); } }
至此,底层所有操作编写完成
4)Spring层
通过配置文件spring-dao.xml整合Mybatis:
<?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"> <!-- 1.关联数据库文件,mysql和jdbc的一些配置信息 --> <context:property-placeholder location="classpath:database.properties"/> <!-- 2.数据库连接池 --> <!--数据库连接池 dbcp 半自动化操作 不能自动连接 c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面) --> <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}"/> <!-- c3p0连接池大小、关闭自动提交、连接超时时间、失败重试次数 --> <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> <!-- 3.配置SqlSessionFactory对象:注入连接池、关联mybatis配置文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <!-- 4.配置动态扫描,自动将Dao接口注入到spring容器中 --> <!--解释 :https://www.cnblogs.com/jpfss/p/7799806.html--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- 给出需要扫描Dao接口包 --> <property name="basePackage" value="com.gaowl.dao"/> </bean> </beans>
通过配置文件spring-service.xml整合service层:
<?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 http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 1.扫描service相关的bean --> <context:component-scan base-package="com.gaowl.service" /> <!-- 2.将业务类BookServiceImpl注入到IOC容器中。此处为配置实现,也可以通过@Service注解实现 --> <bean id="BookServiceImpl" class="com.gaowl.service.BookServiceImpl"> <property name="bookMapper" ref="bookMapper"/> </bean> <!-- 3.配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource" /> </bean> </beans>
5)springMVC层
配置web.xml:
<?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"> <!-- 1.注册DispatcherServlet --> <servlet> <servlet-name>DispatcherServlet</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>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 2.开启中文乱码过滤encodingFilter --> <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> <!-- 3.设置Session过期时间 --> <session-config> <session-timeout>15</session-timeout> </session-config> </web-app>
配置spring-mvc.xml:
<?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"> <!-- 1.开启SpringMVC注解驱动、静态资源过滤 --> <mvc:annotation-driven /> <mvc:default-servlet-handler/> <!-- 2.扫描web相关的bean --> <context:component-scan base-package="com.gaowl.controller" /> <!-- 3.配置ViewResolver视图解析器 --> <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> </beans>
通过applicationContext.xml整合dao、service、controller层的spring配置文件
<?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="spring-dao.xml"/> <import resource="spring-service.xml"/> <import resource="spring-mvc.xml"/> </beans>
编写controller及视图层
首页index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE HTML> <html> <head> <title>首页</title> <style type="text/css"> a { text-decoration: none; color: black; font-size: 18px; } h3 { width: 180px; height: 38px; margin: 100px auto; text-align: center; line-height: 38px; background: deepskyblue; border-radius: 4px; } </style> </head> <body> <h3> <a href="${pageContext.request.contextPath}/book/allBook">点击进入列表页</a> </h3> </body> </html>
查询所有书籍
控制类方法:调用service中的查询方法,并通过model将结果传递给对应的
allBook.jsp
文件@RequestMapping("/allBook") public String list(Model model) { List<Books> list = bookService.queryAllBook(); model.addAttribute("bookList", list); // 该boolList可以在jsp文件中,通过EL表达式拿到 return "allBook"; }
<%@ 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"> <!-- 引入 Bootstrap --> <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> <div class="row"> <div class="col-md-4 column"> <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增</a> </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> <tbody> <c:forEach var="book" items="${requestScope.get('bookList')}"> <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> </table> </div> </div> </div> </body> </html>
添加一本新书
控制器类的方法:index中的按钮绑定的是toAddBook方法,跳转到添加书籍的界面
addBook.jsp
,而其提交时绑定的action为addBook方法,此方法中调用service层中的方法进行书籍的添加,最后重定向到所有图书的界面,显示所有书籍。@RequestMapping("/toAddBook") public String toAddBook(Books books){ return "addBook"; } @RequestMapping("/AddBook") public String addBook(Books books){ System.out.println(books); bookService.addBook(books); return "redirect:/book/allBook"; }
<%-- Created by IntelliJ IDEA. User: GWL Date: 2021/1/7 Time: 10:16 To change this template use File | Settings | File Templates. --%> <%@ 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"> <!-- 引入 Bootstrap --> <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/AddBook" method="post"> 书籍名称:<input type="text" name="bookName"><br><br><br> 书籍数量:<input type="text" name="bookCounts"><br><br><br> 书籍详情:<input type="text" name="detail"><br><br><br> <input type="submit" value="添加"> </form> </div> </body> </html>
更新书籍信息
控制器中的方法:拿到index.jsp传递过来的id时,先调用service的方法拿到对应id的书籍信息,然后将这个信息传递给updateBook.jsp,在这个视图进行书籍信息的修改;当修改完提交时,该jsp的action属性绑定的方法UpdateBook触发,再次调用service层的方法,将更新到的书籍信息持久化到MySQL数据库中;最后返回所有书籍信息的显示界面
@RequestMapping("/toUpdateBook") public String toUpdateBook(Model model, int id){ System.out.println(id); Books books = bookService.queryBookById(id); System.out.println(books); model.addAttribute("book",books); // 将信息传递给updateBook.jsp return "updateBook"; } @RequestMapping("/UpdateBook") public String UpdateBook(Model model, Books book){ bookService.updateBook(book); return "redirect:/book/allBook"; }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>修改信息</title> </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/UpdateBook"> <input name="bookID" value="${book.getBookID()}"/> 书籍名称:<input type="text" name="bookName" value="${book.getBookName()}"/> 书籍数量:<input type="text" name="bookCounts" value="${book.getBookCounts()}"/> 书籍详情:<input type="text" name="detail" value="${book.getDetail() }"/> <input type="submit" value="提交"/> </form> </div> </body> </html>
删除一本书
直接调用service层的方法,其中id在
index.jsp
中通过restful风格传递,因此此处需要在@RequestMappering
中获取@RequestMapping("del/{bookID}") public String delBook(Model model, @PathVariable("bookID") int id){ bookService.deleteBookById(id); return "redirect:/book/allBook"; }
查询一本书
6)最终界面展示
九、Ajax
十、拦截器和文件传输
占坑,看了一点感觉没多大意思,SpringBoot去了
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!