一.搭建原理
运用Struts2.0+Hibernate3.1+Spring3.0+MySql方式搭建。
二.搭建环境准备
2.1. 建立新项目
右击创建新项目,如:erp,在com下先创建common,database,service,web包,分别用于存放通用类,数据库实体类,服务类和控制跳转类;
2.2. 引入项目包
将以上程序包添加到WebRoot-WEB-INF-lib里面,作为程序的基础包;(附件内容比较大,建议下载SSH框架包)
2.3. MySql数据库创建项目数据库
创建数据库erp,并在数据库里面创建表principal(用户信息表),用户登录认证;建表语句如下:
CREATE TABLE`principal` (
`ID` varchar(32) primary key,
`NAME` varchar(100) default NULL,
`ACCOUNT` varchar(32) default NULL,
`PASSWORD` varchar(32) default NULL,
`COMPANY_CODE` varchar(32) default NULL,
`COMPANY_NAME` varchar(32) default NULL,
`DEP_CODE` varchar(32) default NULL,
`DEP_NAME` varchar(32) default NULL,
`EMAIL` varchar(32) default NULL,
`TELEPHONE` varchar(32) default NULL,
`STATE` varchar(32) default NULL,
`LOGIN_TYPE` varchar(255) default NULL
) ENGINE=InnoDBDEFAULT CHARSET=utf8;
创建一条基础记录
INSERT INTO `principal`VALUES ('admin', '系统管理员', 'admin', 'E10ADC3949BA59ABBE56E057F20F883E', null, null, null,null, null, null, null, '1');
2.4. 修改项目web.xml配置
首选引入Web容器配置,这里需要引入包commons-logging-1.1.1.jar
<!-- 引入监听器 -->
<!-- 启动Web容器时,自动装配ApplicationContext的配置信息 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
然后引入ApplicationContext.xml配置
<!-- ApplicationContext文件路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/conf/applicationContext.xml
</param-value>
</context-param>
然后引入Struts配置
<!-- 引入Struts-->
<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>
再定义数据源
<!-- 定义数据源 -->
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/erpDS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Unshareable</res-sharing-scope>
</resource-ref>
定义首页(欢迎页)
<welcome-file-list>
<welcome-file>manager/login.jsp</welcome-file>
</welcome-file-list>
2.5. applicationContext.xml配置
在web.xml配置文件看出,该配置文件应该建立在classpath:/conf/applicationContext.xml上。因此创建项目包conf。由于是需要AOP业务的,同时需要引进aopalliance.jar,bean解释过程中,需要引入dom4j-1.6.1.jar,slf4j-api-1.5.0.jar,slf4j-jcl-1.5.0.jar,commons-collections-3.2.1.jar。
首先,文件前缀不变,如下:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring
http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">
启动Spring扫描机制
<!-- Spring扫描机制 -->
<context:component-scan base-package="com"/>
使用DBCP连接方式引用数据源
<!-- 使用DBCP连接方式引用数据源 -->
<bean id="dataSource"class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/erpDS</value>
</property>
</bean>
开启Hibernate工厂,引入Hibernate文件,指定为MySql数据源,并指向hbm配置文件路径
<!-- 开启HIBERNATE工厂 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 引用数据源 -->
<property name="dataSource"ref="dataSource" />
<property name="hibernateProperties">
<props>
<!-- SQL方言 -->
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLInnoDBDialect
</prop>
<!-- SQL打印输出 -->
<prop key="hibernate.show_sql">true</prop>
<!-- 缓存设置 -->
<prop key="hibernate.cache.provider_class">
org.hibernate.cache.EhCacheProvider
</prop>
<!-- 开启二级缓存 -->
<prop key="hibernate.cache.use_query_cache">true</prop>
</props>
</property>
<!-- 通配符指定项目文件 -->
<property name="mappingLocations"
value="classpath*:com/**/*.hbm.xml" />
</bean>
开启事务配置,并指向Service后缀的为事务控制点。这里涉及到事务管理,要引入jta-1.1.jar包,做事务控制
<!--事务配置 -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="transactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager"ref="txManager" />
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED,-Exception</prop>
</props>
</property>
</bean>
<bean
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>*Service</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
</list>
</property>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
2.6. struts.xml配置
创建struts.xml到项目的包根目录
<?xml version="1.0"encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD StrutsConfiguration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="sysmgr" namespace="/sysmgr"extends="struts-default">
<!-- 登录Action -->
<action name="login"class="com.erp.web.sysmgr.LoginAction">
<result>
/WEB-INF/jsp/HelloWorld.jsp
</result>
</action>
</package>
</struts>
2.7. 系统lib配置
重新引包,刷新项目文件
2.8. tomcat配置
进入conf/server.xml,配置一个Service
<Servicename="service2">
<Connector port="8383" protocol="HTTP/1.1"connectionTimeout="20000" redirectPort="8444"URIEncoding="GBK" />
<Connector port="9999"protocol="AJP/1.3" redirectPort="8444"/>
<Engine name="erp"defaultHost="localhost">
<RealmclassName="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
<Hostname="localhost" appBase="webapps"unpackWARs="true" autoDeploy="true"xmlValidation="false" xmlNamespaceAware="false">
<ContextdocBase="D:\ehome\erp\WebRoot" path="/erp">
<Resourcename="jdbc/erpDS"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
maxActive="150"
maxIdle="20"
maxWait="10000"
username="root"
password="123456"
url="jdbc:mysql://localhost:3306/erp"
/>
</Context>
</Host>
</Engine>
</Service>
进行启动测试,没有问题,证明框架初步成型
三.验证搭建环境
3.1. 新增用户登录页面
在项目manager/login.jsp上面,添加如下内容
<%@ page language="java"import="java.util.*" pageEncoding="utf-8"%>
<%
String path =request.getContextPath();
String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title></title>
</head>
<body>
<form action="<%=basePath%>sysmgr/login.action"method="post">
用户名:
<input type="text" name="username">
<input type="submit" value="登录">
</form>
</body>
</html>
3.2. 新增用户登录Action
在项目web层下创建sysmgr/LoginAction.java。
在项目中,使用AOP注入方式,继承ActionSupport,如下:
package com.erp.web.sysmgr;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionSupport;
/**
* 用户登录方法测试
*
* @author ChenJianHui
*
*/
@Scope("prototype")
@Controller("loginAction")
@SuppressWarnings("serial")
public class LoginAction extends ActionSupport{
private String username;
public String execute() {
System.out.println(username);
return null;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
3.3. 新增底层数据持久化Dao
在项目database层上面创建dao/CommonDao.java。
packagecom.erp.database.dao;
importorg.hibernate.Query;
import org.hibernate.Session;
importorg.hibernate.SessionFactory;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;
importorg.springframework.stereotype.Repository;
/**
* 通用数据访问对象
*
* @author ChenJianHui
*
*/
@Repository()
public classCommonDao extends HibernateDaoSupport {
/**
* 设置工厂类
*
* @param sessionFactory
*/
@Autowired
public voidsetSession$Factory(SessionFactory sessionFactory) {
super.setSessionFactory(sessionFactory);
}
/**
* 取当前管理的数据访问会话.
*
* @return HIBERNATE会话对象
*/
public Session currentSession() {
return this.getSession();
}
/**
* 根据SQL创建查询对象
*
* @param queryString
* @return
*/
public Query createQuery(StringqueryString) {
returnthis.currentSession().createQuery(queryString);
}
}
3.4. 新增用户信息实体
在项目database层上面创建entity/sysmgr/Principal.java。
package com.erp.database.entity.sysmgr;
import java.io.Serializable;
/**
* 登录用户信息表
*
* @author ChenJianHui
*
*/
@SuppressWarnings("serial")
public class Principal implements Serializable {
// Fields
private String id; // 用户ID
private String name; // 用户名称
private String account; // 用户账号
private String password; // 密码
private String companyCode; // 公司编码
private String companyName; // 公司名称
private String depCode; // 部门编码
private String depName; // 所属部门
private String email; // 邮件
private String telephone; // 联系电话
private String state; // 用户状态
private String loginType; // 用户类型
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCompanyCode() {
return companyCode;
}
public void setCompanyCode(String companyCode) {
this.companyCode = companyCode;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getDepCode() {
return depCode;
}
public void setDepCode(String depCode) {
this.depCode = depCode;
}
public String getDepName() {
return depName;
}
public void setDepName(String depName) {
this.depName = depName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getLoginType() {
return loginType;
}
public void setLoginType(String loginType) {
this.loginType = loginType;
}
}
3.5. 新增用户信息HBM实体
在项目database层上面创建entity/sysmgr/Principal.hbm.xml。
<?xml version="1.0"encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/HibernateMapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated byMyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.erp.database.entity.sysmgr.Principal"table="PRINCIPAL">
<id name="id" type="java.lang.String">
<column name="ID" length="32"/>
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="50"/>
</property>
<property name="account" type="java.lang.String">
<column name="ACCOUNT" length="50"not-null="true" unique="true"/>
</property>
<property name="password" type="java.lang.String">
<column name="PASSWORD" length="64"/>
</property>
<property name="companyCode" type="java.lang.String">
<column name="COMPANY_CODE" length="32" />
</property>
<property name="companyName" type="java.lang.String">
<column name="COMPANY_NAME" length="32" />
</property>
<property name="depCode" type="java.lang.String">
<column name="DEP_CODE" length="100"/>
</property>
<property name="depName" type="java.lang.String">
<column name="DEP_NAME" length="100"/>
</property>
<property name="email" type="java.lang.String">
<column name="EMAIL" length="50"/>
</property>
<property name="telephone" type="java.lang.String">
<column name="TELEPHONE" length="50"/>
</property>
<property name="state" type="java.lang.String">
<column name="STATE" length="10"/>
</property>
<property name="loginType" type="java.lang.String">
<column name="LOGIN_TYPE" length="10" />
</property>
</class>
</hibernate-mapping>
3.6. 新增用户登录服务Service
在项目service层上面创建sysmgr/principal/LoginService.java。
package com.erp.service.sysmgr.principal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.erp.database.dao.CommonDao;
import com.erp.database.entity.sysmgr.Principal;
/**
* 用户登录逻辑处理Service
*
* @author ChenJianHui
*
*/
@Service("loginService")
@SuppressWarnings("unchecked")
public class LoginService {
@Autowired
private CommonDao commonDao;
/**
* 根据用户账号查询
*
* @param account
* @return
* @throws Exception
*/
public Principal findPrincipal(String account) throws Exception {
Principal principal = null;
try {
String hql = "From " + Principal.class.getName() + " model where model.account = :account ";
List<Principal> principalList = this.commonDao.createQuery(hql).setParameter("account", account).list();
if (!principalList.isEmpty()) {
principal = principalList.get(0);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return principal;
}
}
3.7. 用户登录Action引用登录服务Service
调用登录服务Service
/**
* 用户登录主方法
*/
public String execute() {
try {
System.out.println(username);
Principal principal = this.loginService.findPrincipal(username);
if (null == principal) {
throw new Exception("用户不存在");
}
} catch (Exception e) {
return null;
}
return null;
}
3.8. 验证登录
如果能够成功进行查询,并返回实体内容,则框架搭建成功。