Servlet和Struts2的交互

来源:互联网 发布:c语言驱动编程 编辑:程序博客网 时间:2024/06/06 00:27

最近做项目,需要用Servlet读取Flex提交的值然后传到Struts2中,纠结了昨天一天一直到昨晚11点才将问题搞定。虽然过程很艰辛,不过最终还是把问题解决了,这点还是比较值得高兴的。整个过程也让我学到了很多,下面我把我的经验和大家分享下。

-------------------------------------

Servlet是可以和Struts2共存的,有些文章说不能共存是错误的,可能是因为在Struts2建立时默认将截取路径设置为/*,这种情况下过滤器会将所有请求截获到Struts2中,才导致Servlet和Struts2不兼容。

1.修改配置文件如下:

[html] view plaincopy
  1. <filter>  
  2.     <filter-name>struts2</filter-name>  
  3.     <filter-class>  
  4.         org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter  
  5.     </filter-class>  
  6. </filter>  
  7. <filter-mapping>  
  8.     <filter-name>struts2</filter-name>  
  9.     <url-pattern>*.action</url-pattern>  
  10.     <dispatcher>REQUEST</dispatcher>  
  11.     <dispatcher>FORWARD</dispatcher>  
  12. </filter-mapping>  
  13. <filter-mapping>  
  14.     <filter-name>struts2</filter-name>  
  15.     <url-pattern>*.do</url-pattern>  
  16.     <dispatcher>REQUEST</dispatcher>  
  17.     <dispatcher>FORWARD</dispatcher>  
  18. </filter-mapping>  

这个配置文件耗费了我昨天一下午和一晚上的时间。默认filter的转发方式为request,即接受到客户端请求将数据转发,增加forward转发方式,该方式为服务器内部转发。很多文章将url-pattern方式写为:
[html] view plaincopy
  1. <span style="font-size:13px;"><url-pattern>*.action;*.do</url-pattern></span>  
这个忽悠了我好长时间,最后实践才发现不能这么写,哈哈~~~

2.新建Servlet文件HelloServlet

主要代码如下:

[java] view plaincopy
  1. public void doPost(HttpServletRequest request, HttpServletResponse response)  
  2.         throws ServletException, IOException {  
  3.     String helloWorld = "helloWorld";  
  4.       
  5.     /* 
  6.     HttpSession session = request.getSession(true); 
  7.     session.setAttribute("hello", helloWorld); 
  8.     */  
  9.     request.setAttribute("hello", helloWorld);  
  10.       
  11.     request.getRequestDispatcher("/helloAction.action").forward(request, response);  
  12.     return;  
  13. }  
3.Struts2的配置文件

[html] view plaincopy
  1. <span style="font-size:10px;">  <package name="struts2" extends="struts-default">  
  2.         <action name="helloAction" class="action.HelloAction">  
  3.             <result name="OK" type="dispatcher">/OK.jsp</result>  
  4.         </action>  
  5.     </package></span>  
4.HelloAction文件主要内容

[java] view plaincopy
  1. public String execute() {  
  2.       
  3.     HttpServletRequest request = ServletActionContext.getRequest();  
  4.     /* 
  5.     HttpSession session = request.getSession(); 
  6.     String hello = (String)session.getAttribute("hello"); 
  7.     */  
  8.     String hello = (String)request.getAttribute("hello");  
  9.       
  10.     System.out.println(hello);  
  11.       
  12.     return "OK";  
  13. }  
原创粉丝点击