SpringMVC
1、简介
-
Spring MVC是Spring Framework的一部分,是基于Java实现MVC的轻量级Web框架
-
官方文档:https://docs.spring.io/spring/docs/5.2.0.RELEASE/spring-framework-reference/web.html#spring-web
-
特点
- 轻量级,简单易学
- 高效 , 基于请求响应的MVC框架
- 与Spring兼容性好,无缝结合
- 约定优于配置
- 功能强大:RESTful、数据验证、格式化、本地化、主题等
- 简洁灵活
-
中心控制器
- DispatcherServlet:以请求为驱动 , 围绕一个中心Servlet分派请求及提供其他功能,是一个实际的Servlet (它继承自HttpServlet 基类)
-
Spring MVC执行原理
- 当发起请求时被前置的控制器拦截到请求,根据请求参数生成代理请求,找到请求对应的实际控制器,控制器处理请求,创建数据模型,访问数据库,将模型响应给中心控制器,控制器使用模型与视图渲染视图结果,将结果返回给中心控制器,再将结果返回给请求者
- 实线表示SpringMVC框架提供的技术,不需要开发者实现,虚线表示需要开发者实现
1、DispatcherServlet表示前置控制器,是整个SpringMVC的控制中心。用户发出请求,DispatcherServlet接收请求并拦截请求。我们假设请求的url为 : http://localhost:8080/SpringMVC/hello,可以分为三部分:1)http://localhost:8080是服务器域名,2)SpringMVC是部署在服务器上的web站点,3)hello是表示控制器,通过分析,如上url表示为:请求位于服务器localhost:8080上的SpringMVC站点的hello控制器。
2、HandlerMapping为处理器映射。DispatcherServlet调用HandlerMapping,HandlerMapping根据请求url查找Handler。
3、HandlerExecution表示具体的Handler,其主要作用是根据url查找控制器,如上url被查找控制器为:hello。
4、HandlerExecution将解析后的信息传递给DispatcherServlet,如解析控制器映射等。
5、HandlerAdapter表示处理器适配器,其按照特定的规则去执行Handler。
6、Handler让具体的Controller执行。
7、Controller将具体的执行信息返回给HandlerAdapter,如ModelAndView。
8、HandlerAdapter将视图逻辑名或模型传递给DispatcherServlet。
9、DispatcherServlet调用视图解析器(ViewResolver)来解析HandlerAdapter传递的逻辑视图名。
10、ViewResolver视图解析器将解析的逻辑视图名传给DispatcherServlet。
11、DispatcherServlet根据视图解析器解析的视图结果,调用具体的视图。
12、最终视图呈现给用户。
2、第一个SpringMVC程序
-
实现步骤
-
新建一个web项目
-
导入相关jar包
-
编写web.xml , 注册DispatcherServlet
-
编写springmvc配置文件
-
创建对应的控制类 , controller
-
完善前端视图和controller之间的对应
-
测试运行调试
SpringMVC三大配件:处理器映射器、处理器适配器、视图解析器
通常,我们只需要手动配置视图解析器,而处理器映射器和处理器适配器只需要开启注解驱动即可,而省去了大段的xml配置
-
2.1、使用配置
用来理解原理,实际上不使用这种方式,使用注解开发
- 新建moudle,添加web支持,配置tomcat
- pom.xml导入SpringMVC依赖,确认lib依赖已经添加(project structure->手动添加lib)
<!-- SpringMVC -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
- 配置web.xml , 注册DispatcherServlet(请求分发器/前端控制器):是springMVC的核心
<?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">
<!--注册DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!--启动级别-1-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--/是会匹配所有请求,不包括.jsp
/*是会匹配所有请求,包括.jsp
-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
- 编写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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--处理映射器HandlerMapping-->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!--处理器适配器HandlerAdapter-->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<!--视图解析器ViewResolver-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
- 编写Controller
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class HelloController implements Controller {
@Override
public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
//ModelAndView 模型和视图
ModelAndView mv = new ModelAndView();
//业务代码:封装对象,放在ModelAndView中
mv.addObject("msg","HelloSpringMVC!");
//视图跳转:封装要跳转的视图,放在ModelAndView中
mv.setViewName("test"); //: /WEB-INF/jsp/test.jsp
return mv;
}
}
- 到springmvc-servlet.xml中注册bean,将自己的类交给SpringIOC容器
<!--Handler-->
<bean id="/hello" class="com.leijiao.controller.HelloController"/>
2.2、使用注解
- web.xml不变
- SpringMVC配置文件springmvc-servlet.xml变化
- 无需配置处理映射器HandlerMapping
- 无需配置处理器适配器HandlerAdapter
<?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.leijiao.controller"/>
<!-- 让Spring MVC不处理静态资源,HTML、JS、CSS、图片、视频 -->
<mvc:default-servlet-handler />
<!--
支持mvc注解驱动
在spring中一般采用@RequestMapping注解来完成映射关系
要想使@RequestMapping注解生效
必须向上下文中注册DefaultAnnotationHandlerMapping
和一个AnnotationMethodHandlerAdapter实例
这两个实例分别在类级别和方法级别处理。
而annotation-driven配置帮助我们自动完成上述两个实例的注入。
-->
<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>
- Controller变化
- @Controller是为了让Spring IOC容器初始化时自动扫描到
- @RequestMapping是为了映射请求路径,这里因为类与方法上都有映射所以访问时应该是/hello/1
- 方法中声明Model类型的参数是为了把Action中的数据带到视图中
- 方法返回的结果是视图的名称test,加上配置文件中的前后缀变成WEB-INF/jsp/test.jsp
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/hello")
public class HelloController {
//真实访问地址 : 项目名/hello/1
@RequestMapping("/1")
public String hello(Model model){
//向模型中添加属性msg与值,可以在JSP页面中取出并渲染
model.addAttribute("msg","hello,SpringMVC");
//web-inf/jsp/test.jsp
return "test";
}
}
3、controller控制器
-
控制器负责提供访问应用程序的行为,通常通过接口定义(章节2.1)或注解定义(章节2.2)两种方法实现
-
控制器负责解析用户的请求并将其转换为一个模型
-
在Spring MVC中一个控制器类可以包含多个方法
-
在Spring MVC中,对于Controller的配置方式有很多种
-
@RequestMapping
- 只注解在方法上面,只需要指定方法的路径
@Controller public class TestController { @RequestMapping("/h1") public String test(){ return "test"; } } //url = http://localhost:8080 / 项目名 / h1
- 同时注解类与方法,需要先指定类的路径再指定方法的路径
@Controller @RequestMapping("/admin") public class TestController { @RequestMapping("/h1") public String test(){ return "test"; } } //url = http://localhost:8080 / 项目名/ admin /h1
4、RestFul风格
概念:Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制,更安全。
传统方式操作资源 :通过不同的参数来实现不同的效果!方法单一,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
4.1、传统的例子
访问:http://localhost:8080/项目名/add?a=1&b=2
@Controller
public class Controller {
@RequestMapping("/add")
public String test(int a, int b, Model model){
int sum = a+b;
model.addAttribute("msg","结果为"+sum);
return "test";
}
}
4.2、RestFul的例子
访问:http://localhost:8080/项目名/add/1/2
- 路径变得更加简洁
- 请求参数不暴露,更安全
- 获得参数更加方便,框架会自动进行类型转换
- 通过路径变量的类型可以约束访问参数,如果类型不一样,则访问不到对应的请求方法,如这里访问是的路径是/add/1/a,则路径与方法不匹配,而不会是参数转换失败,错误码400
@Controller
public class RestfulController {
@RequestMapping("/add/{a}/{b}")
//@PathVariable 注解,让方法参数的值对应绑定到一个URI模板变量上
public String test(@PathVariable int a, @PathVariable int b, Model model){
int sum = a+b;
model.addAttribute("msg","结果为"+sum);
return "test";
}
}
4.3、指定请求类型
方法一:@RequestMapping中添加method 属性
method = {RequestMethod.POST}指定了请求方式是POST,浏览器访问http://localhost:8080/项目名/test时是GET方法,会报错:HTTP状态 405 - 方法不允许
@Controller
public class test1Controller {
@RequestMapping(value = "/test",method = {RequestMethod.POST})
public String test(Model model){
model.addAttribute("msg","method指定请求方式");
return "test";
}
}
方式二:直接使用指定注解
@Controller
public class test2Controller {
/* 使用注解直接指定请求方式
* @GetMapping
* @PostMapping
* @PutMapping
* @DeleteMapping
* @PatchMapping
* */
@GetMapping("/test2")
public String test(Model model){
model.addAttribute("msg","@GetMapping指定为GET方式");
return "test";
}
}
5、结果跳转方式
5.1、ModelAndView
同章节2.1的例子
设置ModelAndView对象 , 根据view的名称 , 和视图解析器跳到指定的页面
- 页面 : {视图解析器前缀} + viewName +{视图解析器后缀},在springmvc配置文件中
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
- controller
public class ControllerTest implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//返回一个模型视图对象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
- 注册
<!--Handler-->
<bean id="/hello" class="com.leijiao.controller.HelloController"/>
5.2、ServletAPI
通过设置ServletAPI , 不需要视图解析器
1、通过HttpServletResponse进行输出
2、通过HttpServletResponse实现重定向
3、通过HttpServletRequest 实现转发
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Controller
public class TestServlet {
@RequestMapping("/test1")
public void test1(HttpServletRequest req, HttpServletResponse resp) throws IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().write("通过HttpServletResponse进行输出");
}
@RequestMapping("/test2")
public void test2(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.sendRedirect(req.getContextPath()+"/index.jsp");
}
@RequestMapping("/test3")
public void test3(HttpServletRequest req, HttpServletResponse resp) throws Exception {
req.setAttribute("msg","通过HttpServletRequest 实现转发");
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp);
}
}
5.3、SpringMVC
5.3.1、有视图解析器
@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为另一个请求/
}
}
5.3.2、无视图解析器
把springmvc配置中的视图解析器注释
<!-- 视图解析器 -->
<!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"-->
<!-- id="internalResourceViewResolver">-->
<!-- <!– 前缀 –>-->
<!-- <property name="prefix" value="/WEB-INF/jsp/" />-->
<!-- <!– 后缀 –>-->
<!-- <property name="suffix" value=".jsp" />-->
<!-- </bean>-->
@Controller
public class ResultSpringMVC {
@RequestMapping("/rsm/t1")
public String test1(){
//转发
return "/index.jsp";
}
@RequestMapping("/rsm/t2")
public String test2(){
//转发二,forward可写可不写
return "forward:/index.jsp";
}
@RequestMapping("/rsm/t3")
public String test3(){
//重定向
return "redirect:/index.jsp";
}
}
6、数据处理
6.1、处理提交数据
提交数据 : http://localhost:8080/hello?name=leijiao
1、提交的域名称和处理方法的参数名一致
@RequestMapping("/hello")
public String hello(String name){
System.out.println(name);
return "hello";
}
2、提交的域名称和处理方法的参数名不一致
提交数据 : http://localhost:8080/hello?username=leijiao
//@RequestParam("username") : username提交的域的名称 .
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
System.out.println(name);
return "hello";
}
3、提交的是一个对象
要求提交的表单域和对象的属性名一致 , 参数使用对象即可。若是不一致,就是null
- 实体类
public class User {
private int id;
private String name;
private int age;
//构造
//get/set
//tostring()
}
- controller
提交数据 : http://localhost:8080/mvc04/user?name=leijiao&id=1&age=15
@RequestMapping("/user")
public String user(User user){
System.out.println(user);
return "hello";
}
6.2、数据回显
6.2.1、ModelAndView
参考章节5.1例子
6.2.2、ModelMap
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class Hello2 {
@RequestMapping("/view2")
public String hello(ModelMap modelMap){
//相当于req.setAttribute("msg",msg);
modelMap.addAttribute("msg","数据回显2:ModelMap");
return "test";
}
}
6.2.3、Model
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class Hello3 {
@RequestMapping("/view3")
public String hello2(Model model){
model.addAttribute("msg","数据回显3:Model");
return "test";
}
}
6.2.4、乱码问题
- 写一个表单页面form.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>表单</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/abc" method="post">
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
- Controller
@Controller
public class EncodeController {
@RequestMapping("/abc")
public String test1(String name, Model model){
model.addAttribute("msg",name);
return "test";
}
}
-
前端访问:http://localhost:8080/项目名/form.jsp,输入中文名称提交,页面显示乱码
-
解决方法一:SpringMVC提供的过滤器,直接在web.xml中配置
<!--SpringMVC提供的过滤器--> <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>
-
解决方法二:修改tomcat配置文件server.xml
<Connector URIEncoding="utf-8" port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
-
解决方法三:自定义过滤器
- EncodeFilter
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 EncodeFilter 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; } }
- web.xml配置过滤器
<filter> <filter-name>encode</filter-name> <filter-class>com.leijiao.filter.EncodeFilter</filter-class> </filter> <filter-mapping> <filter-name>encode</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
7、JSON
7.1、json介绍
-
JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式,目前使用特别广泛
-
语法格式
{"name": "leijiao"}
{"age": 25}
{"sex": "女"}
- JavaScript对象和json的区别
var obj = {a: 'Hello', b: 'World'}; //这是一个对象,注意键名也是可以使用引号包裹的
var json = '{"a": "Hello", "b": "World"}'; //这是一个 JSON 字符串,本质是一个字符串
- JSON 和 JavaScript 对象互转
//json转js对象,结果是 {a: 'Hello', b: 'World'}
var obj = JSON.parse('{"a": "Hello", "b": "World"}');
//js对象转json,结果是 '{"a": "Hello", "b": "World"}'
var json = JSON.stringify({a: 'Hello', b: 'World'});
7.2、Jackson
7.2.1、基本用法
- pom.xml依赖
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.4</version>
</dependency>
- 控制器
- 使用jackson将str转为json格式
- @RequestMapping中添加属性produces = “application/json;charset=utf-8”,可以防止中文乱码,但是每一个请求都要加,有点麻烦,参考7.2.2统一解决方法
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.leijiao.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserController {
@RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
//@ResponseBody不走视图解析器,直接返回字符串
@ResponseBody
public String json1() throws JsonProcessingException {
//创建一个jackson的对象映射器,用来解析数据
ObjectMapper objectMapper = new ObjectMapper();
//创建一个对象
User user = new User("用户1号", 3, "女");
//将对象解析成为json格式
String s = objectMapper.writeValueAsString(user);
//由于@ResponseBody注解,这里会将str转成json格式返回;十分方便
return s;
}
}
7.2.2、乱码统一解决
- springmvc-servlet.xml中添加StringHttpMessageConverter转换配置即可
<!-- 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>
7.2.3、返回json统一解决
直接在类上添加注解**@RestController**,类里面的所有方法都会返回字符串,不需要再每个方法上使用@ResponseBody,更加便捷。
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.leijiao.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//@RestController类里面的所有方法都会返回字符串
@RestController
public class UserController2 {
@RequestMapping(value = "/j2")
public String json2() throws JsonProcessingException {
//创建一个jackson的对象映射器,用来解析数据
ObjectMapper objectMapper = new ObjectMapper();
//创建一个对象
User user = new User("用户2号", 3, "女");
//将对象解析成为json格式
String s = objectMapper.writeValueAsString(user);
return s;
}
}
7.2.4、返回集合
@RequestMapping(value = "/j3")
public String json3() throws JsonProcessingException {
//创建一个jackson的对象映射器,用来解析数据
ObjectMapper objectMapper = new ObjectMapper();
//创建集合
User user1 = new User("用户1号", 3, "女");
User user2 = new User("用户2号", 3, "女");
User user3 = new User("用户3号", 3, "女");
ArrayList<User> users = new ArrayList<>();
users.add(user1);
users.add(user2);
users.add(user3);
//将集合解析成为json格式
String s = objectMapper.writeValueAsString(users);
return s;
}
//输出:{"name":"用户1号","age":3,"sex":"女"},{"name":"用户2号","age":3,"sex":"女"},{"name":"用户3号","age":3,"sex":"女"}]
7.2.5、返回时间对象
- 返回时间戳
@RequestMapping(value = "/j4")
public String json4() throws JsonProcessingException {
//创建一个jackson的对象映射器,用来解析数据
ObjectMapper objectMapper = new ObjectMapper();
//创建一个时间对象
Date date = new Date();
//将对象解析成为json格式
String s = objectMapper.writeValueAsString(date);
return s;
}
//输出1632300641412
- 返回自定义时间格式
@RequestMapping(value = "/j5")
public String json5() throws JsonProcessingException {
//创建一个jackson的对象映射器,用来解析数据
ObjectMapper objectMapper = new ObjectMapper();
//不使用时间戳
//objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
//自定义时间格式对象
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//指定日期格式
objectMapper.setDateFormat(simpleDateFormat);
//创建一个时间对象
Date date = new Date();
//将对象解析成为json格式
String s = objectMapper.writeValueAsString(date);
return s;
}
7.3、fastjson
- pom.xml依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
- 常用方法
//java对象转json字符串
JSON.toJSONString(obj);
//json字符串转java对象
JSON.parseObject(json,javaobj.class);
//Java对象转json对象
(JSONObject) JSON.toJSON(javaobj);
//JSON对象转Java对象
SON.toJavaObject(jsonobj, javaobj.class);
8、整合SSM框架
8.1、环境准备
1、环境
- IDEA
- MySQL
- Tomcat
- Maven
2、数据库准备
CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
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, '从进门到进牢' );
3、项目搭建
- 新建maven项目,添加web支持
- pom.xml依赖
<dependencies>
<!-- junit单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!-- Spring -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.9</version>
</dependency>
<!-- mybatis-spring整合包 -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- servlet -->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- servlet.jsp -->
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<!-- jstl表达式的依赖 -->
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- standard标签库 -->
<!-- https://mvnrepository.com/artifact/taglibs/standard -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- mybatis -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.9</version>
</dependency>
<!-- mysql -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!-- 数据库连接池 -->
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<!-- lombok -->
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
</dependencies>
- 静态资源过滤
<!-- 构建 -->
<build>
<finalName>mybatis</finalName>
<!-- 在build中配置resources,避免出现资源导出失败的问题 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
-
项目基本框架
- com.leijiao.pojo
- com.leijiao.dao
- com.leijiao.service
- com.leijiao.controller
- 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> </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>
8.2、mybatis层编写
(pojo、dao、service)
- 数据库配置文件db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
jdbc.username=root
jdbc.password=123456
- 编写pojo实体类Books
package com.leijiao.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;
}
- 编写Dao层的Mapper接口
package com.leijiao.dao;
import com.leijiao.pojo.Books;
import java.util.List;
public interface BooksMapper {
//增
int insert(Books book);
//删
int delete(int id);
//改
int update(Books book);
//查
Books select(int id);
//查全部
Books selectall();
}
- 编写Mapper.xml配置
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace绑定一个mapper接口-->
<mapper namespace="com.leijiao.dao.BooksMapper">
<!--增-->
<insert id="insert" parameterType="Books">
insert into books (bookName,bookCounts,detail)
values (#{bookName},#{bookCounts},#{detail});
</insert>
<!--删-->
<delete id="delete" parameterType="int">
delete from books where bookID = #{bookID}
</delete>
<!--改-->
<update id="update" parameterType="Books">
update books
set bookName = #{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookID=#{bookID};
</update>
<!--查-->
<select id="select" parameterType="int" resultType="Books">
select * from books where bookID=#{bookID};
</select>
<!--查全部-->
<select id="selectall" resultType="Books">
select * from books;
</select>
</mapper>
- 编写MyBatis的核心配置文件mybatis-config.xml
<!--别名-->
<typeAliases>
<package name="com.leijiao.pojo"/>
</typeAliases>
<!--注册mapper-->
<mappers>
<mapper resource="com/leijiao/dao/BooksMapper.xml"/>
</mappers>
- 编写Service层的接口
package com.leijiao.service;
import com.leijiao.pojo.Books;
import java.util.List;
public interface BooksService {
//增
int insert(Books book);
//删
int delete(int id);
//改
int update(Books book);
//查
Books select(int id);
//查全部
List<Books> selectall();
}
- 编写Service层的接口的实现类
package com.leijiao.service;
import com.leijiao.dao.BooksMapper;
import com.leijiao.pojo.Books;
import java.util.List;
public class BooksServiceImpl implements BooksService{
//service层调用dao层
private BooksMapper booksMapper;
//setter方法
public void setBooksMapper(BooksMapper booksMapper) {
this.booksMapper = booksMapper;
}
@Override
public int insert(Books book) {
return booksMapper.insert(book);
}
@Override
public int delete(int id) {
return booksMapper.delete(id);
}
@Override
public int update(Books book) {
return booksMapper.update(book);
}
@Override
public Books select(int id) {
return booksMapper.select(id);
}
@Override
public List<Books> selectall() {
return booksMapper.selectall();
}
}
8.3、Spring整合dao层
数据源使用c3p0连接池
- 编写spring整合mybatis的配置文件spring-dao.xml
- 1、关联数据库文件
- 2、数据库连接池
- 3、配置SqlSessionFactory对象
- 4、注册bean(配置扫描Dao接口包,动态实现Dao接口注入到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"
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">
<!-- 配置整合mybatis -->
<!-- 1.关联数据库文件 -->
<context:property-placeholder location="classpath:db.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"/>
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!-- 3.配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 4.配置扫描Dao接口包,动态实现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.leijiao.dao"/>
</bean>
</beans>
8.4、Spring整合service层
- 编写spring整合mybatis的配置文件spring-dao.xml
- 1、扫描service相关的bean
- 2、service接口实现类注入到IOC容器中
- 3、配置事务管理器
<?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">
<!-- 扫描service相关的bean -->
<context:component-scan base-package="com.leijiao.service" />
<!--BookServiceImpl注入到IOC容器中-->
<bean id="BookServiceImpl" class="com.leijiao.service.BooksServiceImpl">
<property name="booksMapper" ref="booksMapper"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
8.5、整合SpringMVC层
- 添加web支持,配置web.xml
- 配置DispatcherServlet
- 乱码过滤器
- Session过期时间
<?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">
<!--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>
<!--乱码过滤器-->
<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过期时间-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
- 添加springmvc配置文件spring-mvc.xml
- 1、开启SpringMVC注解驱动
- 2、静态资源默认servlet配置
- 3、ViewResolver视图解析器
- 4、扫描controller相关的bean
<?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">
<!-- 配置SpringMVC -->
<!-- 1.开启SpringMVC注解驱动 -->
<mvc:annotation-driven />
<!-- 2.静态资源默认servlet配置-->
<mvc:default-servlet-handler/>
<!-- 3.配置jsp 显示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>
<!-- 4.扫描web相关的bean -->
<context:component-scan base-package="com.leijiao.controller" />
</beans>
8.6、总配置整合文件
- applicationContext.xml将dao、service、controller层的配置文件导入
<import resource="classpath:spring-dao.xml"></import>
<import resource="classpath:spring-service.xml"></import>
<import resource="classpath:spring-mvc.xml"></import>
8.7、增删改查功能实现
8.7.1、Controller层
- BooksController.java
package com.leijiao.controller;
import com.leijiao.pojo.Books;
import com.leijiao.service.BooksService;
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.List;
@Controller
@RequestMapping("/books")
public class BooksController {
//controller层调用service层
//@Autowired、@Qualifier注解自动装配
@Autowired
@Qualifier("BookServiceImpl")
private BooksService booksService;
@RequestMapping("/bookslist")
public String selectall(Model model){
List<Books> selectall = booksService.selectall();
model.addAttribute("list",selectall);
return "bookslist";
}
@RequestMapping("/insertpage")
public String toAddPaper() {
return "addbooks";
}
@RequestMapping("/insert")
public String insert(Books books){
booksService.insert(books);
return "redirect:/books/bookslist";
}
@RequestMapping("/select/{bookId}")
public String select(@PathVariable("bookId") int id,Model model){
Books select = booksService.select(id);
model.addAttribute("select",select);
return "selectbooks";
}
@RequestMapping("/updatepage/{bookId}")
public String toUpdatePaper(Model model,@PathVariable("bookId") int id) {
Books select = booksService.select(id);
System.out.println(select);
model.addAttribute("select",select);
return "updatebooks";
}
@RequestMapping("/update")
public String update(Model model, Books books){
booksService.update(books);
Books select = booksService.select(books.getBookID());
model.addAttribute("select",select);
return "redirect:/books/bookslist";
}
@RequestMapping("/delete/{bookId}")
public String delete(@PathVariable("bookId") int id){
booksService.delete(id);
return "redirect:/books/bookslist";
}
}
8.7.2、jsp
- bookslist.jsp
<%--引入JSTL核心标签库--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<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}/books/insertpage">新增</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('list')}">
<tr>
<td>${book.getBookID()}</td>
<td>${book.getBookName()}</td>
<td>${book.getBookCounts()}</td>
<td>${book.getDetail()}</td>
<td>
<a href="${pageContext.request.contextPath}/books/select/${book.getBookID()}">查看</a>
<a href="${pageContext.request.contextPath}/books/updatepage/${book.getBookID()}">更改</a>
<a href="${pageContext.request.contextPath}/books/delete/${book.getBookID()}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
- addbooks.jsp
<%@ 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}/books/insert" 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>
- selectbooks.jsp
<%@ 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>
<c:set var="select" value="${requestScope.get('select')}"></c:set>
<div>书籍名称:${select.getBookName()}</div>
<div>书籍数量:${select.getBookCounts()}</div>
<div>书籍详情:${select.getDetail()}</div>
</div>
- updatebooks.jsp
<%@ 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}/books/update" method="post">
<c:set var="book" value="${requestScope.get('select')}"></c:set>
<input type="hidden" name="bookID" value="${book.getBookID()}"/>
书籍名称:<input type="text" name="bookName" value="${book.getBookName()}"/><br><br>
书籍数量:<input type="text" name="bookCounts" value="${book.getBookCounts()}"/><br><br>
书籍详情:<input type="text" name="detail" value="${book.getDetail()}"/><br><br>
<input type="submit" value="提交"/>
</form>
</div>
9、Ajax
9.1、Ajax介绍
-
ajax 全名 async javascript and XML(异步JavaScript和XML)
-
ajax 是前后台交互的能⼒ 也就是我们客户端给服务端发送消息的⼯具,以及接受响应的⼯具
-
ajax 不是新的编程语言,而是一种使用现有标准的新方法。
-
ajax 是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下。
-
ajax 是⼀个默认异步执⾏机制的功能,ajax 分为同步(async = false)和异步(async = true)
-
ajax不需要插件的⽀持,原⽣ js 就可以使⽤,用户不需要刷新⻚⾯就可以更新数据
9.2、jQuery.ajax
9.2.1、方法参数说明
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 将自动替换 ? 为正确的函数名,以执行回调函数
9.2.2、HttpServletResponse实现
- springmvc的配置文件需要加静态资源过滤和注解驱动配置
<!-- 让Spring MVC不处理静态资源,HTML、JS、CSS、图片、视频 -->
<mvc:default-servlet-handler />
<!-- 注解驱动 -->
<mvc:annotation-driven />
- jsp页面
<%@ 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>--%>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.0.js"></script>
<script>
function a1(){
$.post({
url:"${pageContext.request.contextPath}/a1",
data:{'name':$("#txtName").val()},
success:function (data,status) {
alert(data);
alert(status);
}
});
}
</script>
</head>
<body>
<%--onblur:失去焦点触发事件--%>
用户名:<input type="text" id="txtName" οnblur="a1()"/>
</body>
</html>
- controller
@RequestMapping(value = "/a1")
public void a1(String name , HttpServletResponse response) throws IOException {
if ("admin".equals(name)){
response.getWriter().print("true");
}else{
response.getWriter().print("false");
}
}
9.2.3、Springmvc实现
- jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<input type="button" id="btn" value="获取数据"/>
<table width="80%" align="center">
<tr>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
</tr>
<tbody id="content">
</tbody>
</table>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.0.js"></script>
<script>
$(function () {
$("#btn").click(function () {
$.post("${pageContext.request.contextPath}/a2",function (data) {
console.log(data)
var html="";
for (var 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);
});
})
})
</script>
</body>
</html>
- 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
@RequestMapping("/a2")
public List<User> a2(){
List<User> list = new ArrayList<User>();
list.add(new User("1号",3,"男"));
list.add(new User("2号",3,"男"));
list.add(new User("3号",3,"男"));
return list; //由于@RestController注解,将list转成json格式返回
}
9.2.4、验证登录demo
- jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.0.js"></script>
<script>
function a1() {
$.post({
url:"${pageContext.request.contextPath}/a3",
data:{"username":$("#username").val()},
success:function (data) {
if (data.toString()=='OK'){
$("#usernameinfo").css("color","green");
}else {
$("#usernameinfo").css("color","red");
}
$("#usernameinfo").html(data);
}
})
}
function a2() {
$.post({
url:"${pageContext.request.contextPath}/a3",
data:{"password":$("#password").val()},
success:function (data) {
if (data.toString()=='OK'){
$("#passwordinfo").css("color","green");
}else {
$("#passwordinfo").css("color","red");
}
$("#passwordinfo").html(data);
}
})
}
</script>
</head>
<body>
<p>
用户名:<input type="text" id="username" οnblur="a1()">
<span id="usernameinfo"></span>
</p>
<p>
密码:<input type="text" id="password" οnblur="a2()">
<span id="passwordinfo"></span>
</p>
</body>
</html>
- controller
@RequestMapping("/a3")
public String a3(String username,String password){
String msg = "";
if(username!=null){
if("admin".equals(username)){
msg = "OK";
}else {
msg = "用户名错误";
}
}
if(password!=null){
if("123456".equals(password)){
msg = "OK";
}else {
msg = "密码错误";
}
}
return msg;
}
`
9.2.4、验证登录demo
- jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.0.js"></script>
<script>
function a1() {
$.post({
url:"${pageContext.request.contextPath}/a3",
data:{"username":$("#username").val()},
success:function (data) {
if (data.toString()=='OK'){
$("#usernameinfo").css("color","green");
}else {
$("#usernameinfo").css("color","red");
}
$("#usernameinfo").html(data);
}
})
}
function a2() {
$.post({
url:"${pageContext.request.contextPath}/a3",
data:{"password":$("#password").val()},
success:function (data) {
if (data.toString()=='OK'){
$("#passwordinfo").css("color","green");
}else {
$("#passwordinfo").css("color","red");
}
$("#passwordinfo").html(data);
}
})
}
</script>
</head>
<body>
<p>
用户名:<input type="text" id="username" οnblur="a1()">
<span id="usernameinfo"></span>
</p>
<p>
密码:<input type="text" id="password" οnblur="a2()">
<span id="passwordinfo"></span>
</p>
</body>
</html>
- controller
@RequestMapping("/a3")
public String a3(String username,String password){
String msg = "";
if(username!=null){
if("admin".equals(username)){
msg = "OK";
}else {
msg = "用户名错误";
}
}
if(password!=null){
if("123456".equals(password)){
msg = "OK";
}else {
msg = "密码错误";
}
}
return msg;
}