嗨,我对struts2很新。从一些书籍和网站我得到了这个例子。在动作类中,它使用validate方法来检查逻辑。该方法在print语句中称为bcoz。但是错误没有显示在字段附近。 Jst帮帮我
的index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home</title>
</head>
<body>
<s:form action="LoginAction ">
<s:textfield name="username" label="Username" />
<s:textfield name="password" label="Password" />
<s:submit value="Login"></s:submit>
</s:form>
</body>
</html>
struts.xml中
<package name="default" extends="struts-default">
<action name="LoginAction" class="org.shammu.struts2.actions.LoginAction">
<result name="success">/welcome.jsp</result>
<result name="input">/index.jsp</result>
</action>
<action name="emptypassthrough">
<result>index.jsp</result>
</action>
</package>
LoginAction.java
package org.shammu.struts2.actions;
import org.shammu.struts2.beans.LoginBean;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
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;
}
public String execute(){
LoginBean login = new LoginBean();
login.setPassword(password);
login.setUsername(username);
if (getUsername().equals("abcd")) {
return "success";
} else {
return "input";
}
}
@Override
public void validate() {
if (username.length() < 3) {
System.out.print("user err ok");
this.addFieldError(username, "Username Empty Pls provide");
}
if (password.length() < 3) {
System.out.print("Pass err ok");
this.addFieldError(password, "Password Empoty provride one pkls");
}
}
}
我没有考虑执行方法。我希望jst在字段附近打印错误消息...帮助
答案 0 :(得分:4)
您未正确使用addFieldError
方法。该方法中的第一个参数是字段的名称。在您的情况下,它应该是"username"
。
addFieldError("username", "Username Empty Pls provide");
答案 1 :(得分:3)
要显示fielderror
,您需要在jsp中添加<s:fielderror />
。
如果它们存在,则渲染字段错误。具体布局取决于特定主题。默认情况下,字段错误字符串将被html转义。
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home</title>
</head>
<body>
<s:form action="LoginAction ">
<s:textfield name="username" label="Username" /><s:fielderror fieldName="username"/>
<s:textfield name="password" label="Password" /><s:fielderror fieldName="password"/>
<s:submit value="Login"></s:submit>
</s:form>
</body>
</html>