6、Spring+Struts2+MyBatis(mybatis有代理)整合增删改查

时间:2021-06-24 20:37:26

1、创建如下的oracle脚本

  create table userinfo
(id number(4),
name varchar2(50),
password varchar2(20
telephone varchar2(15),
isadmin varchar2(5)); --4.2 用户表序列
create sequence seq_userinfo; alter table userinfo add constraint pk_userinfo_id primary key(id); insert into userinfo values(seq_userinfo.nextval,'holly','','134518024
','是'); commit;

userinfo.sql

2、创建如下项目结构

6、Spring+Struts2+MyBatis(mybatis有代理)整合增删改查

3、在项目的WebRoot下的WEB-INF下的lib下添加如下jar文件

aopalliance.jar
aspectjweaver.jar
cglib-nodep-2.1_3.jar
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-logging-1.0.4.jar
freemarker-2.3.15.jar
log4j-1.2.8.jar
mybatis-3.2.3.jar
mybatis-spring-1.2.1.jar
ognl-2.7.3.jar
ojdbc14.jar
org.springframework.aop-3.0.2.RELEASE.jar
org.springframework.asm-3.0.2.RELEASE.jar
org.springframework.beans-3.0.2.RELEASE.jar
org.springframework.context-3.0.2.RELEASE.jar
org.springframework.core-3.0.2.RELEASE.jar
org.springframework.expression-3.0.2.RELEASE.jar
org.springframework.jdbc-3.0.2.RELEASE.jar
org.springframework.orm-3.0.2.RELEASE.jar
org.springframework.transaction-3.0.2.RELEASE.jar
org.springframework.web-3.0.2.RELEASE.jar
struts2-core-2.1.8.1.jar
struts2-spring-plugin-2.1.8.1.jar
xwork-core-2.1.6.jar

4、在src下的com.bean包下创建UserInfo.java

 package com.bean;

 public class UserInfo {
private Integer id;
private String name;
private String password;
private String telephone;
private String isadmin; public UserInfo() { }
public UserInfo(Integer id, String name, String password, String telephone,
String isadmin) {
this.id = id;
this.name = name;
this.password = password;
this.telephone = telephone;
this.isadmin = isadmin;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getIsadmin() {
return isadmin;
}
public void setIsadmin(String isadmin) {
this.isadmin = isadmin;
}
@Override
public String toString() {
return "UserInfo [id=" + id + ", isadmin=" + isadmin + ", name=" + name
+ ", password=" + password + ", telephone=" + telephone + "]";
} }

UserInfo.java

5、在src下的com.dao包下创建UserInfoDao.java

 package com.dao;

 import java.util.List;

 import com.bean.UserInfo;
/**
* mybatis映射文件的dao接口
* @author pc
*
*/
public interface UserInfoDao {
public List<UserInfo> findAll(); //查所有
public UserInfo findUser(UserInfo user);//条件查询
public void insertUser(UserInfo user); //插入对象
public void updateUser(UserInfo user); //修改对象
public void deleteUser(int id); //条件删除 }

UserInfoDao.java

6、在src下的com.dao包下创建UserInfoDao.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" >
<mapper namespace="com.dao.UserInfoDao">
<select id="findAll" resultType="user">
select * from userinfo
</select>
<select id="findUser" resultType="user" parameterType="user">
select * from userinfo where name=#{name} and password=#{password}
</select>
<insert id="insertUser" parameterType="user">
insert into userinfo values(seq_userinfo.nextval,#{name},#{password},#{telephone},#{isadmin})
</insert>
<update id="updateUser" parameterType="user">
update userinfo set name=#{name},password=#{password},telephone=#{telephone},isadmin=#{isadmin} where id=#{id}
</update> <delete id="deleteUser" parameterType="int">
delete from userinfo where id=#{id}
</delete>
</mapper>

UserInfoDao.xml

7、在src下创建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>
<!-- mybatis映射文件的别名配置 -->
<typeAliases>
<typeAlias type="com.bean.UserInfo" alias="user"/>
</typeAliases> <!-- 注册mybatis的映射文件 -->
<mappers>
<mapper resource="com/dao/UserInfoDao.xml"/>
</mappers>
</configuration>

mybatis-config.xml

8、在src下的com.dao.impl包下创建UserInfoDaoImpl.java

 package com.dao.impl;

 import java.util.List;

 import org.mybatis.spring.SqlSessionTemplate;

 import com.bean.UserInfo;
import com.dao.UserInfoDao;
/**
* 数据dao接口实现类
* @author pc
*
*/
public class UserInfoDaoImpl implements UserInfoDao {
private SqlSessionTemplate sqlSession;
/**
* 根据id删除
*/
public void deleteUser(int id) {
//获取代理对象
UserInfoDao dao=sqlSession.getMapper(UserInfoDao.class);
try {
dao.deleteUser(id); //调用代理对象映射的dao接口删除
sqlSession.commit(); //提交事务
System.out.println("删除成功");
} catch (Exception e) {
System.out.println("删除失败");
e.printStackTrace();
}
}
/**
* 查询所有
*/
public List<UserInfo> findAll() {
//获取代理对象
UserInfoDao dao=sqlSession.getMapper(UserInfoDao.class);
List<UserInfo> list=null;
try {
list=dao.findAll();
System.out.println("查询所有成功");
} catch (Exception e) {
System.out.println("查询所有失败");
e.printStackTrace();
}
return list;
} /**
* 条件查询
*/
public UserInfo findUser(UserInfo user) {
//获取代理对象
UserInfoDao dao=sqlSession.getMapper(UserInfoDao.class);
UserInfo userinfo=null;
try {
if(user!=null){
userinfo=dao.findUser(user);
System.out.println("条件查询成功");
}else{
System.out.println("条件查询参数为空");
}
} catch (Exception e) {
System.out.println("条件查询失败");
e.printStackTrace();
}
return userinfo;
}
/**
*添加
*/
public void insertUser(UserInfo user) {
//获取代理对象
UserInfoDao dao=sqlSession.getMapper(UserInfoDao.class);
try {
if(user!=null){
dao.insertUser(user);
sqlSession.commit(); //提交事务
System.out.println("添加成功");
}else{
System.out.println("添加参数为空");
}
} catch (Exception e) {
System.out.println("添加失败");
e.printStackTrace();
} }
/**
* 修改对象
*/
public void updateUser(UserInfo user) {
//获取代理对象
UserInfoDao dao=sqlSession.getMapper(UserInfoDao.class);
try {
if(user!=null){
dao.updateUser(user);
sqlSession.commit(); //提交事务
System.out.println("修改成功");
}else{
System.out.println("修改参数为空");
}
} catch (Exception e) {
System.out.println("修改失败");
e.printStackTrace();
}
}
public SqlSessionTemplate getSqlSession() {
return sqlSession;
}
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
} }

UserInfoDaoImpl.java

9、在src下的com.service包下创建UserInfoService.java

 package com.service;

 import java.util.List;

 import com.bean.UserInfo;
/**
* 服务接口
* @author pc
*
*/
public interface UserInfoService {
public List<UserInfo> findAll(); //查所有
public UserInfo findUser(UserInfo user);//条件查询
public void insertUser(UserInfo user); //插入对象
public void updateUser(UserInfo user); //修改对象
public void deleteUser(int id); //条件删除 }

UserInfoService.java

9、在src下的com.service.impl包下创建UserInfoServiceImpl.java

 package com.service.impl;

 import java.util.List;

 import com.bean.UserInfo;
import com.dao.UserInfoDao;
import com.dao.impl.UserInfoDaoImpl;
import com.service.UserInfoService; public class UserInfoServiceImpl implements UserInfoService{
//引入数据层接口
UserInfoDao dao=new UserInfoDaoImpl();
/**
* 删除
*/
public void deleteUser(int id) {
dao.deleteUser(id);
}
/**
* 查所有
*/
public List<UserInfo> findAll() {
return dao.findAll();
}
/**
* 条件查询
*/
public UserInfo findUser(UserInfo user) {
return dao.findUser(user);
}
/**
* 插入对象
*/
public void insertUser(UserInfo user) {
dao.insertUser(user);
}
/**
* 修改对象
*/
public void updateUser(UserInfo user) {
dao.updateUser(user);
} public UserInfoDao getDao() {
return dao;
}
public void setDao(UserInfoDao dao) {
this.dao = dao;
} }

UserInfoServiceImpl.java

10、在src下的com.action包下创建UserInfoAction.java

 package com.action;

 import com.bean.UserInfo;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
import com.service.UserInfoService;
import com.service.impl.UserInfoServiceImpl;
/**
*
* @author pc
* ActionSupport可以最数据校验
*/
public class UserInfoAction extends ActionSupport { /**
* 引用服务层对象
*/
private UserInfoService service=new UserInfoServiceImpl();
/**
* 对象用于接收请求中的值
* 必须创建setter和getter方法,代理对象才能获取或设置
*/
private UserInfo user;
/**
* 登录
* @return
*/
public String login(){ if(user!=null){
System.out.println("登录表单值接收到");
UserInfo userinfo=service.findUser(user);
if(userinfo!=null){
System.out.println("登录陈宫");
return SUCCESS; }else{
return ERROR;
} }else{
System.out.println("登录表单值没有接收到");
return ERROR; }
} /**
* 注册
* @return
*/
public String register(){
if(user!=null){
System.out.println("注册表单值接收到");
service.insertUser(user);
System.out.println("action注册成功");
return SUCCESS; }else{
System.out.println("注册表单值没有接收到");
return ERROR; }
} public UserInfoService getService() {
return service;
} public void setService(UserInfoService service) {
this.service = service;
} public UserInfo getUser() {
return user;
} public void setUser(UserInfo user) {
this.user = user;
} }

UserInfoAction.java

11、在src下创建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 ">
<!-- 1.配置数据源 -->
<bean id="oracleDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>
<property name="username" value="scott"/>
<property name="password" value="tiger"/>
</bean> <!-- 3.事务管理session工厂 -->
<!-- 事务配置 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="oracleDataSource"/>
</bean> <!--2.在sqlSessionFactory中注入数据源 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据源 -->
<property name="dataSource" ref="oracleDataSource"/> <!-- 引用mybatis的主配置文件,(注册dao映射文件) -->
<property name="configLocation">
<value>classpath:mybatis-config.xml</value>
</property>
</bean> <!-- 3.用构造获取sqlSessionTemplate -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory"/>
</bean> <!-- 4.dao注入sqlSesson -->
<bean id="userdao" class="com.dao.impl.UserInfoDaoImpl">
<property name="sqlSession" ref="sqlSessionTemplate"/>
</bean> <!-- 5.service注入dao -->
<bean id="servicedao" class="com.service.impl.UserInfoServiceImpl">
<property name="dao" ref="userdao"/>
</bean> <!-- 6.在Action中注入service -->
<bean id="userAction" class="com.action.UserInfoAction">
<property name="service" ref="servicedao"/>
</bean>
</beans>

applicationContext.xml

12、在src下创建struts.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "struts-2.1.dtd" >
<struts>
<!-- 中文乱码处理 -->
<constant name="struts.i18n.encoding" value="UTF-8"/> <package name="default" namespace="/" extends="struts-default"> <!-- method是对应action类的有返回值的方法名 -->
<!-- 登录,注册,通配符设置,动态调用方法,*表示Login或register -->
<action name="*" class="userAction" method="{1}">
<result name="input">{1}.jsp</result>
<result name="success">success.jsp</result>
<result name="error">error.jsp</result>
</action> </package>
</struts>

struts.xml

13、编辑WebRoot下的WEB-INF下的web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<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>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter> <filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list> </web-app>

web.xml

14、在WebRoot下创建register.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 'index.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>
<center>
<fieldset style="width:400px;">
<legend>注册</legend>
<form action="registerUser.action" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="user.name"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="user.password"/></td>
</tr>
<tr>
<td>电话号码:</td>
<td><input type="text" name="user.telephone"/></td>
</tr>
<tr>
<td>是否是管理员:</td>
<td>
<input type="radio" name="user.isadmin" value="是">
<input type="radio" name="user.isadmin" value="否" checked="checked"/>
</td>
</tr>
<tr>
<td><input type="submit" value="提交"/></td>
<td><input type="reset" value="重置"/></td>
</tr>
</table> </form>
</fieldset>
</center>
</body>
</html>

register.jsp

15、在WebRoot下创建login.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 'index.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>
<center>
<fieldset style="width:400px;">
<legend>登录</legend>
<form action="login.action" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="user.name"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="user.password"/></td>
</tr>
<tr>
<td><input type="submit" value="提交"/></td>
<td><input type="reset" value="重置"/></td>
</tr>
</table> </form>
</fieldset>
</center>
</body>
</html>

login.jsp

16、在WebRoot下创建success.jsp

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<%
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 'index.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>
<h1>操作成功</h1>
<s:if test="user.name eq 'holly'">
holly你来啦?
</s:if>
<s:else>
我不认识你?你是谁?
</s:else>
</body>
</html>

success.jsp

17、在WebRoot下创建error.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 'index.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>
操作失败!
</body>
</html>

error.jsp

18、运行

<%@ 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 'index.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>    <center>      <fieldset style="width:400px;">        <legend>注册</legend>        <form action="registerUser.action" method="post">        <table>          <tr>              <td>用户名:</td>              <td><input type="text" name="user.name"/></td>          </tr>          <tr>               <td>密码:</td>               <td><input type="password" name="user.password"/></td>           </tr>          <tr>               <td>电话号码:</td>               <td><input type="text" name="user.telephone"/></td>           </tr>          <tr>               <td>是否是管理员:</td>               <td>               <input type="radio" name="user.isadmin" value="是">               <input type="radio" name="user.isadmin" value="否" checked="checked"/>               </td>           </tr>          <tr>               <td><input type="submit" value="提交"/></td>               <td><input type="reset" value="重置"/></td>           </tr>        </table>                </form>      </fieldset>    </center>  </body></html>