简单范例
1、下载struts2.0.11-all.rar
2、开发环境:myEclipse6.0
Servelet container Tomcat6.0
3、工程示例
new-->web project
4、手工配置
1)新建jsp页面login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'login.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="login.action" method="post"> username:<input type="text" name="username"><br> password:<input type="password" name="password"><br> <input type="submit" value="submit"> </form> </body> </html>
同时在tomcat的server.xml文件中加入<Context path="/struts2" docBase="D:\workspace\struts2\WebRoot" reloadable="true"/>
2)配置必要的jar包,拷贝到lib下
common-logging.jar
freemarker.jar
ognl.jar
struts2-core.jar
xwork.jar
3)在WEB-INF目录下的web.xml文件中添加以下过滤器
<filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
4)新建类LoginAction
package com.test.action; import java.util.Map; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String execute() throws Exception { return "success"; } }
5)新建result.jsp
... <body> username:${requestScope.username} <br> </body> ...
6)struts.xml文件放在src下
<?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="struts2" extends="struts-default"> <action name="login" class="com.test.action.LoginAction"> <result name="success">result.jsp</result> </action> </package> </struts>
7)流程
login.jsp--->提交后---->struts.xml文件中找到name=login的Action-->根据页面上的值和action的set方法,
自动地将值赋给相应的变量--》然后执行action中execute()方法--》根据方法中返回结果跳转到所标识的页面