struts2+MyBatis框架整合
Hibernate,为了DAO的ORMapping,生生把SQL的优良特性给腰斩完蛋了。比起来更喜欢MyBatis,不失SQL的灵活。
但,MyBatis怎么挂载到Struts2中呢?搜遍大江南北都是利用Spring——你们还有没有点新鲜玩意儿?说白了,就是我这个小小的项目用Sping不是杀鸡用牛刀吗,而且Sping的复杂度让人望而却步。
所以我们现在用一个MybatisUtil工具类,实现sqlSessionFactory连接
在映射类Dao中实现一个DaoImpl,来简易方便,使用struts2+MyBatis框架整合的技术。
项目结构目录图:
src:
WebRoot:
配置Struts2: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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<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>
</web-app>
一步:编写实体类,映射类操作接口和具体实现类
public class UserInfo {
private String userid;
private String username;
private String userpwd;
private int userStatus;//默认为0,正常。1为注销
private Date userTime;
get……set 方法
}
public interface IUserInfo {
public UserInfo findByName(String username);
//public UserInfo findById(String userid);
public void insertUser(UserInfo user);
//public void updateToLock(Map map);
//public void updateToFailedCount(Map map);
//public void updateToIsOrNotActive(Map map);
public void updateToPwd(Map map);
//public void updateToPwdChangeTime(Map map);
//public void updateToIsOrNotFirst(Map map);
public void deleteUser(UserInfo user);
}
IUserInfoImpl.java
public class IUserInfoImpl implements IUserInfo {
public void deleteUser(UserInfo user) {
SqlSession session = MybatisUtils.currentSession();
IUserInfo iUserInfoDao = session.getMapper(IUserInfo.class);
iUserInfoDao.deleteUser(user);
session.commit();
MybatisUtils.closeSession();
}
public UserInfo findByName(String username) {
SqlSession session = MybatisUtils.currentSession();
IUserInfo iUserInfoDao = session.getMapper(IUserInfo.class);
return iUserInfoDao.findByName(username);
}
public void insertUser(UserInfo user) {
SqlSession session = MybatisUtils.currentSession();
IUserInfo iUserInfoDao = session.getMapper(IUserInfo.class);
iUserInfoDao.insertUser(user);
session.commit();
MybatisUtils.closeSession();
}
public void updateToPwd(Map map) {
SqlSession session = MybatisUtils.currentSession();
IUserInfo iUserInfoDao = session.getMapper(IUserInfo.class);
iUserInfoDao.updateToPwd(map);
session.commit();
MybatisUtils.closeSession();
}
}
二步:编写接口映射器,UserMap.xml,和MyBatis部署配置文件
UserMap.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.cloudycd.yanmj.dao.IUserInfo">
<resultMap type="UserInfo" id="userResultMap">
<id property="userid" column="USERID"/>
<result property="username" column="USERNAME"/>
<result property="userpwd" column="USERPWD"/>
<result property="userStatus" column="USERSTATUS"/>
<result property="userTime" column="USERTIME"/>
</resultMap>
<select id="findByName" parameterType="String" resultMap="userResultMap">
SELECT * FROM USERINFO SU
WHERE SU.USERNAME = #{username}
</select>
<!--
<select id="findById" parameterType="String" resultMap="userResultMap">
SELECT * FROM USERINFO SU
WHERE SU.USERNAME = #{userid}
</select>
-->
<insert id="insertUser" parameterType="UserInfo">
INSERT INTO USERINFO(USERID,USERNAME,USERPWD,USERSTATUS,USERTIME)
VALUES(#{userid},#{username},#{userpwd},#{userStatus},#{userTime})
</insert>
<update id="updateToPwd" parameterType="Map">
UPDATE USERINFO SU
SET SU.USERPWD= #{userpwd}
WHERE SU.USERNAME= #{username}
</update>
<delete id="deleteUser" parameterType="UserInfo">
DELETE FROM USERINFO
WHERE USERNAME = #{username}
</delete>
</mapper>
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>
<typeAliases>
<typeAlias alias="UserInfo" type="com.cloudycd.yanmj.entity.UserInfo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/userlogin"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/cloudycd/yanmj/dao/UserMap.xml" />
</mappers>
</configuration>
三步:配置Struts2.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="strtus.i18n.encoding" value="UTF-8" />
<package name="userlogin" extends="struts-default">
<action name="login">
<result>/jsp/userLogin.jsp</result>
</action>
<action name="backlogin">
<result>/jsp/userLogin.jsp</result>
</action>
<action name="toregister">
<result>/jsp/register.jsp</result>
</action>
<action name="modifyPwd">
<result>/jsp/modifyPwd.jsp</result>
</action>
<action name="deleteUser">
<result>/jsp/deleteUser.jsp</result>
</action>
<action name="loginAction" class="com.cloudycd.yanmj.action.LoginAction">
<result name="success">/jsp/logined.jsp</result>
<result name="input">/jsp/userLogin.jsp</result>
<result name="error">/jsp/loginfailed.jsp</result>
<result name="modifypwd">/jsp/modifyPwd.jsp</result>
</action>
<!-- <action name="toActivateAction" class="com.cloudycd.yanmj.action.ToActivateAction">
<result name="success">/jsp/logined.jsp</result>
</action>
-->
<action name="modifyPwdAction" class="com.cloudycd.yanmj.action.ModifyPwdAction">
<result name="userlogin">/jsp/userLogin.jsp</result>
<result name="input">/jsp/modifyPwd.jsp</result>
<result name="ReLogin">/jsp/userLogin.jsp</result>
</action>
<action name="registerAction" class="com.cloudycd.yanmj.action.RegisterAction">
<!-- <result name="success" type="redirect">loginAction.action</result>-->
<result name="success">/jsp/userLogin.jsp</result>
<result name="input">/jsp/register.jsp</result>
</action>
<action name="deleteUserAction" class="com.cloudycd.yanmj.action.DeleteUserAction">
<!-- <result name="success" type="redirect">loginAction.action</result>-->
<result name="success">/jsp/deleteUser.jsp</result>
<result name="error">/jsp/deleteUser.jsp</result>
</action>
</package>
</struts>
四步:写ActionSupport:
package com.cloudycd.yanmj.action;
import com.cloudycd.yanmj.dao.IUserInfo;
import com.cloudycd.yanmj.dao.IUserInfoImpl;
import com.cloudycd.yanmj.entity.UserInfo;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private static int failedcount = 0;
private UserInfo userInfo;
private IUserInfo iuinfo ;
public UserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
@Override
public String execute() throws Exception {
//boolean flag = userLogin.checkUsername(userInfo.getUsername());
// 根据username获得userpwd
//System.out.println("flag=" + flag);
//UserInfo uinfo =null;
iuinfo = new IUserInfoImpl();
UserInfo uinfo = iuinfo.findByName(userInfo.getUsername());
System.out.println("userInfo.userpwd=" + userInfo.getUserpwd() + ",userInfo.username=" +userInfo.getUsername());
System.out.println("uinfo.userpwd=" + uinfo.getUserpwd() + ",uinfo.username=" +uinfo.getUsername());
if (uinfo.getUsername().equals(userInfo.getUsername())) {
if (!uinfo.getUserpwd().equals(userInfo.getUserpwd())) {
if (failedcount == 3) {
// 记录failedcount+1,并记录当前时间errortime和修改ISORNOTLOCK锁定状态
uinfo.getUsername();
this.addActionMessage("sorry! 密码不正确!登录错误次数已经3次,请于10分钟后再尝试登录。");
}else {
failedcount++;
this.addActionMessage("sorry! 密码不正确!");
}
return "error";
} else {
//修改为:userStatus,0:正常,1:注销
// 如果密码匹配
if (uinfo.getUserStatus() == 0) {
// 判断是否是激活的,如果未激活 ##1:激活 ,0:未激活
this.addActionMessage("用户正常");
return "success";
} else if (uinfo.getUserStatus() == 1) {
this.addActionMessage("用户已注销!");
return "error";
}
}
} else {
this.addActionMessage("不存在的用户!");
return "error";
}
return null;
}
}
ModifyPwdAction .java
package com.cloudycd.yanmj.action;
import java.util.HashMap;
import java.util.Map;
import com.cloudycd.yanmj.dao.IUserInfo;
import com.cloudycd.yanmj.dao.IUserInfoImpl;
import com.cloudycd.yanmj.entity.UserInfo;
import com.opensymphony.xwork2.ActionSupport;
public class ModifyPwdAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private UserInfo userInfo;
private IUserInfo iuserinfo;
public UserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
@Override
public String execute() throws Exception {
iuserinfo = new IUserInfoImpl();
UserInfo uinfo = iuserinfo.findByName(userInfo.getUsername());
if(uinfo.getUsername().equals(userInfo.getUsername())){
//修改密码
Map map=new HashMap();
map.put("username",userInfo.getUsername());
map.put("userpwd", userInfo.getUserpwd());
iuserinfo.updateToPwd(map);
this.addActionMessage("密码修改成功,请重新登陆");
return "userlogin";
}else{
this.addActionMessage("用户名、密码错误,请重新输入");
return "ReLogin";
}
}
}
RegisterAction.java
package com.cloudycd.yanmj.action;
import java.util.Date;
import com.cloudycd.yanmj.dao.IUserInfo;
import com.cloudycd.yanmj.dao.IUserInfoImpl;
import com.cloudycd.yanmj.entity.UserInfo;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private UserInfo userInfo;
private IUserInfo iuserinfo;
public UserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
@Override
public String execute() throws Exception {
iuserinfo = new IUserInfoImpl();
userInfo.setUserTime(new Date());
iuserinfo.insertUser(userInfo);
userInfo.printUserInfo();
this.addActionMessage("register success!");
return "success";
}
}
DeleteUserAction .java
package com.cloudycd.yanmj.action;
import com.cloudycd.yanmj.dao.IUserInfo;
import com.cloudycd.yanmj.dao.IUserInfoImpl;
import com.cloudycd.yanmj.entity.UserInfo;
import com.opensymphony.xwork2.ActionSupport;
public class DeleteUserAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private UserInfo userInfo;
private IUserInfo iuserinfo;
public UserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
@Override
public String execute() throws Exception {
iuserinfo = new IUserInfoImpl();
iuserinfo.deleteUser(userInfo);
userInfo.printUserInfo();
this.addActionMessage("delete success!");
return "success";
}
}
五步:编写jsp页面
userLogin.jsp
<div id="global">
<s:actionmessage/>
<s:fielderror></s:fielderror>
<form action="loginAction.action" method="post">
USERNAME:<input type="text" name="userInfo.username">
PASSWORD:<input type="password" name="userInfo.userpwd"><br>
<input type="submit" value="LOGIN">
<input type="reset" value="reset"><br>
<a href="toregister.action">register</a>
<a href="modifyPwd.action">Change the password</a>
<a href ="deleteUser.action">Delete the User</a>
</form>
</div>
deleteUser.jsp
<div id="global">
<s:actionmessage/>
<form action="deleteUserAction.action" method="post">
USERNAME:<input type="text" name="userInfo.username">
<input type="submit" value="GO">
<s:fielderror></s:fielderror>
</form>
</div>
<a href ="index.jsp">返回登录页面</a>
</body>
logined.jsp
<div id="div_logined">
<s:actionmessage/>
<h3>WELCOME </h3><p>${UserInfo.username }</p>
</div>
<a href ="index.jsp">返回登录页面</a>
</body>
modifyPwd.jsp
<div id="global">
<s:actionmessage/>
<form action="modifyPwdAction.action" method="post">
USERNAME<input type="text" name="userInfo.username"/>
new password:<input type="password" name="userInfo.userpwd">
<input type="submit" value="GO">
<s:fielderror></s:fielderror>
</form>
</div>
register.jsp
<div id="global">
<s:actionmessage/>
<form action="registerAction.action" method="post">
<h4>user register</h4>
USERID: <input type="text" name="userInfo.userid"><br>
USERNAME: <input type="text" name="userInfo.username"><br>
PASSWORD: <input type="password" name="userInfo.userpwd"><br>
USERSTATUS:<input type="text" name = "userInfo.userStatus"><br>
<input type="hidden" name ="userInfo.userTime">
<input type="submit" value="GO">
<s:fielderror></s:fielderror>
</form>
</div>