Struts2+Spring2+Hibernate3

创建数据库表及ORM映射文件
数据库SQL
drop database if exists TEST;
create database TEST;

use TEST;

drop table if exists USERS;
create table USERS (
UID INT AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(20) NOT NULL UNIQUE,
PASSWORD VARCHAR(32) NOT NULL) ENGINE=MyISAM;
insert into USERS(USERNAME, PASSWORD) VALUES('admin', '21232f297a57a5a743894a0e4a801fc3');
insert into USERS(USERNAME, PASSWORD) VALUES('test', '098f6bcd4621d373cade4e832627b4f6');


User.java:
package test.bean;

public class User {
	private int uid;
	private String username;
	private String password;
	
	public int getUid() {
		return this.uid;
	}
	public void setUid(int uid) {
		this.uid = uid;
	}
	
	public String getUsername() {
		return this.username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	
	public String getPassword() {
		return this.password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}


User.hbm.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="test.bean.User" table="USERS">
		<id name="uid" type="int">
			<column name="UID" />
			<generator class="increment" />
		</id>
		
		<property name="username" type="java.lang.String">
			<column name="USERNAME" length="20" />
		</property>
		
		<property name="password" type="java.lang.String">
			<column name="PASSWORD" length="32" />
		</property>
	</class>
</hibernate-mapping>


Struts2 Spring2 Hibernate3配置文件
web.xml:
<?xml version="1.0"?>

<web-app>
	<display-name>SSH Test</display-name>
	
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>


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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test" />
		<property name="driverClass" value="com.mysql.jdbc.Driver" />
		<property name="user" value="root" />
		<property name="password" value="root" />
		<property name="maxPoolSize" value="40" />
		<property name="minPoolSize" value="1" />
		<property name="initialPoolSize" value="1" />
		<property name="maxIdleTime" value="20" />
	</bean>
	
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
			</props>
		</property>
		<property name="mappingResources">
			<list>
				<value>test/bean/User.hbm.xml</value>
			</list>
		</property>
	</bean>
	
	<bean id="userDao" class="test.dao.impl.UserDAOImpl">
		<property name="sessionFactory">
			<ref bean="sessionFactory" />
		</property>
	</bean>
	
	<bean id="userService" class="test.service.impl.UserServiceImpl">
		<property name="userDao">
			<ref bean="userDao" />
		</property>
	</bean>

	<bean id="Login" class="test.action.Login" scope="prototype">
		<property name="userService">
			<ref bean="userService" />
		</property>
	</bean>
</beans>


struts.xml:
<?xml version="1.0" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<package name="test" extends="struts-default">
		<action name="Login" class="Login">
			<result>/success.jsp</result>
			<result name="input">/index.jsp</result>
			<result name="error">/index.jsp</result>
		</action>
	</package>
	
</struts>


struts.properties:
struts.objectFactory=spring
struts.locale=en_GB
struts.i18n.encoding=GBK


log4j.properties:
log4j.rootLogger=info,console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%p - %d{HH:mm:ss} %m%n

接下来就是程序部分
UserDAO.java:
package test.dao;

import test.bean.User;

public interface UserDAO {
	public User find(String username);
}


UserDAOImpl.java:
package test.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import test.bean.User;
import test.dao.UserDAO;

public class UserDAOImpl implements UserDAO {
	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	@SuppressWarnings("unchecked")
	public User find(String username) {
		Session session = null;
		
		try {
			session = sessionFactory.openSession();
		} catch(HibernateException e) {
			e.printStackTrace();
			return null;
		}
		if(session != null) {
			List<User> list;
			try {
				String hql = "from User u where u.username=?";
				Query query = session.createQuery(hql);
				query.setString(0, username);
				list = query.list();
				if(list.size() == 1)
					return list.get(0);
				else
					return null;
			} catch(HibernateException e) {
				return null;
			} finally {
				session.close();
			}
		} else
			return null;
	}
}


UserService.java:
package test.service;

public interface UserService {
	public boolean validate(String username, String password);
}


UserServiceImpl.java:
package test.service.impl;

import test.bean.User;
import test.dao.UserDAO;
import test.service.UserService;

public class UserServiceImpl implements UserService {
	private UserDAO userDAO;
	
	public UserDAO getUserDao() {
		return this.userDAO;
	}
	public void setUserDao(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	
	public boolean validate(String username, String password) {
		User user = null;
		user = userDAO.find(username);
		if(user != null) {
			if(password.equals(user.getPassword()))
				return true;
			else
				return false;
		} else
			return false;
	}
}


Login.java:
package test.action;

import test.bean.User;
import test.service.UserService;
import test.util.Encryption;

import com.opensymphony.xwork2.ActionSupport;

public class Login extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private User user;
	private UserService userService;
	
	public User getUser() {
		return this.user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	
	public UserService getUserService() {
		return this.userService;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	public String execute() {
		String username = user.getUsername();
		String password = new Encryption(user.getPassword()).getCryptograph();
		if(userService.validate(username, password))
			return SUCCESS;
		else
			return ERROR;
	}
}


Encryption.java:
package test.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Encryption {
	private String s;
	
	public Encryption(String s) {
		this.s = s;
	}
	
	public String getCryptograph() {
		String cryptograph = null;
		
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch(NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
		if(md != null) {
			byte[] b = md.digest(s.getBytes());
			StringBuffer buf = new StringBuffer(b.length * 2);
			for(int i = 0; i < b.length; i++) {
				if((b[i] & 0xff) < 16)
					buf.append("0");
				buf.append(Long.toString(b[i] & 0xff, 16));
			}
			cryptograph = buf.toString();
			return cryptograph;
		} else
			return null;
	}
}

你可能感兴趣的:(java,Hibernate,log4j,bean,struts)