-----------補充說明-----------html
文章中所列出的struts2的2.2jar包已經不是最新的了,這個版本有嚴重漏洞,java
如今最新版本爲2.3.15,因此。你懂的 http://struts.apache.org/download.cgi#struts23151
node
感謝網友提醒,如今不作ssh2的開發了,因此也忘了更新這篇文章,誤導你們了,抱歉!
web
SSH框架,當今最爲流行的項目開發框架組合,那麼掌握他的第一步是學習如何配置環境,java Web開發的不管哪一種框架都離不開各類xml配置,雖說配置在網上處處都有,可是要成爲合格的程序猿,必需要明白配置中每一部分的意義,分析它的規律,所以這一步相當重要。spring
SSH分爲SSH1和SSH2,區別主要在於Struts的版本,即Struts1和Struts2,Struts1與Struts2在配置上有所差異,sql
這回主要爲你們介紹的是基於Struts2的SSH2框架搭建。數據庫
咱們在搭建框架以前,首先必定要注意各個框架的版本,不一樣的版本集成方式和所需的jar包是有區別的。express
SSH2框架的版本爲:struts-2.2.3 + spring-2.5.6 + hibernate-3.6.8apache
1. 所需jar包:猛擊下載免費jar包資源api
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配置
注意:
① 配置自定義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配置
- <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>
-
- <constant name="struts.objectFactory" value="spring" />
-
-
- <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
- <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">
-
- <context:annotation-config/>
-
-
- <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>
-
-
- <bean id="myFilter" class="test.service.MyFilter"></bean>
-
-
- <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
- <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
- <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
- <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
- <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
- <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層
- <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>