ssh整合登录

1.ssh整合目录结构

     jar包图

     

2. action层

     2.1 UserAction类

package com.zhanggaosong.action;

import java.util.Map;

import org.apache.struts2.interceptor.RequestAware;

import com.opensymphony.xwork2.ActionSupport;
import com.zhanggaosong.domain.User;
import com.zhanggaosong.service.UserService;

public class UserAction extends ActionSupport implements RequestAware {

private static final long serialVersionUID = 1L;
private Map<String, Object> request;
private User user;

private UserService userService;

public void setRequest(Map<String, Object> request) {
this.request = request;
}

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;
}

@Override
public String execute() throws Exception {
String result = null;
User u = userService.checkLogin(user);
if (u == null) {
result = INPUT;
} else {
request.put("user", u);
result = SUCCESS;
}
return result;
}
}

    2.2登录验证文件UserAction-validation.xml

<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">

<validators>
<field name="user.name">
<field-validator type="requiredstring">
<message>用户名不能为空</message>
</field-validator>
<field-validator type="stringlength">
<param name="minLength">6</param>
<param name="maxLength">12</param>
<message>用户名长度必须在${minLength}和${maxLength}之间</message>
</field-validator>

</field>
<field name="user.password">
<field-validator type="requiredstring">
<message>密码不能为空</message>
</field-validator>
<field-validator type="stringlength">
<param name="minLength">6</param>
<param name="maxLength">18</param>
<message>密码长度必须在${minLength}和${maxLength}之间</message>
</field-validator>
</field>
</validators>

  3.Service层

      3.1 接口层

package com.zhanggaosong.service;

import com.zhanggaosong.domain.User;

public interface UserService {

public User checkLogin(User user);

}

      3.2 实现层

package com.zhanggaosong.service;

import com.zhanggaosong.dao.UserDao;
import com.zhanggaosong.domain.User;

public class UserServiceImpl implements UserService {
private UserDao userDao;


public UserDao getUserDao() {
return userDao;
}


public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}


@Override
public User checkLogin(User user) {

return userDao.checkLogin(user);
}

}

4.dao层

       4.1接口层

package com.zhanggaosong.dao;

import com.zhanggaosong.domain.User;

public interface UserDao {

public User checkLogin(User user);
}

      4.2实现层

package com.zhanggaosong.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.zhanggaosong.domain.User;
import com.zhanggaosong.utils.MD5;

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

@Override
public User checkLogin(User user) {

String hql = " from User u where u.name=? and u.password=? ";
Session session =this.getSession();
Query query = session.createQuery(hql);
query.setString(0, user.getName());

//对user.getPassword()加密
String password = MD5.getMD5(user.getPassword().getBytes());

query.setString(1,password);

@SuppressWarnings("unchecked")
List<User> list = query.list();
if(list!=null&&list.size()>0){
return list.get(0);
}else{
return null;
}
}
}

5 实体类 (javaBean)

     5.1 类   

package com.zhanggaosong.domain;

import java.io.Serializable;

public class User implements Serializable {

private static final long serialVersionUID = 1L;

private Integer id;
private String name;
private String password;
public User() {}

public User(String name, String password) {
this.name = name;
this.password = password;
}

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;
}
}

     5.2映射文件

<?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.zhanggaosong.domain.User" table="tb_user" lazy="true">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<property name="password"/>
</class>

</hibernate-mapping>

6 工具类

package com.zhanggaosong.utils;

public class MD5 {
public static String getMD5(byte[] source) {
String s = null;
char hexDigits[] = { // 用来将字节转换成 16 进制表示的字符
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f' };
try {
java.security.MessageDigest md = java.security.MessageDigest
.getInstance("MD5");
md.update(source);
byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数,
// 用字节表示就是 16 个字节
char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符,
// 所以表示成 16 进制需要 32 个字符
int k = 0; // 表示转换结果中对应的字符位置
for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节
// 转换成 16 进制字符的转换
byte byte0 = tmp[i]; // 取第 i 个字节
str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
// >>> 为逻辑右移,将符号位一起右移
str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
}
s = new String(str); // 换后的结果转换为字符串
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
// public static void main(String[] args) {
// String ss = MD5.getMD5("张高".getBytes());
// System.out.println(ss);
// }
}

7.配置文件

    7.1  hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///ssh</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>

<mapping resource="com/zhanggaosong/domain/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>

      7.2 spring配置文件

            7.2.1  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"
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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<import resource="db-applicationContext.xml"/>
<import resource="user-applicationContext.xml"/>
</beans>

             7.2.2 db-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"
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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 配置SessionFactory-初步和Hibernate整合 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>classpath:hibernate/hibernate.cfg.xml</value>
</property>
</bean>

<!-- 配置事务(声明式事务),用Spring去控制Hibernate的事务管理 -->
<!-- 配置事务管理器 -->

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!-- 告诉事务管理器 那些方法下需要由Spring 去管理事务 -->
<tx:advice id="tx" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="*" isolation="DEFAULT" propagation="REQUIRED" read-only="true"/>
</tx:attributes>
</tx:advice>

<!-- 告诉事务管理器 那些包以及那些类下需要Spring 去管理事务(一定是在SERVICE层上处理事务) -->
<aop:config>
<aop:pointcut expression="execution(* com.zhanggaosong.service.*.*(..))" id="perform"/>
<aop:advisor pointcut-ref="perform" advice-ref="tx"/>
</aop:config>

</beans>

        7.2.3 user-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"
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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 程序员要做的事情-让SPRING 去创建DAO 对象,Service 对象 -->
<bean id="userDao" class="com.zhanggaosong.dao.UserDaoImpl">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="userService" class="com.zhanggaosong.service.UserServiceImpl">
<property name="userDao">
<ref bean="userDao"/>
</property>
</bean>
<!--用SPRING去创建ACTION的时候,要确保ACTION是多实例 scope="prototype"
而且你要清楚:action由Spring创建但是由Struts管理
-->
<bean id="userAction" class="com.zhanggaosong.action.UserAction" scope="prototype" >
<property name="userService">
<ref bean="userService"/>
</property>
</bean>
</beans>

8.struts配置文件

    user-struts.xml

<?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="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />

<package name="userAction" namespace="/" extends="struts-default">

<action name="userAction" class="com.zhanggaosong.action.UserAction">
<result name="input">/index.jsp</result>
<result>
/main.jsp
</result>
</action>
</package>
</struts>

   struts.xml

<?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>
<include file="struts/user-struts.xml"/>
</struts>

9. 导出表 

package com;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

public class CreateTable {
@Test
public void testCreateTable(){
Configuration cfg = new Configuration().configure("hibernate/hibernate.cfg.xml");
SchemaExport export = new SchemaExport(cfg);
export.create(true, true);
}
}

10.插入测试数据

package com;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.zhanggaosong.domain.User;
import com.zhanggaosong.utils.MD5;

public class Client {
public static void main(String[] args) {
//读取hibernate.cfg.xml文件
Configuration cfg=new Configuration().configure("hibernate/hibernate.cfg.xml");
//建立SessionFactory
SessionFactory factory=cfg.buildSessionFactory();
//取得Session
Session session=null;
try{
//取得Session
session=factory.openSession();
//开启事务
session.beginTransaction();

User user=new User();
user.setName("zhanggaosong");
String password="123456";
// 对密码password加密并保存在md5password中
String md5password=MD5.getMD5(password.getBytes());
user.setPassword(md5password);

//保持user对象
session.save(user);
//提交事务
session.getTransaction().commit();

}catch (Exception e) {
e.printStackTrace();
//回滚事务
session.getTransaction().rollback();
}finally{
if(session!=null){
if(session.isOpen()){
//管理session
session.close();
}
}
}
}
}

11.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">
<!-- 配置SPRING监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext.xml</param-value>
</context-param>
<!-- 配置openSessionInView ,这也是靠SPRING去完成-->
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<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>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

 

12.登录页面   

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<s:actionmessage/>
<s:form action="userAction" method="post" namespace="/">
<table>
<tr>
<td>
<s:textfield label="用户名" name="user.name"/>
</td>
</tr>
<tr>
<td>
<s:password label="密 码" name="user.password"/>
</td>
</tr>
<tr>
<td>
<s:submit value="提交"/>
</td>
</tr>
</table>
</s:form>
</center>
</body>
</html>

 

posted @ 2013-03-12 10:24  zhgs_cq  阅读(292)  评论(0编辑  收藏  举报