用戶登陸案例:
新建web項目
導(dǎo)入相關(guān)jar包
配置web.xml--配置struts2的核心過濾器
<pre>
<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>*.action</url-pattern>
</filter-mapping>
</pre>在src編寫struts.xml
編寫login.jsp
<pre>
<form action="login.action" method="post">
用戶名:<input type="text" name="name" />
密碼:<input type="text" name="pwd" />
<input type="submit" value="登陸" />
</form>
</pre>
注:action的提交地址:action是擴(kuò)展名,默認(rèn)為action;action的擴(kuò)展名和web.xml中配置的struts2的核心過濾器相匹配,也就是說如果表單中提交的地址以.action結(jié)尾,那么在配置filter的url-patten時,<url-pattern>*.action</url-pattern>;第三步和第五步紅色的代碼。
- 編寫LoginAction類
<pre>
public class LoginAction {
private String name;
private String pwd;
public String execute() {
if("bjsxt".equals(name) && "123".equals(pwd)) {
return "success";
}else {
return "failed";
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
</pre>
注:LoginAction中的屬性名和表單元素的名稱要一致。第五步橙色和第六步橙色代碼。并且為屬性提供get/set方法。Struts2自動將用戶提交的表單數(shù)據(jù)設(shè)置到LoginAction的對應(yīng)屬性上,并且在jsp中可以直接獲取,不用手動向request設(shè)置。
- 在struts.xml中配置LoginAction
<pre>
<struts>
<package name="user" extends="struts-default">
<action name="login" class="com.bjsxt.action.LoginAction">
<result name="success">/index.jsp</result>
<result name="failed">/login.jsp</result>
</action>
</package>
</struts>
</pre> - 訪問
http://localhost:8080/02_0725_struts2_login/login.jsp
結(jié)果: