前提:tomcat服務器配置好
操作系統:win10
工具:eclipse jee,struts-2.3.24-all.zip
解壓struts-2.3.24-all.zip
將jar包導入eclipse
選擇全部,鼠標右擊Build Path,導包成功
修改web.xml,添加核心過濾器
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<init-param>
<param-name>struts.il8n.encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
如果沒有web.xml,點擊鏈接
在src目錄下新建struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 包含4個配置文件 -->
<!-- 不指定路徑,默認在src下時的方式 -->
<include file="struts-shop.xml" />
<include file="struts-user.xml" />
<include file="struts-shoppingcart.xml" />
<!-- 配置文件在具體包中時的方式 -->
<include file="com/test/demo/struts-product.xml" />
<!-- constant元素用於常量的配置,可用於編輯struts.properties的常量 -->
<!-- 設置默認編碼集爲UTF-8 -->
<constant name="struts.i18n.enconding" value="UTF-8" />
<!-- 瀏覽器是否進行緩存處理 -->
<constant name="struts.serve.static.browserCache" value="false" />
<!-- 配置文件是否自動加載無需啓動服務器 -->
<constant name="struts.configuration.xml.reload" value="true" />
<!-- 請求url後綴必須是action或do -->
<constant name="struts.action.extension" value="action,do" />
<!-- 關閉動態方法調用功能 -->
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<!-- 設置開發模式,產品發佈時改回false-->
<constant name="struts.devMode" value="true" />
<!-- package元素用於包的配置 -->
<!-- checkLogin -->
<package name="user" extends="struts-default" namespace="/">
<action name="checkLogin" class="com.test.demo.LoginAction" method="check">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
<!-- include用於包含配置 -->
<include file="example.xml" />
<!-- Add packages here -->
</struts>
src目錄下新建類LoginAction,並實現check方法,
package com.test.demo;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
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 check() {
ActionContext context=ActionContext.getContext();
if(username.equals("root")&&password.equals("123")) {
//將用戶名和密碼信息放入context對象中
context.put("username", username);
context.put("password", password);
context.put("success", "用戶登錄成功");
return SUCCESS;
}
else {
context.put("error", "用戶登錄失敗");
return ERROR;
}
}
}
success.jsp
error.jsp
login.jsp調用
注意:
自始至終,瀏覽器處理結果路徑都是http://localhost:8080/Struts2//checkLogin.action