相关jar包分享:struts2+hibernate3+spring3 以及aop ,mysql,以及整合必须包。
链接:https://pan.baidu.com/s/1nCHmSsKU0hiV8DTj_V03sQ 密码:29nf
在学习spring和hibernate的基础后,试着将三大框架整合,下面以登陆为例,作为学习笔记供初学者参考。
总结一下思路:
第一步:从客户端获取用户输入数据,即用户名和密码,然后交给action处理。
第二步:action需要使用service接口提供的功能,如登陆,注册,修改信息等,并返回执行结果,然后给用户响应。
第三步:service层负责业务逻辑,通过dao接口来增删改查数据库中多个表的数据,从而完成一个功能,实际应用中不可能像登陆这么简单。
第四步:hibernate完成了实体类持久化,所有dao层负责对model层实体类的管理,即实现了对表数据的管理。
另外使用了事物管理器,使事物的管理更加规范,代码也更加简洁,这里不做介绍,可以参考其他文章。
web.xml配置代码:
注:其中这里applicationContext.xml放在src目录下,需用classpath指明。(系统默认的applicationContext.xml文件是在WEB-INF下)
<!-- 配置Spring的核心监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param> <!-- 配置structs2 -->
<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>*.do</url-pattern>
</filter-mapping>
login.jsp代码:
<form method="post" onsubmit="return loginCheck()" id="loginForm">
<div>
<input type="text" id="name"/>
</div>
<div>
<input type="password" id="pass"/>
</div>
<button id="submit" type="submit">登 录</button>
</form>
在这里并没有用action="login.do"的方式提交表单,而是使用ajax异步请求,读者若不理解可以使用传统的方式,下面做简单的介绍:
格式:$.ajax({type:'',data:'',async:''...})
参数:
cache: true缓存页面 false不缓存页面
type:get/post
data:发送到服务器的数据,必须为Object/String类型,对象必须为key/value格式
dataType:想要服务器返回数据的类型
success:(data,textStatus,jqXHR):请求成功后的回调函数。参数:由服务器返回,并根据dataType参数进行处理后的数据;描述状态的字符串。还有 jqXHR(在jQuery 1.4.x的中,XMLHttpRequest) 对象 。在jQuery 1.5, 成功设置可以接受一个函数数组。每个函数将被依次调用。
点击登陆按钮执行loginCheck()函数,代码如下:
//登陆按钮事件
function loginCheck(){
$.ajax({
url:"${pageContext.request.contextPath}/wp/login.do",
data:{
username:function(){
return $("#name").val();//注:用id为name的值赋值给username(对应Action属性里的username)
},
password:function(){
return $("#pass").val();
}
},
dataType:"json",
cache:false,
type:"POST",
success:function(data){
if(data =='ok'){
alert("登陆成功!");
} else{
alert("登陆失败!");
}
},
});
return false;
}
loginAction代码:
public class loginAction extends ActionSupport{
private String username;
private String password;
private UserService userService;//业务逻辑层的接口
private User user;
public String checkresult;//判断结果,以json的方式传给ajax public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService){
this.userService = userService;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String login(){
this.user=userService.getUserByLoginname(username);
if(user!=null&&user.getPassword().equals(password)){
//System.out.println("success");
ActionContext actionContext=ActionContext.getContext();
actionContext.getSession().put("user", user);
this.checkresult = "ok";
}else{
this.checkresult ="err";
}
return SUCCESS;
} public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getcheckresult() {
return this.checkresult;
}
}
struts.xml代码:
<package name="user" namespace="/" extends="json-default">
<action name="login" class="loginAction" method="login">
<result type="json">
<param name="root">checkresult</param>
</result>
</action>
</package>
以上已经完成表现层的设计,下面我们要具体的设计业务逻辑层和数据访问层,在这之前我们要先说明下各个文件的放置位置。
首先我们在包目录:com.标识公司名.项目名.模块名
下再分别建sevice,dao,action,model四个包,service和dao中新建Impl放接口的实现,一个模块的包结构如下图。
applicationContent.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:util="http://www.springframework.org/schema/util" 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.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
default-lazy-init ="true">
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 启用事务注解扫描 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- User -->
<bean id="user" class="com.user.model.User" lazy-init="false"></bean>
<!--UserDaoImpl-->
<bean id="userDAO" class="com.user.dao.impl.UserDaoImpl">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<!--UserServiceImpl-->
<bean id="userService" class="com.user.service.impl.UserServiceImpl">
<property name="userDAO" ref="userDAO"/>
</bean>
<!--loginAction-->
<bean id="loginAction" class="com.user.action.loginAction" scope="prototype">
<property name="userService" ref="userService"/>
<property name="user" ref="user"/>
</bean>
</beans>
hibernate.cfg.xml :配置数据库的连接池,以及.hbm.xml文件的映射。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/wp</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="com/user/model/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
User-hbm.xml 和User类放在model包下 :xml文件配置与User类的映射,注意与User类的对应,熟悉后可使用工具直接从数据库生成。
数据库user表有三个属性:id,loginname,password
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.user.model.User" table="user" catalog="wp">
<id name="id" type="long">
<column name="id" />
<generator class="identity" />
</id>
<property name="loginName" type="string">
<column name="loginName" length="50" not-null="true" />
</property>
<property name="password" type="string">
<column name="password" length="50" not-null="true" />
</property>
</class>
</hibernate-mapping>
User类:
public class User {
private long id;
private String loginName;
private String password;
public User() {
}
public User(long id, String loginName, String password) {
this.id = id;
this.loginName = loginName;
this.password = password;
} public long getId() {
return this.id;
} public void setId(long id) {
this.id = id;
} public String getLoginName() {
return this.loginName;
} public void setLoginName(String loginName) {
this.loginName = loginName;
} public String getPassword() {
return this.password;
} public void setPassword(String password) {
this.password = password;
} }
UserService接口放在sevice包中,如下所示。
public interface UserService {
public User getUserByLoginname(String username);// 判断用户名是否存在
public boolean save(User user);//注册
public boolean modifyUser(User newuser);//修改用户信息
public boolean updatePass(Long id,String newPassword);//修改密码
}
UserServiceImpl实现了 UserService接口,放在sevice.impl包中。
public class UserServiceImpl implements UserService{
private UserDao userDao; public UserDao getUserDAO(){
return userDAO;
}
public void setUserDAO(UserDao userDAO) {
this.userDAO = userDAO;
}
public User getUserByLoginname(String username){
User user= userDAO.findByLoginname(username);
if(user!=null){
return user;
}
else
return null;
}
public boolean save(User user){
return userDAO.save(user);
}
@Override
public boolean modifyUser(User newuser) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean updatePass(Long id, String newPassword) {
// TODO Auto-generated method stub
return false;
} }
UserDao接口放在dao包中, UserDaoImpl实现接口,放在dao.impl中。
public interface UserDao {
public boolean save(User user) ;
public User getById(Long id);
public User findByLoginname(String username);
public boolean updateUser(User user);
public boolean updateUser(User user,String newpassword);
}
@Transactional//事物注解
public class UserDaoImpl implements UserDao {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public boolean save(User user) {
Session session= sessionFactory.getCurrentSession();
try{
session.save(user);
}catch(HibernateException e){
return false;
}
return true;
}
@Override
public User getById(Long id) {
Session session = sessionFactory.getCurrentSession();
User user=null;
user=(User)session.get(User.class,id);
return user;
}
@Override
public User findByLoginname(String username) {
List<User> users=findByProperty("loginName",username);
if(users!=null&&users.size()==1)
return users.get(0);
return null;
}
public List<User> findByProperty(String PropertyName,Object value){
Session session =sessionFactory.getCurrentSession();
List<User> users=null;
Criteria cr = session.createCriteria(User.class);
cr.add(Restrictions.eq(PropertyName,value));
users=cr.list();
return users;
}
@Override
public boolean updateUser(User user) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean updateUser(User user, String newpassword) {
// TODO Auto-generated method stub
return false;
} }