J2EE社区

苟有恒,何必三更起五更眠;
最无益,只怕一日曝十日寒.
posts - 241, comments - 318, trackbacks - 0, articles - 16

struts2整合spring应用实例

Posted on 2008-09-13 17:34 xcp 阅读(54176) 评论(22)  编辑  收藏 所属分类: struts2
    我们知道struts1与spring整合是靠org.springframework.web.struts.DelegatingActionProxy来实现的,以下通过具体一个用户登录实现来说明struts2整合spring的相关内容.

    一、准备工作
        

 1.实例分析我们在这不与数据库打交道,所有就是当用登录的时候判断用户名是否为指定值,密码是否为指定值,以及相关的异常处理、
        2.为什么我们要说struts2整合spring呢?相信在家都知道,我也不用多说了....
        4.在  http://struts.apache.org/download.cgi#struts212下载struts2的jar包,源码,API文档.
        5.在  http://static.springframework.org/downloads/nightly/release-download.php下载不同版本的spring的jar包,源码,API文档.
        6.配置开发环境:MyEclipse6.0+Eclipse3.3+JDK6.0+Tomcat6.0+Struts 2.0.11+spring2.0
    7.新建web项目,导入相应的jar包,如以下所示:
     a.由于现在IDE开发工具还没有对struts2.0有很好的支持,所有我们需要手功配置,首先将我们刚下下来的struts2.0的lib里面的commons-logging-1.0.4.jar、ognl-2.6.11.jar、xwork-2.0.4.jar、freemarker-2.3.8.jar、struts2-core-2.0.11.1.jar以及struts2.0里面所需要的插件包struts2-spring-plugin-2.0.11.1.jar添加的WEB-INF/lib下面
     b.通过通过IDE开发工具项目对spring2.0的支持
    7.在src下建立struts.xml文件(具体的写法在后面呈现)
    8.配置web.xml,如下:
    

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd"
>
    
    
    
<!-- 加载struts2核心 -->
    
<filter>
        
<filter-name>struts2</filter-name>
        
<filter-class>
            org.apache.struts2.dispatcher.FilterDispatcher
        
</filter-class>
    
</filter>
    
<filter-mapping>
        
<filter-name>struts2</filter-name>
        
<url-pattern>/*</url-pattern>
    
</filter-mapping>

    
<!-- 指明spring配置文件在何处 -->
    
<context-param>
        
<param-name>contextConfigLocation</param-name>
        
<param-value>classpath*:applicationContext.xml</param-value>
    
</context-param>

    
<!-- 加载spring配置文件applicationContext.xml -->
    
<listener>
        
<listener-class>
            org.springframework.web.context.ContextLoaderListener
        
</listener-class>
    
</listener>    
</web-app>


        

    二、建立前台页面
      1.用户登录肯定有一个用户登录页面login.jsp,如下:
        

<%@ page language="java"  pageEncoding="GB2312"%>
<%@ taglib prefix="s"  uri="/struts-tags"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//CN">
<html>
  
<head>
      
<title>login2</title>
  
</head>

  
<body>
      
<s:form name="login" action="login" method="post" >
          
<s:textfield name="username" label="帐号"></s:textfield>
          
<s:password name="password"  label="密码"></s:password>
          
<s:submit></s:submit>
      
</s:form>
  
</body>
</html>

   2.若登录成功的index.jsp文件,如下:
    

<%@ page language="java"  pageEncoding="GB2312"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//CN">
<html>
  
<head>
      
<title>login2</title>
  
</head>
    
  
<body>
          
<div>
              
<h4>欢迎你!</h4><font color="red">${username}</font>
              
<br/>
              
<h4>你登录的密码是<h4><font color="red">${password}</font>;
          
</div>
  
</body>
</html>

3、用户名非法提示页面.usernameInvalid.jsp(通过el表达示得到异常信息)
    
    

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding
="GB18030"
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
    用户名非法:
<font color="red">${exception.message}</font>
</body>
</html>

4、密码非法提示页面.passwordInvalid.jsp(struts2标签得到异常信息);
    
    

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding
="GB18030"
%>
 
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
    密码非法:
<FONT  color="red"><s:property value="exception.message"/></FONT>
</body>
</html>

    
     三、建立对应的action

       1.提供用户请求服务的LoginService类
       
           

package org.topCSA.s2s.service;

import org.topCSA.s2s.exception.PasswordException;
import org.topCSA.s2s.exception.UsernameException;

public class LoginService
{
    
/*
     * 我们这只是一个小的例子,不与数据库打交到
     * 若有数据库操作,那么在这个LoginService就是操作具体Dao类实现登录的相关操作
     
*/

    
public boolean validate(String username,String password)throws Exception
    
{
        
boolean v = false;
        
if(!"xcp".equals(username))//如果用户名不等于xcp,就抛出一个异常
        {
            
throw new UsernameException("用户名不正确");
        }

        
else if(!"123".equals(password))))//如果密码不等于123,就抛出一个异常

        
{
            
throw new PasswordException("密码不正确");
        }

        
else
        
{
            v 
= true;            
        }

        
return v;
    }

}


       2.接收用户请求的LoginAction类

        

package org.topCSA.s2s.action;

import org.topCSA.s2s.service.LoginService;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport
{

    
/**
     * 
     
*/

    
private static final long serialVersionUID = 1L;

    
private String username;
    
private String password;
    
    
/*
     * 我们通过Spring的IOC容器注入LoginService,从而减少类之间的依赖关系
     
*/

    
private LoginService loginService;
    
    
public LoginService getLoginService()
    
{
        
return loginService;
    }

    
public void setLoginService(LoginService loginService)
    
{
        
this.loginService = loginService;
    }

    
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 void validate()
    
{
        
/*
         * 我们可以在这个方法类加一些输入验证 但是为了体现后面我们写的业务逻辑方法这就不验证
         
*/

    }

    
    @Override
    
public String execute() throws Exception
    
{
        
        
boolean result = loginService.validate(username, password);
        
if(result == true)
        
{
            
return SUCCESS;
        }

        
else
        
{
            
return INPUT;
        }

    }

}

   
  四、配置struts.xml与applicationContext.xml
    
        1.配置struts.properties,为了解决中文问题,具体用法参照struts2的用法如下:里面加上struts.i18n.encoding = gb2312,当然也可以直接加到struts.xml里面写法为<constant name="struts.i18n.encoding" value="gbk"></constant>
        2.配置struts.xml
        

<?xml version="1.0" encoding="GB2312" ?>
<!DOCTYPE struts PUBLIC
    
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    
<package name="struts2" extends="struts-default">
        
<action name="login" class="LoginAction">
            
<exception-mapping result="usernameInvalid" exception="org.topCSA.s2s.exception.UsernameException" />
            
<exception-mapping result="passwordInvalid" exception="org.topCSA.s2s.exception.PasswordException" />
            
<result name="success">/index.jsp</result>
            
<result name="input">/login.jsp</result>
            
<result name="usernameInvalid">/usernameInvalid.jsp</result>
            
<result name="passwordInvalid">/passwordInvalid.jsp</result>
        
</action>
    
</package>
</struts>


        3.配置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-2.0.xsd">
    
    
<bean name="loginService" class="org.topCSA.s2s.service.LoginService" />
    
    
<bean name="LoginAction" class="org.topCSA.s2s.action.LoginAction">
        
<property name="loginService">
            
<ref bean="loginService"/>
        
</property>
    
</bean>        

</beans>


         五、测试(全部成功)    
    

           



        
            
            


            
            




名称: ♪4C.ESL | .↗Evon
口号: 遇到新问题♪先要寻找一个方案乄而不是创造一个方案こ
mail: 联系我


Feedback

# re: struts2整合spring应用实例  回复  更多评论   

2008-09-13 18:48 by 12
?你的exception呢

# re: struts2整合spring应用实例  回复  更多评论   

2008-09-15 13:37 by xcp
@12
呵呵,exception我写在局部的!!!

# re: struts2整合spring应用实例  回复  更多评论   

2009-02-18 14:32 by mary
想看
exceptn.PasswordException和
UsernameException的代码

# re: struts2整合spring应用实例  回复  更多评论   

2010-03-23 13:12 by 打酱油的
你的exception让我们看看可以吗

# re: struts2整合spring应用实例  回复  更多评论   

2011-06-21 15:40 by 李俊
写的很清晰, 初学者或是想快速掌握的人的理想资料.

# re: struts2整合spring应用实例[未登录]  回复  更多评论   

2011-12-28 10:34 by JAVA
补充exception的代码

public class UsernameException extends Exception {

/**
*
*/
private static final long serialVersionUID = 1L;

public UsernameException(){};
public UsernameException(String message)
{
super(message);
}

}

# re: struts2整合spring应用实例[未登录]  回复  更多评论   

2011-12-28 10:35 by JAVA
另外一个exception的代码
public class PasswordException extends Exception {

/**
*
*/
private static final long serialVersionUID = 1L;
public PasswordException(){}
public PasswordException(String message)
{
super(message);
}

}

# re: struts2整合spring应用实例[未登录]  回复  更多评论   

2011-12-31 00:53 by 小猪
谢谢

# re: struts2整合spring应用实例[未登录]  回复  更多评论   

2012-02-23 23:06 by 123
多谢博主 我也成功了

# re: struts2整合spring应用实例  回复  更多评论   

2012-09-09 12:24 by lihuabest
多谢,初学者,整合不容易啊!

# re: struts2整合spring应用实例  回复  更多评论   

2013-01-22 09:46 by wangsk
谢谢楼主啊

# re: struts2整合spring应用实例  回复  更多评论   

2013-03-30 15:20 by 王保蛟
楼主,我按照你这个做了。提示找不到LoginAction,我用的spring3.0

# re: struts2整合spring应用实例[未登录]  回复  更多评论   

2013-04-02 20:03 by 小宝
很清晰 感谢楼主

# re: struts2整合spring应用实例[未登录]  回复  更多评论   

2013-06-02 19:24 by lee
奇怪了,你们竟然都能成功?我也是按照楼主的写法一步一步的写的,后来这里始终有报这错:
com.lee.ssh.test.exception.PasswordException: 密码不正确
com.lee.ssh.test.login.LoginService.validate(LoginService.java:13)
com.lee.ssh.test.login.LoginAction.execute(LoginAction.java:29)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450)
com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
..................

求解……

# re: struts2整合spring应用实例  回复  更多评论   

2013-07-29 22:24 by lcc0210
Struts2的action是每一此请求都被实例化一次,你用spring注入LoginService保存的是非静态变量,当访问action时action又被实例化了一次,此时LoginService已经不是现在这个对象所拥有,还是null。

# re: struts2整合spring应用实例  回复  更多评论   

2013-11-05 14:12 by 投币手
@lee
你应该是没写这两个jsp页面
passwordInvalid.jsp和usernameInvalid.jsp

# re: struts2整合spring应用实例  回复  更多评论   

2013-11-27 21:23 by jackLin
spring中的bean管理struts中的action时是要配置scope的

# re: struts2整合spring应用实例  回复  更多评论   

2014-05-04 09:47 by 涛涛
非常感谢

# re: struts2整合spring应用实例  回复  更多评论   

2014-10-27 15:42 by 123456
严重: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:506)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:488)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:115)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4909)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5492)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

十月 27, 2014 3:44:05 下午 org.apache.catalina.core.StandardContext listenerStart
严重: Skipped installing application listeners due to previous error(s)

# re: struts2整合spring应用实例  回复  更多评论   

2014-10-29 15:09 by 合格
根本不能运行

# re: struts2整合spring应用实例  回复  更多评论   

2016-01-25 10:22 by 落念
为什么我的是404错误

# re: struts2整合spring应用实例  回复  更多评论   

2016-02-28 11:58 by hdblocal
action中注入不了service

只有注册用户登录后才能发表评论。


网站导航: