使用了druid(德鲁伊连接池)和同用mapper,spring,springmvc,mybatis框架,前台是jquery
1.配置文件
1.1pom.xml配置文件
<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>cn.jzh</groupId>
<artifactId>maven_crud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>maven_crud</name>
<properties>
<webVersion>3.1</webVersion>
</properties>
<dependencies>
<!-- servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- Spring相关依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<!-- Mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!-- mybatis整合Spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- mybatis plugins begin -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.3.9</version>
</dependency>
<!-- mybatis plugins end -->
<!-- MySql依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<!-- 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.18</version>
</dependency>
<!-- slf4j日志依赖 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<!-- JSP相关 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<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>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.9</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
1.2applicationContext.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 首先加载application.properties -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- spring注解扫描 -->
<context:component-scan base-package="cn.jzh.service"></context:component-scan>
<!-- 配置dataSource -->
<bean id ="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 配置sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 自动扫描mapping.xml文件,**表示迭代查找 -->
<property name="mapperLocations" value="classpath:mapper/*Mapper.xml"></property>
</bean>
<!-- 3.配置MapperScannerConfigurer,用于扫描指定包下的Mapper接口,
生成代理对象的id为Mapper接口名第一个字母小写(userinfoMapper) -->
<!-- 扫描com.redis下的mapper接口 -->
<bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.jzh.mapper"></property>
<!--使用mybatis通用mapper插件 -->
<property name="properties">
<value>
mappers=tk.mybatis.mapper.common.Mapper
</value>
</property>
</bean>
<!-- 声明事物 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 事物详情 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut expression="execution(* cn.jzh.service.*.*(..))" id="myPointcut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"/>
</aop:config>
</beans>
1.3springmvc.xml配置文件
因为这一层只扫描到controller层的,所以注解也是只扫描到controller层
<?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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 注解扫描,自动扫描只扫描controller层的 -->
<context:component-scan base-package="cn.jzh.controller"></context:component-scan>
<!-- 注解驱动 -->
<mvc:annotation-driven>
<mvc:message-converters>
<!-- spring 自带中文编码转换器 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg index="0" value="UTF-8" />
</bean>
<!-- json格式化 -->
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="prettyPrint" value="true"></property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/view/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 放行静态 -->
<mvc:default-servlet-handler/>
</beans>
1.4jdbc.properties配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root
1.5.mapper.xml的SQL文件
<?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="cn.jzh.mapper.UserInfoMapper" >
<resultMap id="BaseResultMap" type="cn.jzh.entity.UserInfo" >
<id column="user_id" property="userId" jdbcType="BIGINT" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="user_age" property="userAge" jdbcType="INTEGER" />
<result column="user_address" property="userAddress" jdbcType="VARCHAR" />
<result column="user_account" property="userAccount" jdbcType="VARCHAR" />
<result column="user_password" property="userPassword" jdbcType="VARCHAR" />
</resultMap>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
delete from user_info
where user_id = #{userId,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="cn.jzh.entity.UserInfo" >
<selectKey resultType="java.lang.Long" keyProperty="userId" order="AFTER" >
SELECT LAST_INSERT_ID()
</selectKey>
insert into user_info (user_name, user_age, user_address,
user_account, user_password)
values (#{userName,jdbcType=VARCHAR}, #{userAge,jdbcType=INTEGER}, #{userAddress,jdbcType=VARCHAR},
#{userAccount,jdbcType=VARCHAR}, #{userPassword,jdbcType=VARCHAR})
</insert>
<update id="updateByPrimaryKey" parameterType="cn.jzh.entity.UserInfo" >
update user_info
set user_name = #{userName,jdbcType=VARCHAR},
user_age = #{userAge,jdbcType=INTEGER},
user_address = #{userAddress,jdbcType=VARCHAR},
user_account = #{userAccount,jdbcType=VARCHAR},
user_password = #{userPassword,jdbcType=VARCHAR}
where user_id = #{userId,jdbcType=BIGINT}
</update>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
select user_id, user_name, user_age, user_address, user_account, user_password
from user_info
where user_id = #{userId,jdbcType=BIGINT}
</select>
<select id="selectAll" resultMap="BaseResultMap" >
select user_id, user_name, user_age, user_address, user_account, user_password
from user_info
</select>
</mapper>
1.6web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>maven_crud</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 解决post提交乱码 -->
<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>
<!-- servlet容器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
2.后台控制部分
2.1实体bean
package cn.jzh.entity;
public class UserInfo {
private Long userId;
private String userName;
private Integer userAge;
private String userAddress;
private String userAccount;
private String userPassword;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public Integer getUserAge() {
return userAge;
}
public void setUserAge(Integer userAge) {
this.userAge = userAge;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress == null ? null : userAddress.trim();
}
public String getUserAccount() {
return userAccount;
}
public void setUserAccount(String userAccount) {
this.userAccount = userAccount == null ? null : userAccount.trim();
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword == null ? null : userPassword.trim();
}
public UserInfo(Long userId, String userName, Integer userAge, String userAddress, String userAccount,
String userPassword) {
super();
this.userId = userId;
this.userName = userName;
this.userAge = userAge;
this.userAddress = userAddress;
this.userAccount = userAccount;
this.userPassword = userPassword;
}
public UserInfo() {
super();
// TODO Auto-generated constructor stub
}
}
2.2mapper接口
package cn.jzh.mapper;
import java.util.List;
import cn.jzh.entity.UserInfo;
public interface UserInfoMapper {
int deleteByPrimaryKey(Long userId);
int insert(UserInfo record);
UserInfo selectByPrimaryKey(Long userId);
List<UserInfo> selectAll();
int updateByPrimaryKey(UserInfo record);
}
2.3service接口
package cn.jzh.service;
import java.util.List;
import cn.jzh.entity.UserInfo;
public interface UserInfoService {
int deleteByPrimaryKey(Long userId);
int insert(UserInfo record);
UserInfo selectByPrimaryKey(Long userId);
List<UserInfo> selectAll();
int updateByPrimaryKey(UserInfo record);
}
2.3.1service接口的实现类
package cn.jzh.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.jzh.entity.UserInfo;
import cn.jzh.mapper.UserInfoMapper;
import cn.jzh.service.UserInfoService;
@Service(value="userInfoServiceImpl")
public class UserInfoServiceImpl implements UserInfoService{
@Autowired
private UserInfoMapper mapper;
@Override
public int deleteByPrimaryKey(Long userId) {
int i = mapper.deleteByPrimaryKey(userId);
return i;
}
@Override
public int insert(UserInfo record) {
int i = mapper.insert(record);
return i;
}
@Override
public UserInfo selectByPrimaryKey(Long userId) {
UserInfo info = mapper.selectByPrimaryKey(userId);
return info;
}
@Override
public List<UserInfo> selectAll() {
List<UserInfo> selectAll = mapper.selectAll();
return selectAll;
}
@Override
public int updateByPrimaryKey(UserInfo record) {
int i = mapper.updateByPrimaryKey(record);
return i;
}
}
2.4controller控制层
package cn.jzh.controller;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import cn.jzh.entity.UserInfo;
import cn.jzh.service.UserInfoService;
@Controller
public class UserInfoController {
@Resource(name="userInfoServiceImpl")
private UserInfoService userInfoService;
//查看
@RequestMapping("/userInfo/list")
public String list(Model model){
List<UserInfo> list = userInfoService.selectAll();
model.addAttribute("userInfoList", list);
return "list";
}
//删除
@RequestMapping("/userInfo/delete")
public String delete(Long userId){
int i = userInfoService.deleteByPrimaryKey(userId);
return "redirect:/userInfo/list";
}
//增加
@RequestMapping(value="/userInfo/add",method=RequestMethod.GET)
public String add(){
return "add";
}
@RequestMapping(value="/userInfo/add",method=RequestMethod.POST)
public String add(UserInfo userInfo){
int i = userInfoService.insert(userInfo);
if(i>0){
return "redirect:/userInfo/list";
}
return "";
}
//更新
@RequestMapping(value="/userInfo/update",method=RequestMethod.GET)
public String update (Long userId,Model model){
UserInfo info = userInfoService.selectByPrimaryKey(userId);
model.addAttribute("user", info);
return "update";
}
@RequestMapping(value="/userInfo/update",method=RequestMethod.POST)
public String update(UserInfo userInfo){
int i = userInfoService.updateByPrimaryKey(userInfo);
if(i>0){
return "redirect:/userInfo/list";
}
return "";
}
}
3.前台展现部分
3.1展示欢迎的页面index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<script type="text/javascript">
console.log(Boolean(false));
</script>
</head>
<body>
<a href="userInfo/list.action">用户列表</a>
</body>
</html>
3.2受保护的view文件下的jsp页面
3.2.1展示页面list.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'add.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<table border="1px" align="center">
<a href="userInfo/add.action">新增</a>
<tr>
<th>用户编号</th>
<th>用户名称</th>
<th>用户年龄</th>
<th>用户地址</th>
<th>用户账户</th>
<th>用户密码</th>
<th>操作</th>
</tr>
<c:if test="${empty userInfoList }">
<tr>
<td colspan="7">是空的</td>
</tr>
</c:if>
<c:if test="${not empty userInfoList }">
<c:forEach items="${userInfoList }" var ="user">
<tr>
<td>${user.userId }</td>
<td>${user.userName }</td>
<td>${user.userAge }</td>
<td>${user.userAddress }</td>
<td>${user.userAccount }</td>
<td>${user.userPassword }</td>
<td>
<a href="userInfo/update.action?userId=${user.userId }">修改</a>
<a href="userInfo/delete.action?userId=${user.userId }">删除</a>
</td>
</tr>
</c:forEach>
</c:if>
</table>
</body>
</html>
3.2.2新增页面add.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'add.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="static/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
});
</script>
</head>
<body>
<form name = "form_user_info" action="userInfo/add.action" method="post" >
用户名:<input type="text" name="userName" /><br/>
年 龄:<input type="text" name="userAge" /><br/>
地 址:<input type="text" name="userAddress" /><br/>
账 户:<input type="text" name="userAccount" /><br/>
密 码:<input type="password" name="userPassword" /><br/>
<input type="submit" value="新增"><br/>
</form>
</body>
</html>
3.2.3修改页面update.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'add.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="userInfo/update.action" method="post">
<input type="hidden" name="userId" value="${user.userId }"><br>
用户名:<input name="userName" value="${user.userName }"><br>
年 龄:<input name="userAge" value="${user.userAge }"><br>
地 址:<input name="userAddress" value="${user.userAddress }"><br>
账 户:<input name="userAccount" value="${user.userAccount }"><br>
密 码:<input name="userPassword" value="${user.userPassword }"><br>
<input type="submit" value="修改"/>
</form>
</body>
</html>
如果调试有什么问题,可以直接和我留言,我会第一时间回复你们