1.struts2在开发中所必须用到的jar包导入到项目的lib目录下
2.在web.xml中配置一个过滤器,代码格式如下
<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>/*</url-pattern> </filter-mapping>
当然,大家应该知道struts2的核心技术是基于拦截器实现的
3.写一个简单的Action
CustomerAction.java
package com.sdu.crm.action; import org.directwebremoting.util.SystemOutLoggingOutput; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.sdu.crm.dao.impl.CustomerDaoImpl; import com.sdu.crm.pojo.Customer; import com.sun.net.httpserver.Authenticator.Success; public class CustomerAction extends ActionSupport { private static final long serialVersionUID = 1L; private Customer customer; public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } /** * * @author fighter24h * 自定义的action方法 * 其形式同execute方法 * 返回String,抛出Exception * 方法名字对应struts配置文件中的method属性 */ public String addCustomerInfo() throws Exception { return "addCustomerInfoOk"; } }
4.配置acton对应的strtus的xml文件
示例:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- package name:用来实现继承的 namespace:用来解决重名的,访问的时候充当路径--> <package name="action-customer-lzm" extends="struts-default" namespace="/customer"> <!-- name:action的名字,访问的使用需要用到 class:具体的action是哪个类,写全路径 method:我们自己定义的方法,而不是执行execute方法 --> <action name="addCustomerInfo" class="com.sdu.crm.action.CustomerAction" method="addCustomerInfo"> <!--name:来自method的返回值,可以自定义! --> <result name="addCustomerInfoOk">/index.jsp</result> </action> </package> </struts>