经过几天的折腾,总算把J2EE的SSH框架搭建起来了。
第一步:
安装 Jdk , MyEcplise , Tomcat
下载Struts2.3.14, Spring3.2.2 ,Hibernate4.2.0
如果使用proxool数据连接池技术 必须加入proxool-0.9.1.jar和proxool-cglib.jar
除了proxool之外,还有DBCP和C3P0数据连接池技术。DBCP不建议使用,proxool和C3P0都是商业级,但proxool相对更加稳定。
如果采用mysql数据库,则必须加上mysql-connector-java-5.1.22-bin.jar。
如果采用其它数据库,需加入相应的jar文件。
最终项目的目录结构:
第二步:
web.xml的配置
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>SSHdisplay-name>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>/WEB-INF/applicationContext.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<filter>
<filter-name>struts2filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterfilter-class>
filter>
<filter-mapping>
<filter-name>struts2filter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<welcome-file-list>
<welcome-file>login.jspwelcome-file>
welcome-file-list>
web-app>
第三步:
配置数据库
jdbc.properties
proxool.maxConnCount=5
proxool.minConnCount=2
proxool.statistics=1m,15m,1h,1d
proxool.simultaneousBuildThrottle=5
proxool.trace=false
proxool.verbose=false
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/test?characterEncoding\=gbk
jdbc.username=lee
jdbc.password=lee
applicationContext.xml
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations"
value="classpath:jdbc.properties" />
bean>
<bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource">
<property name="driver" value="${jdbc.driverClassName}" />
<property name="driverUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maximumConnectionCount" value="${proxool.maxConnCount}" />
<property name="minimumConnectionCount" value="${proxool.minConnCount}" />
<property name="statistics" value="${proxool.statistics}" />
<property name="simultaneousBuildThrottle" value="${proxool.simultaneousBuildThrottle}" />
<property name="trace" value="${proxool.trace}" />
<property name="verbose" value="${proxool.verbose}" />
bean>
第四步:
建立po对象,通过hibernate进行持久化。编写数据库逻辑层。
User.java
package com.model;
import javax.persistence.*;
@Entity
@Table(name="stock")
public class User {
private Integer Id;
private String Name;
private String Pass;
@Id
@GeneratedValue
public Integer getId() {
return this.Id;
}
public void setId(Integer Id) {
this.Id = Id;
}
@Column(name="name")
public String getName() {
return this.Name;
}
public void setName(String Name) {
this.Name = Name;
}
@Column(name="pass")
public String getPass() {
return this.Pass;
}
public void setPass(String Pass) {
this.Pass = Pass;
}
}
UserDao.java
package com.dao;
import com.model.User;
public interface UserDAO {
public User queryUserByName(String Name);
}
UserDaoImpl.java
Hibernate4相对于Hibernate3在api上进行了较大改动,原先Hibernate3中的HibernateTemplate等已经失效。
通过在applicationContext.xml中的配置,通过spring把sessionFactory注入到UserDaoImpl中。
package com.dao;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import com.model.User;
public class UserDAOImpl implements UserDAO {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public User queryUserByName(String name) {
Query query = sessionFactory.getCurrentSession().createQuery(
"from User as u where u.Name = ?");
query.setString(0, name);
User u = (User) query.uniqueResult();
return u;
}
}
第五步:
编写业务逻辑层
UserService.java
package com.service;
public interface UserService {
public boolean ValidLogin(String name,String password);
}
UserServiceImpl.java
由于没有在该类的ValidLogin()之前加上注解@Transactional,导致sessionFactory.getCurretSession()总是返回null。
猜测Hibernate把事务管理委托给spring,所以必须spring启动事务,才能生产session。
package com.service;
import org.springframework.transaction.annotation.Transactional;
import com.dao.UserDAO;
import com.model.User;
public class UserServiceImpl implements UserService {
private UserDAO userDAO;
@Transactional
public boolean validLogin(String name, String password) {
User u = userDAO.queryUserByName(name);
if (u == null) {
return false;
} else {
if (u.getPass().equals(password)) {
return true;
} else {
return false;
}
}
}
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
}
第六步:
编写Acton(控制器)
LoginAction.java
package com.action;
import com.service.UserService;
public class LoginAction {
private String name;
private String password;
private UserService userService;
public String login() {
if(name == null && password == null) {
return "login";
} else {
Boolean u = userService.ValidLogin(name, password);
if(u) {
return "ok";
} else {
return "error";
}
}
}
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;
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
}
struts.xml
name="default" namespace="/" extends="struts-default">
name="login" class="loginAction" method="login">
<result name="login">login.jspresult>
<result name="ok">loginOk.jspresult>
<result name="error">loginError.jspresult>
第七步:
编写表现层的jsp
login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<body>
<center>
<form method="post" action="login">
UserName <input type="text" name="name" id="name"/><br/>
Password <input type="password" name="password" id="password"/><br/>
<input type="submit" value="login"/>
form>
center>
body>
html>
loginError.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<body>
Login Is Error. <br>
body>
html>
loginOk.java
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<body>
Login Is Ok. <br>
body>
html>
第八步
给出struts.xml和applicationContext.xml的完整代码
struts.xml
<struts>
<constant name="struts.objectFactory" value="spring" />
<constant name="struts.devMode" value="false" />
<constant name="struts.configuration.xml.reload" value="true" />
<constant name="struts.serve.static.browserCache" value="false" />
<constant name="struts.i18n.encoding" value="utf-8" />
<constant name="struts.i18n.reload" value="true" />
<constant name="struts.multipart.maxSize" value="104857600" />
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<constant name="struts.enable.SlashesInActionNames" value="false" />
<constant name="struts.tag.altSyntax" value="true" />
<constant name="struts.dispatcher.parametersWorkaround" value="false" />
<package name="default" namespace="/" extends="struts-default">
<action name="login" class="loginAction" method="login">
<result name="login">login.jspresult>
<result name="ok">loginOk.jspresult>
<result name="error">loginError.jspresult>
action>
package>
struts>
applicationContext.xml
applicationContext.xml十分重要,同时也是最容易出错的。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:tool="http://www.springframework.org/schema/tool" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.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/jee
http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/tool
http://www.springframework.org/schema/tool/spring-tool.xsd"
default-lazy-init="true" default-autowire="byName">
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations"
value="classpath:jdbc.properties" />
bean>
<bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource">
<property name="driver" value="${jdbc.driverClassName}" />
<property name="driverUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maximumConnectionCount" value="${proxool.maxConnCount}" />
<property name="minimumConnectionCount" value="${proxool.minConnCount}" />
<property name="statistics" value="${proxool.statistics}" />
<property name="simultaneousBuildThrottle" value="${proxool.simultaneousBuildThrottle}" />
<property name="trace" value="${proxool.trace}" />
<property name="verbose" value="${proxool.verbose}" />
bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.modelvalue>
list>
property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialectprop>
<prop key="hibernate.show_sql">trueprop>
<prop key="hibernate.format_sql">trueprop>
<prop key="hibernate.hbm2ddl.auto">updateprop>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContextprop>
props>
property>
bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
property>
<property name="dataSource" ref="dataSource" />
bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="loginAction" class="com.action.LoginAction" >
<property name="userService" ref="userService" />
bean>
<bean id="userService" class="com.service.UserServiceImpl" >
<property name="userDAO" ref="userDAO" />
bean>
<bean id="userDAO" class="com.dao.UserDAOImpl" >
<property name="sessionFactory" ref="sessionFactory" />
bean>
beans>
总结:
再进行编写SSH框架demo的时候,出现了许多问题,每个问题都去网上搜索,虽然最终都解决,但花了太多时间,解决问题的效率有待提高。同时,在遇到一个问题时,要自己多分析问题,要多思考。