SSH框架,当今最为流行的项目开发框架组合,那么掌握他的第一步是学习如何配置环境,java Web开发的无论哪种框架都离不开各种xml配置,虽然说配置在网上到处都有,但是要成为合格的程序猿,必须要明白配置中每一部分的意义,分析它的规律,因此这一步至关重要。
SSH分为SSH1和SSH2,区别主要在于Struts的版本,即Struts1和Struts2,Struts1与Struts2在配置上有所差别,
这回主要为大家介绍的是基于Struts2的SSH2框架搭建。
我们在搭建框架之前,首先一定要注意各个框架的版本,不同的版本集成方式和所需的jar包是有区别的。
SSH2框架的版本为:struts-2.2.3 + spring-2.5.6 + hibernate-3.6.8
1. 所需jar包:猛击下载免费jar包资源
struts2:
struts2-core-2.2.3.jar
struts2-spring-plugin-2.2.3.jar
xwork-core-2.2.3.jar
commons-io-2.0.1.jar
commons-lang-2.5.jar
commons-fileupload-1.2.2.jar
freemarker-2.3.16.jar
ognl-3.0.1.jar
javassist-3.12.0.GA.jar(hibernate同样需要)
spring:
spring.jar
commons-logging-1.1.1.jar
common-annotations.jar
aspectjrt.jar
aspectjweaver.jar
cglib-nodep-2.1_3.jar
(如果用BasicDataSource来配置数据库连接,还要加入以下2个包)
commons-dbcp.jar
commons-pool.jar
hibernate:
hibernate3.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
antlr-2.7.6.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
slf4j-api-1.6.1.jar
slf4j-nop-1.6.4.jar(这个jar包要去slf4j官网下载slf4j-1.6.4集成包)
jdbc:
ojdbc14.jar(oracle)
2. web.xml配置
[xml] view plaincopy
<span style="background-color:rgb(255,255,255)"><?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">
<display-name>testSSH</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 配置资源 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/applicationContext.xml</param-value>
</context-param>
<!-- 配置自定义filter,并由spring管理 -->
<!--
<filter>
<filter-name>myFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
-->
<!-- 配置CharacterEncoding,设置字符集 -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 将HibernateSession开关控制配置在Filter,保证一个请求一个session,并对lazy提供支持 -->
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<!-- 配置struts2 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<init-param>
<param-name>config</param-name>
<param-value>struts-default.xml,struts-plugin.xml,/config/struts.xml</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 页面session配置 -->
<session-config>
<session-timeout>20</session-timeout>
</session-config>
<!-- 错误页面 -->
<error-page>
<error-code>404</error-code>
<location>/error404.html</location>
</error-page>
</web-app></span>
注意:
① 配置自定义filter即DelegatingFilterProxy时,参数targetFilterLifecycle设为true是将filter放入web容器中成为真正意义上的filter。否则只是个代理filter,不具有filter的生命周期,因此无法执行filter的init、destroy方法。因为统一交由spring管理,所以在spring资源配置文件(如applicationContext.xml)中必须相应的并且名称为myFilter的bean。
② OpenSessionInViewFilter要将参数singleSession设置为true,否则意义不大。
③ 配置struts2建议采用StrutsPrepareAndExecuteFilter。struts.xml默认放在src根目录下,若想放置到其他地方还要将struts-default.xml和struts-plugin.xml一同配置下,否则在于其他框架结合时(如spring)就会报错。配置struts2的filter标签要放到所有filter标签的最下面,否则会有问题。
3. struts.xml配置
[xml] view plaincopy
<span style="background-color:rgb(255,255,255)"><!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 将Action的创建交给spring来管理 -->
<constant name="struts.objectFactory" value="spring" />
<!-- 更改struts2请求Action的后缀名,默认为action。若想去掉后缀,设为","即可 -->
<constant name="struts.action.extension" value="do"></constant>
<package name="struts" namespace="/" extends="struts-default">
<!-- 配置拦截器 -->
<interceptors>
<interceptor name="myInterceptor" class="myInterceptor"></interceptor>
<interceptor-stack name="myDefult">
<interceptor-ref name="myInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="myLogin" class="loginAction">
<result name="success">/success.jsp</result>
<result name="error" type="redirect">/index.jsp</result>
</action>
<action name="testSession" class="sessionAction">
<interceptor-ref name="myDefult"></interceptor-ref>
<result name="success">/success.jsp</result>
<result name="error" type="redirect">/login.jsp</result>
</action>
</package>
</struts></span>
注意:
① 执行完自定义拦截器后,还要执行struts2默认的拦截器defaultStack,否则可能会出错。
② action标签的class属性,与spring结合后要写成spring中bean的名称name。
4. applicationContext.xml
[xml] view plaincopy
<span style="background-color:rgb(255,255,255)"><?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:tx="http://www.springframework.org/schema/tx"
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-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/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 启用spring注解支持 -->
<context:annotation-config/>
<!-- 第一种方法配置sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:config/hibernate.cfg.xml"></property>
</bean>
<!-- 第二种方法配置sessionFactory
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@localhost :1521:wang"/>
<property name="username" value="wang"/>
<property name="password" value="wang"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="mappingLocations">
<list>
<value>classpath:test/entity/User.hbm.xml</value>
</list>
</property>
</bean>
-->
<!-- 第一种方法配置事务 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:advice id="txadvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="del*" propagation="REQUIRED" no-rollback-for="MyException"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="daoMethods" expression="execution(* test.dao.*.*(..))"/>
<aop:advisor advice-ref="txadvice" pointcut-ref="daoMethods"/>
</aop:config>
<!-- 第二种方法配置事务
<bean id="transactionProxy" class= "org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true">
必须为true时CGLIB才不用强制编写DAO接口
<property name="proxyTargetClass" value="true" />
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributes">
<props>
<prop key="add*">PROPAGATION_REQUIRED, -Exception</prop>
<prop key="del*">PROPAGATION_REQUIRED, +MyException</prop>
<prop key="update">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED, readOnly</prop>
</props>
</property>
</bean>
<bean id="userService" parent="transactionProxy">
<property name="target" ref="iUserService"></property>
</bean>
<bean id="iUserService" class="test.service.UserServiceImpl"></bean>
-->
<bean id="userService" class="test.service.UserServiceImpl"></bean>
<bean id="userDao" class="test.dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- spring管理的自定义filter -->
<bean id="myFilter" class="test.service.MyFilter"></bean>
<!-- spring管理struts2的Action -->
<bean id="loginAction" class="test.action.LoginAction" scope="prototype"></bean>
<bean id="sessionAction" class="test.action.SessionAction" scope="prototype"></bean>
<bean id="myInterceptor" class="test.service.MyInterceptor" scope="prototype"></bean>
</beans></span>
注意:
① 配置事务时,如果事务是与含有sessionFactory的DAO层关联的话,要将<aop:config>标签的proxy-target-class属性设为true(第二种方法是proxyTargetClass属性),否则就会报错
② 采用Resource或Autowired注解时,bean中无需配置property属性标签。
③ 采用第二种方法配置sessionFactory时,还需要另外引入两个包(详见上述“所需jar”部分)。
5. filter与拦截器
● MyFilter.java
[java] view plaincopy
<span style="background-color:rgb(255,255,255)">package test.service;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class MyFilter implements Filter {
private String encoding;
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig config) throws ServletException {
System.out.println("========" + config.getInitParameter("encoding") + "========");
encoding = config.getInitParameter("encoding");
}
}</span>
● MyInterceptor.java
[java] view plaincopy
<span style="background-color:rgb(255,255,255)">package test.service;
import java.util.Map;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
@SuppressWarnings("serial")
public class MyInterceptor implements Interceptor{
@Override
public void destroy() {
}
@Override
public void init() {
}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
Map sessionMap = invocation.getInvocationContext().getSession();
String username = (String)sessionMap.get("username");
if (username != null) {
return invocation.invoke();
}
return "error";
}
}</span>
filter与拦截器(interceptor)的区别:
二者不论从结构还是功能都非常相似,但是二者是有区别的,:
① filter是基于servlet容器的,而interceptor仅限于struts2,因此filter的作用域要远大于interceptor。
② filter中doFilter方法是基于回调函数,而interceptor中intercept方法则是基于java反射。
③ filter的功能要远大于interceptor,filter除了过滤请求外通过通配符可以保护页面,图片,文件,还可以进行加密、安全过滤、权限管理等等,而Interceptor基本只能过滤请求。
④ filter拦截请求的粒度较粗,interceptor拦截请求的粒度较细。
6. action层
● LoginAction.java
[java] view plaincopy
<span style="background-color:rgb(255,255,255)">package test.action;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import test.entity.User;
import test.service.IUserService;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class LoginAction extends ActionSupport {
@Resource
private IUserService userService;
private String username;
private String password;
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;
}
@Override
public String execute() throws Exception {
User user = new User();
user.setUsername(username);
user.setPassword(password);
try {
userService.addUser(user);
HttpServletRequest request = ServletActionContext.getRequest();
request.getSession().setAttribute("username", username);
return "success";
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}
}</span>
7. service层
● UserServiceImpl.java
[java] view plaincopy
<span style="background-color:rgb(255,255,255)">package test.service;
import java.util.List;
import javax.annotation.Resource;
import test.dao.IUserDao;
import test.entity.User;
public class UserServiceImpl implements IUserService{
@Resource
private IUserDao userDao;
@Override
public void addUser(User user) throws Exception {
userDao.addUser(user);
if (!"admin".equals(user.getUsername()) || !"admin".equals(user.getPassword())) {
throw new Exception();
}
}
@Override
public boolean updateUser(User user) {
return false;
}
@Override
public boolean delUser(String username) {
return false;
}
@Override
public List<User> findAllUser() {
return null;
}
}</span>
接口因为很简单,就不展示了,这里我将filter和拦截器也放到了service层,仅是个示例而已,filter或interceptor最好单独放在一层。
8. dao层
● UserDaoImpl.java
[java] view plaincopy
<span style="background-color:rgb(255,255,255)">package test.dao;
import java.util.Date;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import test.entity.User;
public class UserDaoImpl extends HibernateDaoSupport implements IUserDao{
@Override
public void addUser(User user){
user.setName("wang");
user.setCreateTime(new Date());
user.setModifyTime(new Date());
this.getHibernateTemplate().save(user);
}
}</span>
9. entity层
[java] view plaincopy
<span style="background-color:rgb(255,255,255)">package test.entity;
import java.util.Date;
public class User {
private String username;
private String password;
private String name;
private String email;
private String tell;
private Date createTime;
private Date modifyTime;
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 String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTell() {
return tell;
}
public void setTell(String tell) {
this.tell = tell;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getModifyTime() {
return modifyTime;
}
public void setModifyTime(Date modifyTime) {
this.modifyTime = modifyTime;
}
}</span>