之前学习的struts2,总结一下一些简单的使用步骤,以便方便学习:
功能实现:输入url地址跳转到一个输入界面,输入姓名,点击提交,跳转到另一个界面,显示Hello,XXX
1、创建一个新的web工程,将struts2的.jar文件复制到WEB-ROOT/WEB-INF/lib文件夹下,其中这个Lib文件夹是定义为用来存放.jar文件的。
2、配置struts2的前端控制器,找到WEB-ROOT/WEB-INF/web.xml文件,添加红色的代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- 定义struts2的前端控制器 -->
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
filter为一个过滤器,是struts2定义的一个前端控制器,这个类包含在struts2的jar包里。
3、配置struts.xml,struts.xml是默认的配置文件,红色字体是需要配置的。
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="hello" extends="struts-default" namespace="/">
<action name="toHello" class="org.struts.ToHello" method="execute">
<result name="success">/WEB-INF/toHello.jsp</result>
</action>
<action name="hello" class="org.struts.Hello" method="execute">
<result name="success">/WEB-INF/hello.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
4、写action类,
//toHello.java,用来跳转到输入界面,不需要输入和输出参数
package org.struts;
public class ToHello {
public String execute(){
return "success";
}
}
//Hello.java,用来接收表单提交的数据,以及输出
package org.struts;
public class Hello {
private String str;
public String execute(){
return "success";
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
5、写jsp文件,在路径WEB-INF下
//toHello.jsp
<%@page pageEncoding="utf-8" contentType="text/html;charset=utf-8"%>
<html>
<head></head>
<body>
<form action="hello.action" method="post">
名字:<input type="text" name="str"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
//hello.jsp
<%@page pageEncoding="utf-8" contentType="text/html;charset=utf-8"%>
<html>
<head></head>
<body>
<h2>Hello,${str}</h2>
</body>
</html>
6、部署在Tomcat上,启动Tomcat服务器,输入url地址http://localhost:8080/struts01/toHello.action
提交之后界面: