Struts 2 要與 Spring 結合並不難,因為 Struts 2 本身就已經預留介面,在 struts2-core-2.x.x.jar 裡的 org.apache.struts2.default.properties 有這一段設定

### if specified, the default object factory can be overridden here
### Note: short-hand notation is supported in some cases, such as "spring"
###       Alternatively, you can provide a com.opensymphony.xwork2.ObjectFactory subclass name here
# struts.objectFactory = spring

### specifies the autoWiring logic when using the SpringObjectFactory.
### valid values are: name, type, auto, and constructor (name is the default)
struts.objectFactory.spring.autoWire = name

 

現在來實作一下:

Step 01: 建立一個帳號登入的 userLogin.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="sj" uri="/struts-jquery-tags" %>
<%@ taglib prefix="sb" uri="/struts-bootstrap-tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
    <!-- 設定 base patch  
    if you want to set a base path for all relative links so that you don't need to repeat
    ${pageContext.request.contextPath} in every relative link, use the <base> tag.
    This way every relative link (i.e. not starting with / or a scheme) will become relative to the <base>.
    -->
    <c:set var="url">${pageContext.request.requestURL}</c:set>
    <base href="${fn:substring(url, 0, fn:length(url) - fn:length(pageContext.request.requestURI))}${pageContext.request.contextPath}/" />    
    <sj:head jqueryui="false"/>
    <sb:head includeScripts="true" includeScriptsValidation="false" includeStyles="true" />    
    
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="keywords" content="struts2, twitter, bootstrap, plugin, showcase" />
    <meta name="description" content="Enable Client Side Validation - Struts2 Bootstrap Plugin" />
    
    <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
    <!--[if lt IE 9]>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

     <!-- Custom styles for this template
    <link href="css/Cosmo/bootstrap.min.css" rel="stylesheet">
    <link href="css/homepage.css" rel="stylesheet">
    -->
<title>User login</title>
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-6">
            Hi Welcome !!
        </div>
        <div class="col-md-6">

            <h1>歡迎光臨  </h1>
            <p>請輸入您的帳號</p>
            <s:actionmessage theme="bootstrap"/>
            <s:actionerror theme="bootstrap"/>


            <!--            
            <s:fielderror theme="bootstrap"/>

            <s:if test="hasActionErrors()">
               <div class="errors">
                  <s:actionerror/>
               </div>
            </s:if>           
            <s:if test="hasActionMessages()">
               <div class="welcome">
                  <s:actionmessage/>
               </div>
            </s:if>
             -->

            
            <s:form action="userLogin" theme="bootstrap" class="form-signin">
                <s:textfield key="loginName" />                
                <s:password key="password" />
                <s:submit cssClass="btn btn-primary"/>
            </s:form>

        </div>
    </div>

    <footer class="footer">
        <p class="pull-right"><a href="#">Back to top</a></p>        
    </footer>

</div>
<!-- /container -->

</body>
</html>

 

Step 02: 建立對應的 userLogin Action Class: com.gu.test.spring.LoginAction

package com.gu.test.spring;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
    private String loginName;
    private String password;
    
    public String getLoginName() {
        return loginName;
    }
    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    
    public String execute() throws Exception {
        if (isInvalid(getLoginName()))
            return INPUT ;
        if(isInvalid(getPassword()))
            return INPUT;  
        
        return SUCCESS;
    }
    
    private boolean isInvalid(String str){
        return ( str==null || str.length()==0 );
    }
    
    @Override
    public void validate() {
        // TODO Auto-generated method stub
        super.validate();
        boolean isInvalidError = false;
        if (isInvalid(getLoginName())){
            this.addFieldError("loginName", this.getText("loginName.error") );
            isInvalidError = true;
        }
        if (isInvalid(getPassword())){
            this.addFieldError("password", this.getText("password.error") );
            isInvalidError = true;
        }
        if (isInvalidError){
            this.addActionError(getText("errors.general"));
        }
        
    }
}

 

Step 03: 利用Maven 來加入 Spring 的 Jar 檔. 可以參考 http://mvnrepository.com/artifact/org.apache.struts/struts2-spring-plugin

<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-spring-plugin</artifactId>
    <version>2.3.16.3</version>
</dependency>

 

Step 04: 配置 Struts & Spring : struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
        
    <!--加入 Spring -->    
    <constant name="struts.objectFactory" value="spring" />
<struts>
    <package name="test" namespace="/test" extends="struts-default">

        <!-- Spring Testing -->
        <action name="userLogin_*" method="{1}" class="userLogin">
            <result name="input">userLogin.jsp</result>
            <result name="success">eip.jsp</result>
        </action>  

        <!-- Add additional "example" package actions here. -->

    </package>
</struts>

這裡的 class="userLogin" 已轉由 Spring 的介面來接手,因此在 Spring 的 applicationContext.xml 要有 bean id="userLogin" 來承接,並指定 class="com.gu.test.spring.LoginAction"

 

Step 05: 配置 Struts & Spring : 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.xsd">

    <bean id="userLogin" class="com.gu.test.spring.LoginAction" scope="prototype"/>
    
</beans>

 

Step 06: 配置 Struts & Spring : web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="struts_blank" version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <display-name>Struts Blank</display-name>

<!-- Context Configuration locations for Spring XML files -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>


  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
      org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    </filter-class>
  </filter>

  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
    

  <!-- 啟動  Spring Bean Configure the Spring listener -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>  
 
</web-app>

 

登入 http://localhost:8080/guMIS/test/userLogin_input 測試,這樣就可以運作正常了。

arrow
arrow
    文章標籤
    Struts 2 Spring
    全站熱搜
    創作者介紹
    創作者 MIS 的頭像
    MIS

    MISTECH 技術手抄本

    MIS 發表在 痞客邦 留言(0) 人氣()