使用标签
注意:Struts2使用标签库找不到URI:[struts-tags]的taglib[s]问题解决[1]
新建 login2.jsp
文件,内容如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Struts2.3 Login2</title>
</head>
<body>
<s:form action="login">
<s:textfield name="username" label="username"></s:textfield>
<s:textfield name="password" label="password"></s:textfield>
<s:submit label="submit"></s:submit>
</s:form>
</body>
</html>
查看结果:
在 Action 中使用 ActionSupport
新增页面
login3.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Struts2.3 Login3</title>
</head>
<body>
<s:form action="login3">
<s:textfield name="username" label="username"></s:textfield>
<s:textfield name="password" label="password"></s:textfield>
<s:submit label="submit"></s:submit>
</s:form>
</body>
</html>
LoginAction3.java
package space.terwer;
import org.apache.commons.lang3.StringUtils;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction3 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;
}
@Override
public void validate() {
if(StringUtils.isBlank(this.getUsername())) {
this.addFieldError("username", "username required");
}
if(StringUtils.isBlank(this.getPassword())) {
this.addFieldError("password", "password required");
}
}
public String execute() {
return "success";
}
}
修改 struts.xml 添加校验跳转 input
struts.xml
<!-- 使用ActionSupport -->
<action name="login3" class="space.terwer.LoginAction3">
<result name="success">/result.jsp</result>
<result name="input">/login3.jsp</result>
</action>
效果
业务验证
在 LoginAction2.java
的 execute()
方法添加验证逻辑
public String execute() {
if("hello".equals(this.getUsername().trim()) && "world".equals(this.getPassword().trim())){
return "success";
}
this.addFieldError("username", "username or password error");
return "failer";
}
在 struts.xml
加入跳转逻辑
<!-- 使用ActionSupport -->
<action name="login3" class="space.terwer.LoginAction3">
<result name="success">/result.jsp</result>
<result name="input">/login3.jsp</result>
<result name="failer">/login3.jsp</result>
</action>
效果
注意:result.jsp
里面的两种写法等价。
username:${requestScope.username}<br />
password:${requestScope.password }
username:<%=request.getParameter("username") %><br />
password:<%=request.getParameter("password") %>
找到
struts2-core
的jar
包,将其复制到无关文件夹中,当作压缩文件解压,在其中的META-INF
目录中找到struts-tags.tld
文件,将其复制到项目中webapp/WEB-INF
目录下,然后在web.xml
文件中 (之前) 添加以下内容:
↩︎<!--配置/struts-tag位置--> <jsp-config> <taglib> <taglib-uri>s</taglib-uri> <taglib-location>/WEB-INF/struts-tags.tld</taglib-location> </taglib> </jsp-config>