最下方是代码但不建议直接使用,自己搭一下环境印象更加深刻。
Spring介绍:
spring 使用基本的 JavaBean 来完成以前只可能由 EJB 完成的事情。然而, Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java 应用都可以从 Spring 中受益。 简单来说, Spring 是一个轻量级的控制反转(IoC )和面向切面( AOP )的容器框架。
SpringMVC介绍
MyBatis介绍
创建数据库、表 t_user user_t【最下面有sql语句】
1.项目整体结构,上一篇已经介绍了搭建maven环境
2.Eclipse下创建Maven项目
配置文件更改。由于maven没有oracle的jar包所以要自己下载,我的工程里有对应的jar包。
pom.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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.zch</groupId>
<artifactId>portal</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>portal Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 1.日志 -->
<!-- 实现slf4j接口并整合 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- DAO: MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
<!-- 3.Servlet web -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- 4.Spring -->
<!-- 1)Spring核心 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- 2)Spring DAO层 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- 3)Spring web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- 4)Spring test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- redis客户端:Jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.0.8</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.0.8</version>
</dependency>
<!-- Map工具类 -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
1.UserMapper.xml
<?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">
<!--
namespace:必须与对应的接口全类名一致 UserMapper.java
id :必须与对应接口的某个对应的方法名一致即必须要和UserMapper.java接口中的方法同名。
-->
<mapper namespace="org.portal.dao.UserMapper">
<insert id="save" parameterType="User">
insert into t_user(user_name,user_age) values(#{userName},#{age})
</insert>
<update id="update" parameterType="User">
update t_user set user_name=#{userName},user_age=#{age} where user_id=#{id}
</update>
<delete id="delete" parameterType="int">
delete from t_user where user_id=#{id}
</delete>
<!-- mybsits_config中配置的alias类别名,也可直接配置resultType为类路径 -->
<select id="findById" parameterType="int" resultType="User">
select user_id id,user_name userName,user_age age from t_user where user_id=#{id}
</select>
<select id="findAll" resultType="User">
select user_id id,user_name userName,user_age age from t_user
</select>
</mapper>
2.applicationContext-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
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">
<!-- 配置整合mybatis过程 -->
<!-- 1.配置数据库相关参数properties的属性:${url} -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 2.数据库连接池 -->
<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>
<!-- mybatis config -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="org.portal.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</beans>
3.applicationContext-service.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
<context:component-scan base-package="org.portal.service"></context:component-scan>
</beans>
4.applicationContext-trans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
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-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
<!-- 配置事务管理器 -->
<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="save*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="create*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="select*" propagation="SUPPORTS" read-only="true" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* org.portal.service.impl.*.*(..))" />
</aop:config>
</beans>
5.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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
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-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
<context:component-scan base-package="org.portal.controller"/>
<!-- 配置处理器映射器 适配器 -->
<mvc:annotation-driven />
<mvc:resources location="/" mapping="/**/*.js"/>
<mvc:resources location="/" mapping="/**/*.css"/>
<mvc:resources location="/assets/" mapping="/assets/**/*"/>
<mvc:resources location="/images/" mapping="/images/*" cache-period="360000"/>
<!-- 配置视图解释器 jsp -->
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
6.jdbc.properties
jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username=zjuser
jdbc.password=zjpass
#c3p0\u8FDE\u63A5\u6C60\u4FE1\u606F
c3p0.minPoolSize=3
c3p0.maxPoolSize=25
7.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>
<settings>
<!-- changes from the defaults -->
<setting name="lazyLoadingEnabled" value="false" />
<!-- JdbcType enumeration. Most common are: NULL, VARCHAR and OTHER -->
<setting name="jdbcTypeForNull" value="NULL" />
</settings>
<typeAliases>
<typeAlias alias="User" type="org.portal.entity.User" />
</typeAliases>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
接下来写java类;
1.UserController
package org.portal.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.portal.entity.User;
import org.portal.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 获取所有用户列表
* @param request
* @return
*/
@RequestMapping("/getAllUser")
public String getAllUser(HttpServletRequest request,Model model){
List<User> user = userService.findAll();
model.addAttribute("userList", user);
request.setAttribute("userList", user);
return "/allUser";
}
/**
* 跳转到添加用户界面
* @param request
* @return
*/
@RequestMapping("/toAddUser")
public String toAddUser(){
return "/addUser";
}
/**
* 添加用户并重定向
* @param user
* @param request
* @return
*/
@RequestMapping("/addUser")
public String addUser(User user,Model model){
userService.save(user);
return "redirect:/user/getAllUser";
}
/**
*编辑用户
* @param user
* @param request
* @return
*/
@RequestMapping("/updateUser")
public String updateUser(User user,HttpServletRequest request,Model model){
if(userService.update(user)){
user = userService.findById(user.getId());
request.setAttribute("user", user);
model.addAttribute("user", user);
return "redirect:/user/getAllUser";
}else{
return "/error";
}
}
/**
* 根据id查询单个用户
* @param id
* @param request
* @return
*/
@RequestMapping("/getUser")
public String getUser(int id,HttpServletRequest request,Model model){
request.setAttribute("user", userService.findById(id));
model.addAttribute("user", userService.findById(id));
return "/editUser";
}
/**
* 删除用户
* @param id
* @param request
* @param response
*/
@RequestMapping("/delUser")
public void delUser(int id,HttpServletRequest request,HttpServletResponse response){
String result = "{\"result\":\"error\"}";
if(userService.delete(id)){
result = "{\"result\":\"success\"}";
}
response.setContentType("application/json");
try {
PrintWriter out = response.getWriter();
out.write(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.UserMapper
package org.portal.dao;
import java.util.List;
import org.portal.entity.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper {
void save(User user);
boolean update(User user);
boolean delete(int id);
User findById(int id);
List<User> findAll();
}
3.User
package org.portal.entity;
public class User {
private int id;
private String userName;
private String age;
@Override
public String toString() {
return "User [id=" + id + ", age=" + age + ", userName=" + userName
+ "]";
}
public User(){
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public User(int id, String age, String userName) {
super();
this.id = id;
this.age = age;
this.userName = userName;
}
}
4.UserService
package org.portal.service;
import java.util.List;
import org.portal.entity.User;
public interface UserService {
void save(User user);
boolean update(User user);
boolean delete(int id);
User findById(int id);
List<User> findAll();
}
5.UserServiceImpl
package org.portal.service.impl;
import javax.annotation.Resource;
import org.portal.dao.UserMapper;
import org.portal.entity.User;
import org.portal.service.UserService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
// 此处不再进行创建SqlSession和提交事务,都已交由spring去管理了。
public class UserServiceImpl implements UserService {
@Resource
private UserMapper mapper;
/**
* 根据 id 删除 数据
*/
public boolean delete(int id) {
return mapper.delete(id);
}
/**
* 查询User的全部数据
*/
public List<User> findAll() {
List<User> findAllList = mapper.findAll();
return findAllList;
}
/**
* 根据 id 查询 对应数据
*/
public User findById(int id) {
User user = mapper.findById(id);
return user;
}
/**
* 新增数据
*/
public void save(User user) {
mapper.save(user);
}
/**
* 根据 id 修改对应数据
*/
public boolean update(User user) {
return mapper.update(user);
}
}
接下来是jsp。
1.addUser.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>添加用户</title>
<script type="text/javascript">
function addUser(){
var form = document.forms[0];
form.action = "<%=basePath%>user/addUser";
form.method="post";
form.submit();
}
</script>
</head>
<body>
<h1><%=path%>添加用户<%=basePath%></h1>
<form action="" name="userForm">
姓名:<input type="text" name="userName">
年龄:<input type="text" name="age">
<input type="button" value="添加" οnclick="addUser()">
</form>
</body>
</html>
2.allUser.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%>">
<script type="text/javascript" src="js/jquery-3.1.0.min.js"></script>
<title>用户列表</title>
<script type="text/javascript">
function del(id){
$.get("<%=basePath%>user/delUser?id=" + id,function(data){
if("success" == data.result){
alert("删除成功");
window.location.reload();
}else{
alert("删除失败");
}
});
}
</script>
</head>
<body>
<h6><a href="<%=basePath%>user/toAddUser">添加用户</a></h6>
<table border="1">
<tbody>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
<c:if test="${!empty userList }">
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.userName }</td>
<td>${user.age }</td>
<td>
<a href="<%=basePath%>user/getUser?id=${user.id}">编辑</a>
<a href="javascript:del('${user.id }')">删除</a>
<%-- <a href="<%=basePath%>user/delUser?id=${user.id}">删除</a>
--%> </td>
</tr>
</c:forEach>
</c:if>
</tbody>
</table>
</body>
</html>
3.editUser.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>编辑用户</title>
<script type="text/javascript">
function updateUser(){
var form = document.forms[0];
form.action = "<%=basePath%>user/updateUser";
form.method="post";
form.submit();
}
</script>
</head>
<body>
<h1>添加用户</h1>
<form action="" name="userForm">
<input type="hidden" name="id" value="${user.id }"/>
姓名:<input type="text" name="userName" value="${user.userName }"/>
年龄:<input type="text" name="age" value="${user.age }"/>
<input type="button" value="编辑" οnclick="updateUser()"/>
</form>
</body>
</html>
注意这里使用的jquery,需要引入对应的juery
在oracle中创建自己所需要的表
CREATE TABLE t_user (
user_id INT NOT NULL ,
user_name varchar(20) NOT NULL,
user_age varchar(20) NOT NULL,
PRIMARY KEY (user_id)
)
INSERT INTO t_user VALUES ('2', '朱佳鹏', '25');
INSERT INTO t_user VALUES ('3', '傻狍子', '150');
INSERT INTO t_user VALUES ('4', 'jiuqiyuliang', '23');
INSERT INTO t_user VALUES ('5', 'jiuqiyuliang', '23');
INSERT INTO t_user VALUES ('6', 'jiuqiyuliang', '23');
INSERT INTO t_user VALUES ('7', 'jiuqiyuliang', '23');
INSERT INTO t_user VALUES ('9', 'liyintao123', '23123');
SELECT * FROM t_user;
CREATE TABLE user_t (
id INT NOT NULL ,
user_name varchar(40) NOT NULL,
password varchar(255) NOT NULL,
age INT NOT NULL,
PRIMARY KEY (id)
)
INSERT INTO user_t VALUES ('1', '测试', 'sfasgfaf', '24');
SELECT * FROM t_user。
至此一个完整的ssm框架下的增删改查工程的系统做好了。
、
以下是对应的代码。
https://files.cnblogs.com/files/cyz110/ssmproduct.rar