Servlet和Struts2的交互

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

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

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

1.修改配置文件如下:

  <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>*.action</url-pattern>
  	<dispatcher>REQUEST</dispatcher>
  	<dispatcher>FORWARD</dispatcher>
  </filter-mapping>
  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>*.do</url-pattern>
  	<dispatcher>REQUEST</dispatcher>
  	<dispatcher>FORWARD</dispatcher>
  </filter-mapping>

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

2.新建Servlet文件HelloServlet

主要代码如下:

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String helloWorld = "helloWorld";
		
		/*
		HttpSession session = request.getSession(true);
		session.setAttribute("hello", helloWorld);
		*/
		request.setAttribute("hello", helloWorld);
		
		request.getRequestDispatcher("/helloAction.action").forward(request, response);
		return;
	}
3.Struts2的配置文件

	<package name="struts2" extends="struts-default">
		<action name="helloAction" class="action.HelloAction">
			<result name="OK" type="dispatcher">/OK.jsp</result>
		</action>
	</package>
4.HelloAction文件主要内容

	public String execute() {
		
		HttpServletRequest request = ServletActionContext.getRequest();
		/*
		HttpSession session = request.getSession();
		String hello = (String)session.getAttribute("hello");
		*/
		String hello = (String)request.getAttribute("hello");
		
		System.out.println(hello);
		
		return "OK";
	}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值