Struts2 getting started Demo, struts2demo
1. introduce necessary jar packages. The required jar packages are as follows:
2. Configure web. xml to intercept requests
<?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>
3. Create and compile struts. xml in the src directory.
<? 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 "> <! -- This code must be used to use wildcards after 2.5. Otherwise, some errors may occur --> <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>
4. Compile the action class. This class must inherit the ActionSupport class. When writing, pay attention to the format of the action method. The action method cannot contain parameters.
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 ("Zhang San"); lists. add ("Li Si"); lists. add ("Wang Wu"); lists. add ("Liu"); lists. add ("123"); System. out. println ("-----------"); return "OK ";}}
5. Compile two jsp pages for testing. Index. jsp and MyJsp. jsp, where MyJsp. jsp uses the sturts2 label, so you need to introduce the corresponding package.
<Body> <form action = "simple_List.action" method = "post"> username: <input type = "text" name = "username"/> password: <input type = "password" name = "password"/> <button type = "submit"> 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>
6. Test Results
7. conclusion: struts2 is much more convenient than servlet, saving a lot of complicated code. only one global variable can be defined, and its data can be easily obtained on the jump page by defining its set and get methods.