SSM框架整合實現增刪改查(簡單的實現)
阿新 • • 發佈:2018-12-11
SSM框架整合實現增刪改查
檔案結構 POM檔案<packaging>war</packaging> <!-- 處理亂碼 --> <properties> <!-- 設定專案字符集 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- spring版本號 --> <spring.version>4.3.2.RELEASE</spring.version> </properties> <dependencies> <!--Dao層Mybatis jar包 --> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency> <!-- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.8</version> </dependency> <!-- Service層 Spring --> <!-- Spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.2.RELEASE</version> </dependency> <!-- Spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.2.RELEASE</version> </dependency> <!-- Spring-bean --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.2.RELEASE</version> </dependency> <!-- Spring-expression --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.3.2.RELEASE</version> </dependency> <!-- Spring-tx --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.2.RELEASE</version> </dependency> <!-- Spring-jbdc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.2.RELEASE</version> </dependency> <!-- Spring-mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> <!-- Servlet層SpringMVC --> <!-- Spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.2.RELEASE</version> </dependency> <!-- Spring-mvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.2.RELEASE</version> </dependency> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <!-- jsp --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> <!-- jsp.jstl --> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- servlet.jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- standard --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- aspect註解 --> <!--使用AspectJ方式註解需要相應的包 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.6.11</version> </dependency> <!--使用AspectJ方式註解需要相應的包 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.11</version> </dependency> </dependencies> <!-- Tomcat外掛 --> <build> <!-- 配置tomcat外掛,web端 --> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <configuration> <path>/</path> <port>8080</port> </configuration> </plugin> </plugins> </build>
Mybatis的XML檔案 applicationContext-mybatis.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- 載入資料庫配置檔案 --> <context:property-placeholder location="classpath:druid.properties"/> <!-- 配置資料庫連線池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 配置資料庫連線基本資訊 --> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${name}" /> <property name="password" value="${password}" /> <!-- ******配置資料庫連線池相關資訊******* --> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="5" /> <property name="minIdle" value="2" /> <property name="maxActive" value="10" /> <!-- 配置獲取連線等待超時的時間 --> <property name="maxWait" value="10000" /> <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一個連線在池中最小生存的時間,單位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="testWhileIdle" value="true" /> <!-- 這裡建議配置為TRUE,防止取到的連線不可用 --> <property name="testOnBorrow" value="true" /> <property name="testOnReturn" value="false" /> <!-- 開啟PSCache,並且指定每個連線上PSCache的大小 --> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <!-- 這裡配置提交方式,預設就是TRUE,可以不用配置 --> <property name="defaultAutoCommit" value="true" /> <!-- 驗證連線有效與否的SQL,不同的資料配置不同 --> <property name="validationQuery" value="select 1" /> </bean> <!-- sqlsessionFactory --> <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入資料來源 --> <property name="dataSource" ref="dataSource"></property> <!-- 載入mybatis配置檔案 --> <property name="configLocation" value="classpath:mybatisConfig.xml"></property> <!-- 載入對映檔案 --> <property name="mapperLocations" value="classpath:cn/edu360/mybatis/entity/*.xml"></property> </bean> <!-- 配置事物管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入資料來源 --> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 通過aop管理事務(事務應該做用在service層) --> <aop:config proxy-target-class="true"> <aop:advisor pointcut="execution (* cn.edu360.service.impl.*.*(..))" advice-ref="departmentAdvice" /> </aop:config> <!-- 建立一個事物 --> <tx:advice id="departmentAdvice" transaction-manager="transactionManager"> <!-- 設定事物的級別和屬性 --> <tx:attributes> <tx:method name="insert*" isolation="READ_COMMITTED" propagation="REQUIRED" read-only="false" timeout="-1" rollback-for="Exception" /> <tx:method name="delete*" isolation="READ_COMMITTED" propagation="REQUIRED" read-only="false" timeout="-1" rollback-for="Exception" /> <tx:method name="update*" isolation="READ_COMMITTED" propagation="REQUIRED" read-only="false" timeout="-1" rollback-for="Exception" /> <tx:method name="select*" propagation="SUPPORTS" read-only="false" rollback-for="Exception" /> <tx:method name="*" isolation="READ_COMMITTED" propagation="REQUIRED" timeout="-1" rollback-for="Exception" read-only="false" /> </tx:attributes> </tx:advice> <!-- 掃描Dao層連線Mybatis的mapper介面 --> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.edu360.mybatis.mapper"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"></property> </bean> </beans>
Mybatis配置檔案 mybatisConfig.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>
Spring配置檔案 applicationContext-spring.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- 啟用classpath掃描 --> <context:component-scan base-package="cn.edu360"></context:component-scan> </beans>
SpringMVC配置檔案 springmvc.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- classpath掃描controller -->
<context:component-scan base-package="cn.edu360.spring.controller"></context:component-scan>
<!-- springMVC 檢視解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>Spring-SpringMVC-Mybatis-ssm</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>
<!-- 在servlet上下文中配置ioc容器檔案 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<!-- 通過監聽器載入ioc容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置過濾器 -->
<!-- POST中文亂碼過濾器 -->
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置前端控制器 -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 預設載入springmvc配置檔案【servlet-name】-servlet.xml 位置在WEB-INF下 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.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>
</web-app>
實體類
package cn.edu360.mybatis.entity;
public class Department {
private int department_id;
private String dname;
private String daddress;
public Department(int department_id, String dname, String daddress) {
super();
this.department_id = department_id;
this.dname = dname;
this.daddress = daddress;
}
public Department() {
super();
}
public int getDepartment_id() {
return department_id;
}
public void setDepartment_id(int department_id) {
this.department_id = department_id;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getDaddress() {
return daddress;
}
public void setDaddress(String daddress) {
this.daddress = daddress;
}
@Override
public String toString() {
return "Department [department_id=" + department_id + ", dname=" + dname + ", daddress=" + daddress + "]";
}
}
Mapping對映檔案
<?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.edu360.mybatis.mapper.DepartmentMapper">
<!-- 新增 -->
<insert id="insertByCount" parameterType="cn.edu360.mybatis.entity.Department">
insert into department values(null,#{dname},#{daddress})
</insert>
<!-- 修改 -->
<update id="updateByCount" parameterType="cn.edu360.mybatis.entity.Department">
update department set dname=#{dname},daddress=#{daddress} where department_id=#{department_id}
</update>
<!-- 刪除 -->
<delete id="deleteByCount" parameterType="cn.edu360.mybatis.entity.Department">
delete from department where department_id=#{department_id}
</delete>
<!-- 查詢全部 -->
<select id="selectByAll" resultType="cn.edu360.mybatis.entity.Department">
select * from department
</select>
<!-- 模糊查詢 -->
<select id="selectByLike" resultType="cn.edu360.mybatis.entity.Department" parameterType="java.lang.String">
select * from department where dname like concat('%',#{keyWord},'%')
</select>
</mapper>
Mapper介面
package cn.edu360.mybatis.mapper;
import java.util.List;
import cn.edu360.mybatis.entity.Department;
public interface DepartmentMapper {
//對資料庫進行新增
int insertByCount(Department dept);
//對資料庫進行修改
int updateByCount(Department dept);
//對資料庫進行刪除
int deleteByCount(Department dept);
//對資料路進行全部查詢
List<Department> selectByAll();
//對資料庫進行模糊查詢
List<Department> selectByLike(String keyWord);
}
Service介面
package cn.edu360.service.inter;
import java.util.List;
import cn.edu360.mybatis.entity.Department;
public interface DepartmentServiceInter {
String insertByCount(Department dept);
String updateByCount(Department dept);
String deleteByCount(Department dept);
List<Department> selectByAll();
List<Department> selectByLike(String keyWord);
}
Service實現類
package cn.edu360.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.edu360.mybatis.entity.Department;
import cn.edu360.mybatis.mapper.DepartmentMapper;
import cn.edu360.service.inter.DepartmentServiceInter;
@Service("departmentServiceImpl")
public class DepartmentServiceImpl implements DepartmentServiceInter {
@Autowired
private DepartmentMapper departmentMapper;
@Override
public String insertByCount(Department dept) {
System.out.println("service+++++++++++++++++++++++++++++++++++++++++++++");
int i = departmentMapper.insertByCount(dept);
String message="";
if(i>0) {
message="新增成功";
}else {
message="新增失敗";
}
return message;
}
@Override
public String updateByCount(Department dept) {
int i = departmentMapper.updateByCount(dept);
String message="";
if(i>0) {
message="修改成功";
}else {
message="修改失敗";
}
return message;
}
@Override
public String deleteByCount(Department dept) {
int i = departmentMapper.deleteByCount(dept);
String message="";
if(i>0) {
message="刪除成功";
}else {
message="刪除失敗";
}
return message;
}
@Override
public List<Department> selectByAll() {
return departmentMapper.selectByAll();
}
@Override
public List<Department> selectByLike(String keyWord) {
return departmentMapper.selectByLike(keyWord);
}
public DepartmentMapper getDepartmentMapper() {
return departmentMapper;
}
public void setDepartmentMapper(DepartmentMapper departmentMapper) {
this.departmentMapper = departmentMapper;
}
}
Controller控制層
package cn.edu360.spring.mybatis.test;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.ibatis.annotations.ResultMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import cn.edu360.mybatis.entity.Department;
import cn.edu360.service.impl.DepartmentServiceImpl;
import cn.edu360.service.inter.DepartmentServiceInter;
@Controller
public class SpringMybatisTest {
@Autowired
private DepartmentServiceInter service;
@RequestMapping("/insert")
public String insertByCount(HttpServletRequest req,Department dept) {
dept.setDname(dept.getDname());
dept.setDaddress(dept.getDaddress());
System.out.println(dept.toString());
String insert = service.insertByCount(dept);
req.setAttribute("insert", insert);
return "/insert";
}
@RequestMapping("/select")
public String selectByAll(HttpServletRequest req){
List<Department> list = service.selectByAll();
req.setAttribute("list", list);
return "/select";
}
@RequestMapping("/update")
public String updateByCount(HttpServletRequest req,Department dept) {
dept.setDname(dept.getDname());
dept.setDaddress(dept.getDaddress());
dept.setDepartment_id(dept.getDepartment_id());
String update = service.updateByCount(dept);
req.setAttribute("update", update);
return "/update";
}
@RequestMapping("/delete")
public String deleteByCount(HttpServletRequest req,Department dept) {
dept.setDepartment_id(dept.getDepartment_id());
String delete = service.deleteByCount(dept);
req.setAttribute("delete", delete);
return "/delete";
}
}
JSP頁面 查詢展示頁面
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>部門列表</title>
</head>
<body>
<table border="solid 1px red;" cellspacing="0px" cellpadding="5px" width="600px" >
<thead>
<tr style="text-align: left;">
<form action="insert.jsp" method="post" enctype="application/x-www-form-urlencoded">
<td colspan="3">
<input type="submit" value="新增"/>
</td>
</form>
<form action="delete.jsp" method="post" enctype="application/x-www-form-urlencoded">
<td colspan="3">
<input type="submit" value="刪除"/>
</td>
</form>
</tr>
<tr style="text-align: center;">
<td><input type="checkbox" id="checkAll"/></td>
<th>部門ID</th>
<th>部門名稱</th>
<th>部門地址</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach items="${ list }" var="p">
<tr style="text-align: center;">
<td><input type="checkbox" class="checkSimple" value="${ p.department_id }"/></td>
<th>${ p.department_id }</th>
<th>${ p.dname }</th>
<th>${ p.daddress }</th>
<td><a href="/update.jsp">修改</a></td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
新增介面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>新增</title>
</head>
<body>
<form action="insert" method="post" enctype="application/x-www-form-urlencoded">
<table border="solid 1px red;" cellspacing="0px" cellpadding="5px" width="600px" >
<thead>
<tr style="text-align: center;">
<td><input type="checkbox" id="checkAll"/></td>
<th>部門名稱</th>
<th>部門地址</th>
<th>商品操作</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkSimple"/></td>
<td><input type="text" name="dname" id="dname"></td>
<td><input type="text" name="daddress" id="daddress"></td>
<td><input type="submit" id="add" value="新增"/></td>
</tr>
</tbody>
</table>
<p style="color:red">${insert}</p>
</form>
</body>
</html>
更改介面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改</title>
</head>
<body>
<form action="/update" method="post" enctype="application/x-www-form-urlencoded">
<table border="solid 1px red;" cellspacing="0px" cellpadding="5px" width="600px" >
<thead>
<tr style="text-align: center;">
<td><input type="checkbox" id="checkAll"/></td>
<th>部門ID</th>
<th>部門名稱</th>
<th>部門地址</th>
<th>商品操作</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkSimple"/></td>
<td><input type="text" name="department_id" id="department_id"></td>
<td><input type="text" name="dname" id="dname"></td>
<td><input type="text" name="daddress" id="daddress"></td>
<td><input type="submit" id="update" value="修改"/></td>
</tr>
</tbody>
</table>
<p style="color: red">${update}</p>
<a href="/select">返回</a>
</form>
</body>
</html>
刪除介面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>刪除</title>
</head>
<body>
<form action="/delete" method="post" enctype="application/x-www-form-urlencoded">
<table border="solid 1px red;" cellspacing="0px" cellpadding="5px" width="600px" >
<thead>
<tr style="text-align: center;">
<td><input type="checkbox" id="checkAll"/></td>
<th>部門ID</th>
<th>商品操作</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkSimple"/></td>
<td><input type="text" name="department_id" id="department_id"></td>
<td><input type="submit" id="delete" value="刪除"/></td>
</tr>
</tbody>
</table>
<p style="color: red">${delete}</p>
<a href="/select">返回</a>
</form>
</body>
</html>