SSH框架的登录实例
来源:互联网 发布:网络安全工程师考试 编辑:程序博客网 时间:2024/06/02 18:20
这个例子详细地讲叙了如何通过搭建SSH实现用户登录,通过此例子可以了解springMVC基本的控制流程和思想。开发环境:MyEclipse2014,MySql,struts 2.1,spring 3.1, hibernate 3.2
第一步:新建web project工程SSH_TEST。
第二步:导入struts 2框架,此步骤请参考本人以前的文章http://blog.csdn.net/moon__stone888888/article/details/51779256或http://blog.csdn.net/moon__stone888888/article/details/51803997
第三步:导入spring框架,此步骤请参考本人以前的文章http://blog.csdn.net/moon__stone888888/article/details/51779256
第四步:新建数据库logindemo,在此数据库中新建一个表user,字段分别为id(int),username(varchar),password(varchar),配置MySql数据库连接,请参考本人以前的文章:http://blog.csdn.net/moon__stone888888/article/details/51782390
第五步:导入hibernate框架,此步骤请参考本人以前的文章:http://blog.csdn.net/moon__stone888888/article/details/51779256或http://blog.csdn.net/moon__stone888888/article/details/51823886
第六步:使用hibernate自动生成永久的java文件
在src目录下新建com.ssh.user包,邮件logindemo数据库下user表,选择Hibernate ReverseEngineering。弹出一个对话框,此处请参考http://blog.csdn.net/moon__stone888888/article/details/51823886文章的第五步,稍有不同的是,在第一个对话框中勾选“JavaData Access Object(DAO)”
完成对话框的设置,在com.ssh.user下面生成了四个文件,AbstractUser.java,User.jva,User.hbm.xml,UserDAO.java。同时可以看到hibernate.cfg.xml文件里有了User.hbm.xml的映射。
第七步:在src下新建com.ssh.dao的包和com.ssh.dao.impl的包,将UserDAO.java移到com.ssh.dao.impl下,在com.ssh.dao包下建一个接口文件,IUserDAO.java。
UserDAO.java的内容:
packagecom.ssh.dao.impl;
importjava.util.List;
importorg.apache.commons.logging.Log;
importorg.apache.commons.logging.LogFactory;
importorg.hibernate.LockMode;
importorg.springframework.context.ApplicationContext;
importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;
importcom.ssh.dao.IUserDAO;
importcom.ssh.user.User;
/**
* A data access object (DAO) providingpersistence and search support for User
* entities. Transaction control of the save(),update() and delete() operations
* can directly support Springcontainer-managed transactions or they can be
* augmented to handle user-managed Springtransactions. Each of these methods
* provides additional information for how toconfigure it for the desired type
* of transaction control.
*
* @see com.ssh.user.User
* @author MyEclipse Persistence Tools
*/
publicclass UserDAO extends HibernateDaoSupport implements IUserDAO {
private static final Log log =LogFactory.getLog(UserDAO.class);
// property constants
public static final String USERNAME ="username";
public static final String PASSWORD ="password";
protected void initDao() {
// do nothing
}
/* (non-Javadoc)
* @seecom.ssh.dao.impl.IUserDAO#save(com.ssh.user.User)
*/
@Override
public void save(UsertransientInstance) {
log.debug("saving Userinstance");
try {
getHibernateTemplate().save(transientInstance);
log.debug("savesuccessful");
} catch (RuntimeException re){
log.error("savefailed", re);
throw re;
}
}
public void delete(UserpersistentInstance) {
log.debug("deleting Userinstance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("deletesuccessful");
} catch (RuntimeException re){
log.error("deletefailed", re);
throw re;
}
}
/* (non-Javadoc)
* @seecom.ssh.dao.impl.IUserDAO#findById(java.lang.Integer)
*/
@Override
public User findById(java.lang.Integerid) {
log.debug("getting Userinstance with id: " + id);
try {
User instance =(User) getHibernateTemplate().get(
"com.ssh.user.User",id);
return instance;
} catch (RuntimeException re){
log.error("getfailed", re);
throw re;
}
}
public List findByExample(Userinstance) {
log.debug("finding Userinstance by example");
try {
List results =getHibernateTemplate().findByExample(instance);
log.debug("findby example successful, result size: "
+results.size());
return results;
} catch (RuntimeException re){
log.error("findby example failed", re);
throw re;
}
}
public List findByProperty(StringpropertyName, Object value) {
log.debug("finding Userinstance with property: " + propertyName
+ ",value: " + value);
try {
String queryString ="from User as model where model."
+propertyName + "= ?";
returngetHibernateTemplate().find(queryString, value);
} catch (RuntimeException re){
log.error("findby property name failed", re);
throw re;
}
}
/* (non-Javadoc)
* @seecom.ssh.dao.impl.IUserDAO#findByUsername(java.lang.Object)
*/
@Override
public List findByUsername(Objectusername) {
returnfindByProperty(USERNAME, username);
}
public List findByPassword(Objectpassword) {
returnfindByProperty(PASSWORD, password);
}
public List findAll() {
log.debug("finding allUser instances");
try {
String queryString ="from User";
returngetHibernateTemplate().find(queryString);
} catch (RuntimeException re){
log.error("findall failed", re);
throw re;
}
}
public User merge(UserdetachedInstance) {
log.debug("merging Userinstance");
try {
User result = (User)getHibernateTemplate().merge(detachedInstance);
log.debug("mergesuccessful");
return result;
} catch (RuntimeException re){
log.error("mergefailed", re);
throw re;
}
}
public void attachDirty(User instance){
log.debug("attachingdirty User instance");
try {
getHibernateTemplate().saveOrUpdate(instance);
log.debug("attachsuccessful");
} catch (RuntimeException re){
log.error("attachfailed", re);
throw re;
}
}
public void attachClean(User instance){
log.debug("attachingclean User instance");
try {
getHibernateTemplate().lock(instance,LockMode.NONE);
log.debug("attachsuccessful");
} catch (RuntimeException re){
log.error("attachfailed", re);
throw re;
}
}
public static IUserDAOgetFromApplicationContext(ApplicationContext ctx) {
return (IUserDAO)ctx.getBean("UserDAO");
}
}
IUserDAO.java的内容:
package com.ssh.dao;
import java.util.List;
import com.ssh.user.User;
public interface IUserDAO {
public abstract voidsave(User transientInstance);
public abstract UserfindById(java.lang.Integer id);
public abstract ListfindByUsername(Object username);
public abstract ListfindByPassword(Object password);
public abstract voiddelete(User persistentInstance);
}
第八步:在src下新建包com.ssh.service和com.ssh.service.impl,这里是spring的结构,实现业务逻辑。
在com.ssh.service下新建接口文件IUserService.java,在com.ssh.service.impl新建实现文件UserService.java。
IUserService.java接口的内容:
package com.ssh.service;
import com.ssh.user.User;
public interface IUserService {
public User getUserById(Integer id);
public User getUserByUsername(Stringusername);
public User getUserByPassword(Stringpassword);
public void addUser(User user);
public void DeleteUser(User user);
public void DeleteUserByUsername(Stringusername);
public void UpdateByUsername(Stringusername, String password_updated);
}
UserService.java实现类的内容:
package com.ssh.service.impl;
import java.util.List;
import com.ssh.dao.IUserDAO;
import com.ssh.service.IUserService;
import com.ssh.user.User;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;
public class UserService implements IUserService {
privateIUserDAO userDAO;
publicvoid addUser(User user) {
SessionFactory sf = newConfiguration().configure().buildSessionFactory();
Sessionsession = sf.openSession();
Transactiontx = session.beginTransaction();
//userDAO.save(user);
session.save(user);
tx.commit();
session.clear();
}
publicvoid DeleteUser(User user) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Sessionsession = sf.openSession();
Transactiontx = session.beginTransaction();
//userDAO.delete(user);
session.delete(user);
tx.commit();
session.clear();
}
publicvoid DeleteUserByUsername(String username) {
int i;
List list =userDAO.findByUsername(username);
if (list.size() == 0)
return;
SessionFactory sf = newConfiguration().configure().buildSessionFactory();
Sessionsession = sf.openSession();
Transactiontx = session.beginTransaction();
try{
for(i = 0; i < list.size(); i++)
{
Useruser = (User)list.get(i);
session.delete(user);
}
//userDAO.delete(user);
//session.save(user);
tx.commit();
}
catch(RuntimeException re) {
tx.rollback();
throwre;
}finally {
session.clear();
}
}
publicvoid UpdateByUsername(String username, String password_updated) {
int i;
List list = userDAO.findByUsername(username);
if (list.size() == 0)
return;
SessionFactory sf = newConfiguration().configure().buildSessionFactory();
Sessionsession = sf.openSession();
Transactiontx = session.beginTransaction();
try{
for(i = 0; i < list.size(); i++)
{
Useruser = (User)list.get(i);
user.setPassword(password_updated);
session.update(user);
}
//userDAO.delete(user);
//session.save(user);
tx.commit();
}
catch(RuntimeException re) {
tx.rollback();
throwre;
}finally {
session.clear();
}
}
publicUser getUserById(Integer id) {
returnuserDAO.findById(id);
}
publicUser getUserByUsername(String username) {
Listlist = userDAO.findByUsername(username);
if(list.size() == 0) {
return null;
} else{
return (User) list.get(0);
}
}
publicUser getUserByPassword(String password) {
List list = userDAO.findByPassword(password);
if (list.size() == 0) {
return null;
}else {
return (User) list.get(0);
}
}
publicIUserDAO getUserDAO() {
returnuserDAO;
}
publicvoid setUserDAO(IUserDAO userDAO) {
this.userDAO = userDAO;
}
}
在src下新建包com.ssh.struts.action,新建一个类文件BaseAction.java
BaseAction.java的内容为:
packagecom.ssh.struts.action;
importorg.springframework.web.context.WebApplicationContext;
importorg.springframework.web.context.support.WebApplicationContextUtils;
import com.ssh.service.IUserService;
importcom.ssh.user.User;
public classBaseAction {
private int fid = 20;
private String username;
private String password;
private IUserService userService;
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 void setUserService(IUserServiceuserService) {
this.userService = userService;
}
public String execute() {
/*
if("suo".equals(this.username) &&"123".equals(this.password))
return "success";
else
return "fail";
}
*/
Useruser = new User();
//user.setUsername(this.username);
//user.setPassword(this.password);
//this.userService.addUser(user);
//this.userService.DeleteUser(user);
//this.userService.UpdateByUsername(this.username,this.password);
user= this.userService.getUserByUsername(this.username);
if (user != null)
{
if (this.password.equals(user.getPassword()))
return"success";
}
return"fail";
}
}
Spring的配置文件applicationContext.xml:
<?xmlversion="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"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<beanid="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<propertyname="configLocation"
value="classpath:hibernate.cfg.xml">
</property>
</bean>
<!-- 配置事务管理器 -->
<beanid="transactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<propertyname="sessionFactory">
<reflocal="sessionFactory"/>
</property>
</bean>
<beanid="userDAO"class="com.ssh.dao.impl.UserDAO">
<propertyname="sessionFactory">
<refbean="sessionFactory"/>
</property>
</bean>
<beanid="userService"class="com.ssh.service.impl.UserService">
<propertyname="userDAO"ref="userDAO"/>
</bean>
<beanname="baseActionBean"class="com.ssh.struts.action.BaseAction"scope="prototype">
<propertyname="userService"ref="userService"/>
</bean>
</beans>
Structs的配置文件struts.xml:
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD StrutsConfiguration 2.1//EN""http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<packagename="test"namespace="/test"extends="struts-default">
<!-- <action name="login"class="com.ssh.struts.action.BaseAction"method="execute"> -->
<actionname="login"class="baseActionBean">
<resultname="success">/WEB-INF/result/success.jsp</result>
<resultname="fail">/WEB-INF/result/fail.jsp</result>
</action>
</package>
</struts>
Web.xml配置文件:
<?xmlversion="1.0"encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"id="WebApp_ID"version="3.1">
<display-name>SSHTEST</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- struts2.1配置 start -->
<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>
<!-- struts2.1 end -->
<!-- 把Session增大以免出现Lazy加载错误 -->
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 对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>
<!-- 对Spring容器进行实例化 end-->
</web-app>
- SSH框架的登录实例
- SSH框架的用户登录小实例
- SSH框架搭建登录实例
- SSH框架整合的实例
- 求一个用SSH框架+mysql写的简单小实例,比如登录注册
- SSH-struts1登录实例
- SSH框架-登录界面
- SSH框架--登录
- ssh框架登录注册
- ssh框架登录注册
- 有关SSH框架的一个实例
- 通过struts框架完成登录的实例
- SSH 框架实例 操作
- ssh框架整合实例
- SSH框架整合实例
- ssh证书登录(实例详解)
- ssh证书登录(实例详解)
- ssh证书登录(实例详解)
- 第6章 Java访问控制权限
- JSP内置对象、基础语法笔记
- 【MAVEN】 Maven开发环境搭建
- Hibernate笔记(4)-hql查询与Criteria查询
- JS获取DOM结点的样式
- SSH框架的登录实例
- JavaScript高级程序设计第八章知识总结
- uva 580-Critical Mass(动态规划)
- andorid-studio nexus 仓库搭建
- C# 调用外部dll
- 解决Genymotion无法启动,VirtualBox报E_FALL(0x80004005)的错误
- Opencv 图像金字塔pyrDown和pyrUp函数
- 【sublime Text-Theme】
- secureCRT连不上虚拟机解决方案