最近做项目,需要用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方式写为:
- <span style="font-size:13px;"><url-pattern>*.action;*.do</url-pattern></span>
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;
- }
- <span style="font-size:10px;"> <package name="struts2" extends="struts-default">
- <action name="helloAction" class="action.HelloAction">
- <result name="OK" type="dispatcher">/OK.jsp</result>
- </action>
- </package></span>
- 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";
- }