SSH整合jar包分享及登陆实例详解
相关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; } }