一、web.xml配置filter
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Struts2</display-name> <filter> <filter-name>action</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>action</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>二、配置struts.xml
<?xml version="1.0"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"> <struts> <!-- 通过常量方式改变struts默认的属性配置, --> <constant name="struts.action.extension" value="do" /> <!-- 设置开发模式,重新加载国际化资源文件和配置文件 --> <constant name="struts.devMode" value="true" /> <!-- 动态方法调用 --> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <package name="HelloWorldPkg" namespace="/helloworld" extends="struts-default"> <!-- 默认该包下默认的action引用,若该包没有要访问的action元素,则使用默认的action引用 --> <default-action-ref name="HelloWorldAction" /> <!-- 设置默认的class引用,将摸个类作为默认的action类 --> <default-class-ref class="pde.ams.struts.action.HelloWorldAction" /> <!-- 通过通配符的方式实现动态方法调用 --> <action name="HelloWorldAction_*" class="pde.ams.struts.action.HelloWorldAction" method="{1}"> <result name="success">/index.jsp</result> <result name="save">/index.jsp</result> <result name="update">/success.jsp</result> </action> <!-- 没有类的action --> <action name="ActionNoClass"> <result>/index.jsp</result> </action> </package> </struts>
三、创建对应的包名及类名
package pde.ams.struts.action; import java.io.IOException; import org.apache.struts2.ServletActionContext; /** * HelloWorldAction */ public class HelloWorldAction { /** */ public String save() { try { ServletActionContext.getResponse().getWriter().println( "this is a resonse output jsp"); } catch (IOException e) { e.printStackTrace(); } System.out.println("save"); return null; } /** * 返回值:路由串 */ public String update() { System.out.println("update"); return "update"; } }
四、如何获取指定参数
1.在对应的Action中获取创建相应的属性名;
2.获取创建的属性名;
五、将后台的值传输到jsp;
1.引入struts2标签;
<%@taglib uri="/struts-tags" prefix="s"%>
2.获取对应的属性名的值;
<s:property value="name" />
五、servletActionContext的几个静态方法;
方法 | 说明 |
static PageContext getPageContext( ) | 取得Web应用的PageContext对象 |
static HttpServletRequest getRequest( ) | 取得Web应用的HttpServletRequest对象 |
static HttpServletResponse getResponse( ) | 取得Web应用的HttpServletResponse对象 |
static ServletContext getServletContext( ) | 取得Web应用的ServletContext对象 |