SpringMVC实现数据增删改查
SpringMVC理解与环境配置
SpringMVC替换了Servlet的职能,降低了web层的耦合性。在 Spring MVC 框架中,Controller 替换 Servlet 来担负控制器的职责,用于接收请求,调用相应的 Model 进行处理,处理器完成业务处理后返回处理结果。Controller 调用相应的 View 并对处理结果进行视图渲染,最终客户端得到响应信息。 springmvc的优点: 1.清晰地角色划分,Spring MVC 在 Model、View 和 Controller 方面提供了一个非常清晰的角色划分,这 3 个方面真正是各司其职,各负其责。 2.灵活的配置功能,可以把类当作 Bean 通过 XML 进行配置。 3.提供了大量的控制器接口和实现类,开发者可以使用 Spring 提供的控制器实现类,也可以自己实现控制器接口。 4.真正做到与 View 层的实现无关。它不会强制开发者使用 JSP,可以根据项目需求使用 Velocity、FreeMarker 等技术。 5.国际化支持面向接口编程与 Spring 框架无缝集成
下图为springmvc的核心框架图: 从图中我们可以看出用户发送一个请求到前端控制器,并不是前端控制器去执行,而是交给自己解析器、处理器去完成工作,前端控制器只负责接受请求与发送响应,其他的渲染,试图解析都是交给其他模块去工作。
DispatcherServlet——>HandlerMapping,处理器映射器将会把请求映射为HandlerExecutionChain对象(包含一个Handler处理器对象、多个HandlerInterceptor拦截器)对象; DispatcherServlet——>HandlerAdapter,处理器适配器将会把处理器包装为适配器,从而支持多种类型的处理器,即适配器设计模式的应用,从而很容易支持很多类型的处理器; 映射器:会把请求映射为HandlerExecutionChain 对象,包含一个Handler对象和多个拦截器对象。将XX.do映射到处理器Controller,映射器总共有三种BeanNameUrlHandlerMapping、SimpleUrlHandlerMapping和ControllerClassNameHandlerMapping。 处理器HandlerAdapter:处理器适配器有两种,可以共存,分别是SimpleControllerHandlerAdapter和HttpRequestHandlerAdapter。用于处理用户提交的请求, 通过调用service层代码, 实现对用户请求的计算响应, 并最终将计算所得数据及要响应的页面封装为一个ModelAndView 对象, 返回给前端控制器。 视图解析器ViewResolver:视图解析器负责将处理结果生成View视图. 这里介绍两种常用的视图解析器:InternalResourceViewResolver内部资源路径 = 前缀 + 视图名称 + 后缀.BeanNameViewResolverInternalResourceViewResolver视图解析器存在一个问题, 就是只可以完成将内部资源封装后的跳转, 无法跳转向外部资源, 如外部网页.
实现增删改查
1.环境搭建(十分关键) 搭建环境我采用的是maven,导入的依赖有:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
<!-- 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/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/aopalliance/aopalliance -->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjtools -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
web.xml配置文件
<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>
springmvc配置文件:
<context:component-scan base-package="com.xiaoliu"/>
<context:annotation-config/>
<mvc:view-controller path="/" view-name="user"/>
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
//表示一个试图解析器bean对象,路径》后缀
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
部分源码:
<%--
Created by IntelliJ IDEA.
User: xiaoniu
Date: 2021/9/22
Time: 19:57
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<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> <title>用户信息</title>
<script>
$(function () {
$.ajax({
type: "GET",
url: "${pageContext.request.contextPath}/user",
dataType:"json",
success: function(json){
$(json).each(function(i,v){
var str = "<tbody> <tr class='active'> <td>"+v.userid+"</td> <td>"+v.username+"</td> <td>"+v.password+"</td><td><button id='delete' type='button' class='btn btn-info'>删除</button></td><td><button id='modify' type='button' class='btn btn-danger' data-toggle='modal' data-target='#myModal'>修改</button></td></tr> </tbody>";
$("table").append(str);
});
}
});
$("#submit").click(function (){
var id = $("[name='id']").val();
if(id==''){
alert("添加");
$("[name='id']").hide();
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/user",
data: "username="+$("[name='username']").val()+"&password="+$("[name='password']").val(),
success: function(mesg){
alert(mesg);
if(mesg=='success'){
window.location.reload();
}
}
});
}else{
alert("修改");
var data ="username="+$("[name='username']").val()+"&password="+$("[name='password']").val()+"&userid="+$("[name='id']").val()+"&_method=PUT";
alert(data);
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/user",
data: data,
success: function(mesg){
alert(mesg);
window.location.reload();
},
error:function (){
alert("连接失败")
}
});
}
});
$(document).on("click","#delete",function (){
var userid = $(this).parents("tr").find("td:first").html();
$.ajax({
type: "DELETE",
url: "${pageContext.request.contextPath}/user/"+userid,
success: function(mesg){
alert(mesg);
window.location.reload();
},
error:function (){
alert("连接失败")
}
});
});
$(document).on("click","#modify",function (){
var userid = $(this).parents("tr").find("td:first").html();
var username = $(this).parents("tr").find("td:first").next().html();
var password = $(this).parents("tr").find("td:first").next().next().html();
alert(userid+"|"+username+"|"+password);
$("#submit").html("修改");
$("[name='id']").val(userid);
$("[name='username']").val(username);
$("[name='password']").val(password);
});
});
</script>
</head>
<body>
<div style="width: 400px;height: 300px;margin: 0px auto;">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>用户名</th>
<th>密码</th></tr>
</thead>
</table>
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">添加用户</button>
<!-- 模态框(Modal) -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">用户信息</h4>
<form action="/user" method="post">
ID<input type="text" name="id"><br>
用户名<input type="text" name="username"><br>
密码<input type="text" name="password"><br>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button id="submit" type="button" class="btn btn-primary" data-dismiss="modal">添加</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
效果图:
|