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

### 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="" %>
<%@ taglib prefix="fn" uri="" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">

    <!-- 設定 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=""></script>

     <!-- 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>

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

            <h1>歡迎光臨  </h1>
            <s:actionmessage theme="bootstrap"/>
            <s:actionerror theme="bootstrap"/>

            <s:fielderror theme="bootstrap"/>

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

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


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

<!-- /container -->



Step 02: 建立對應的 userLogin Action Class:


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 ;
            return INPUT;  
        return SUCCESS;
    private boolean isInvalid(String str){
        return ( str==null || str.length()==0 );
    public void validate() {
        // TODO Auto-generated method stub
        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){


Step 03: 利用Maven 來加入 Spring 的 Jar 檔. 可以參考



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

<?xml version="1.0" encoding="UTF-8" ?>
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    <!--加入 Spring -->    
    <constant name="struts.objectFactory" value="spring" />
    <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>

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


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


Step 05: 配置 Struts & Spring : applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <bean id="userLogin" class="" scope="prototype"/>


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

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="struts_blank" version="2.4"
  <display-name>Struts Blank</display-name>

<!-- Context Configuration locations for Spring XML files -->




  <!-- 啟動  Spring Bean Configure the Spring listener -->


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



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