第一步,
首先在web.xml中定义,以及
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" 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">
<display-name>Struts Blank</display-name>
<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>
filter是一个过滤器,是一个url的拦截,
filter-mapping拦截哪些url
第二步,
定义Action,
比如,
在配置package src/com.test.action.LoginAction.java文件
package com.test.action;
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;
}
//此处验证用户必须等hello 密码登录word才会返回成功页面。当然,真实开发中肯定不会这样写,这里只是做一个模拟。
public String execute() throws Exception
{
//if("hello".equals(this.getUsername().trim()) && "word".equals(this.getPassword().trim()))
//{
return "failer";
//}
// else
// {
// this.addFieldError("username", "usernmae or password error");
// return "failer";
// }
}
//下面内容判断用户名不能为空
}
配置好Action之后,
第三步,
定义struts.xml文件
<?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" />
<package name="default" namespace="/" extends="struts-default">
<action name="login" class="com.test.action.LoginAction">
<result name="success">/success.jsp</result>
<result name="failer">/login.jsp</result>
<result name="input">/error.jsp</result>
</action>
</package>
</struts>
其中,
<package name="default" namespace="/" extends="struts-default">
<action name="login" class="com.test.action.LoginAction">
//action name和package中的LoginAction对应
<result name="success">/success.jsp</result>
//result name的名称和LoginAction的execute()方法的返回值对应,
<result name="failer">/login.jsp</result>
<result name="input">/error.jsp</result>
</action>
注意:
一定要确定你在excute返回的字符串在 struts.xml中有定义
还有一个要提醒的就是:
在validate中验证有错误的话且没有指定return 字符串的话,
struts2默认就返回的是 return INPUT 也就是return "input"
第四步,
定义好struts.xml文件的result name所对应的 .jsp文件即可。
然后,就可以了,点击对应新建的project工程,右击Run As-> Run on Server运行tomcat服务器,
首先查看Server日志,是否正确运行。
然后检查浏览器url是否出错,url末尾须加上struts.xml中所定义的action name.
eg:
http://localhost:8080/struts2001/login
或者
http://localhost:8080/struts2001/login.action
一个简单的struts搭建完成。