1.在maven工程下添加需要导入的jar包节点
<dependencies> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.3.24</version> </dependency> <dependency> <groupId>org.apache.struts.xwork</groupId> <artifactId>xwork-core</artifactId> <version>2.3.24</version> </dependency> </dependencies>
2.web-inf文件下配置web.xml节点
<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>
3.构建index.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="s" uri="/struts-tags" %> <%@ page isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <s:fielderror value="error"></s:fielderror> <s:actionerror/> <s:property value="ret"/> <s:debug/> <form action="testAction" method="post"> 用户名:<input name="uname"/><br/> 密码:<input name="upwd"/><br/> <input type="submit"/> </form> </body> </html>
4.创建TestAction
方法一:实现Action接口
public String execute() throws Exception { System.out.println("action"); if (this.getUname().equals("")) { addFieldError("error", "用户名为空值"); addActionError("actionerror"); return "ret1"; }else if (this.getUpwd().equals("")){ addFieldError("error", "密码为空值"); return "ret1"; } return "ret1"; }
方法二:继承ActionSupport类
public void validate() { System.out.println("actionsuppo"); if (this.getUname().equals("")) { addFieldError("error", "用户名为空值"); addActionError("actionerror"); }else if (this.getUpwd().equals("")){ addFieldError("error", "密码为空值"); } }
5.配置struts.xml文件
<constant name="struts.enable.DynamicMethodInvocation" value="false"/> <constant name="struts.devMode" value="true"/> <package name="default" namespace="/" extends="struts-default"> <action name="testAction" class="action.TestAction"> <result name="input">index.jsp</result> </action> </package>
6.测试页面
但用户名为空时
但密码为空时
时间: 2024-09-30 10:49:58