一.引入必要的jar包,所需jar包如下:
二.配置web.xml.主要目的是拦截请求
<?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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>struts2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>s2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>s2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> </web-app>
三.创建并编写struts.xml,创建位置在src目录下
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <package name="Demo" extends="struts-default"> <!-- 2.5之后使用通配符时需要使用这句代码,否则会发生一些错误 --> <global-allowed-methods>regex:.*</global-allowed-methods> <action name="simple_*" class="com.hck.controller.SimpleAction" method="{1}"> <result name="ok">/MyJsp.jsp</result> <result name="success">/index.jsp</result> </action> </package> </struts>
四.编写action类,该类需要继承ActionSupport,在编写时需要注意action方法的格式,action方法不能带有参数
public class SimpleAction extends ActionSupport{ List<String> lists=new ArrayList<String>(); public List<String> getLists() { return lists; } public void setLists(List<String> lists) { this.lists = lists; } public String List() { lists.add("张三"); lists.add("李四"); lists.add("王五"); lists.add("老刘"); lists.add("123"); System.out.println("-----------"); return "ok"; } }
五.编写两个用于测试的jsp页面。index.jsp跟MyJsp.jsp,其中MyJsp.jsp使用到了sturts2标签所以需要引入相应的包。
<body> <form action="simple_List.action" method="post"> 用户名:<input type="text" name="username"/> 密码:<input type="password" name="password"/> <button type="submit">提交</button> </form> </body>
<%@taglib prefix="s" uri="/struts-tags" %>
<body>
<s:debug></s:debug>
<s:iterator value="lists" var="list">
<s:property value="list"/>
</s:iterator>
</body>
六.测试结果
七.总结:struts2相较于servlet来说要便捷的多,省去了许多的烦杂的代码量.只有有一个全局的变量,再定义其set跟get方法即可在跳转页面轻松获取其数据。