整个项目工程的目录结构如下:
用Eclipse构建一个Struts工程,步骤如下:
1.添加相关的jar包支持
2.编写配置文件
(1)编写web.xml(web项目配置文件)
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<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>
</web-app>
(2)编写struts.xml(Struts2框架配置文件)
<?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>
<constant name="struts.devMode" value="true"></constant>
<constant name="struts.i18n.encoding" value="UTF-8"></constant>
<package name="mypkg" namespace="/student" extends="struts-default">
<action name="studentInfo" class="com.mama.action.StudentAction">
<result name="success">/b.jsp</result>
</action>
</package>
</struts>
3.编写后台代码
在包com.mama.action下创建类StudentAction
StudentAction.java
package com.mama.action;
import com.opensymphony.xwork2.ActionSupport;
public class StudentAction extends ActionSupport {
private Integer id;
private String name;
private Integer age;
public String execute() {
return ActionSupport.SUCCESS;
}
/*
* id,name,age的setter,getter方法
*/
}
4.编写前端页面
参数传递流程:
a.jsp提交参数-->studentInfo.action获取参数并转发至b.jsp-->b.jsp取出参数
传参页面a.jsp
<body>
<a href="student/studentInfo.action?id=100">点击我提交参数id</a>
<form action="student/studentInfo.action" method="get">
编号:<input type="text" name="id" value="1"/><br/>
姓名<input type="text" name="name" value="张三"/><br/>
年龄:<input type="text" name="age" value="100"/><br/>
<input type="submit" value="get方式提交参数"/>
</form><br/>
<form action="student/studentInfo.action" method="post">
编号:<input type="text" name="id" value="2"/><br/>
姓名<input type="text" name="name" value="李四"/><br/>
年龄:<input type="text" name="age" value="200"/><br/>
<input type="submit" value="post方式提交参数"/>
</form>
</body>
取参页面b.jsp
超链接传来的id值为:<s:property value="id"/><br/><br/>
<%String method=request.getMethod();
if (method.equals("GET")){%>
get提交方式传来的id值为<s:property value="id"/>,
name值为<s:property value="name"/>,
age值为<s:property value="age"/><br/>
<%}%>
<%String method1=request.getMethod();
if (method.equals("POST")){%>
post提交方式传来的id值为<s:property value="id"/>,
name值为<s:property value="name"/>,
age值为<s:property value="age"/><br/>
<%}%>
5.测试
在tomcat(端口号:8080)上部署该项目(项目名为:Struts04)
浏览器输入http://localhost:8080/Struts04/a.jsp
(1)点击超链接
(2)点击“get方式提交参数”
(3)点击“post方式提交参数”