使用validate函数时是否有必要在表单中使用struts标签?

时间:2014-10-30 11:32:02

标签: java jsp struts2

我阅读了struts教程,并且在struts验证中遇到了一些问题(来源:http://www.tutorialspoint.com/struts_2/struts_validations.htm)。当我希望使用struts框架提供的隐式validate()函数时,我想知道是否有必要使用struts标记。是否有任何可能的方法使用我没有使用struts标签仍然,我可以使用隐式验证功能以及选项' addFieldError'?

我曾尝试制作相同的代码,但似乎我们无法使用' addFieldError'除非我们在表单中完全使用struts标签。任何人都可以对此作一点澄清吗?

以下是我尝试过的代码,但是' addFieldError'没有工作,网页被直接重定向到' struts.xml'中指定的页面。结果被指定为"输入"

/*public void validate()//Function to check implicit validations provided by Struts
{
    System.out.println("Inside implicit validate\n");
    if(!name.equalsIgnoreCase("harshit"))
    {
        addFieldError("name","Only Harshit is allowed in name field");
    }
}*/

很抱歉,因为我不熟悉这里的格式。

struts.xml的内容

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="false"/>
<package name="helloworld" extends="struts-default">
    <action name="hello"
    class="com.tutorialspoint.struts2.HelloWorldAction"
    method="execute">
    <result name="success">/HelloWorld.jsp</result>
    <result name="error">/error.jsp</result>
    <result name="input">/index.jsp</result>
    </action>
</package>
</struts>

Web.xml的内容

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://java.sun.com/xml/ns/javaee" 
   xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="WebApp_ID" version="3.0">

   <display-name>Struts 2</display-name>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
   </filter>

   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

Index.jsp页面的内容

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script>
function validate()
{
    var empId= document.frm.empId.value;
    var name=document.frm.name.value;
    var letters = /^[A-Za-z]+$/;
    var email=document.frm.email.value;
    if(name=="")
        {
        //alert("Name should not be blank..");
        document.getElementById("error").innerHTML="Name shouldnt be blank";
        document.frm.name.focus();
        return false;
        }

    else if(empId=="")
        {
        alert("Employee ID should not be blank");
        document.frm.empId.focus();
        return false;
        }

    else if(isNaN(empId)==true)
        {
        alert("Employee ID should be a number");
        return false;
        }
    else if(!name.match(letters))
        {
        alert("Name should be an ablphabet");
        return false;
        }
    else if(!email.match(".com"))
        {
        alert("Please enter a valid email");
        return false;
        }
}
</script>
<title>Hello World</title>
</head>
<body bgcolor="beige">
   <h1>Employee Details</h1>

<form  action="hello" name="frm" onSubmit="return validate()">

      <label>Please enter your name</label><br/>

    <input type="text" name="name"/><font size="4" color="red"> <div id="error"> </div></font>

      <br/>
      <label>Employee ID:</label><br/>
       <input type="text" name="empId"/><br/>

       <label>Email Id:</label><br/>
       <input type="text" name="email">
       <br/>
       <label>Phone Number:</label><br/>
       <input type="text" name="phone">
       <br/>
       <br/>

       <br/>
       <input type= "button" value="Check" onclick="return validate()">
      <input type="submit" value="Submit"/>
   </form>
</body>
</html>

我的动作类的内容

    package com.tutorialspoint.struts2;
    import com.opensymphony.xwork2.ActionSupport;


    public class HelloWorldAction extends ActionSupport
    {  
        private String name ;
        private String email;
        private long phone;
        private int empId;


        public int getEmpId() {
            return empId;
        }
        public void setEmpId(int empId) {
            this.empId = empId;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
        public long getPhone() {
            return phone;
        }
        public void setPhone(long phone) {
            this.phone = phone;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }


        public String execute() throws Exception
        {
            //String result=serverValidation();
            String result="success";//Temporarily making it success as the server validation is commented. Aim is to check the implicit validate method provided by struts
            return result;
        }

        /*public String serverValidation() throws Exception
        {
            long phnum= phone;
            System.out.println("Phone="+phone);
            System.out.println("phnum="+phnum);
            System.out.println("Employee Id=" +empId);
            int d=0;
            while(phnum>0)
            {
                phnum=phnum/10;
                d=d+1;
            }
            if(d==10)
            return "success";

            else
            {
                System.out.println("d="+d);
                return "error";
            }
        }*/

        public void validate()//Function to check implicit validations provided by Struts
        {
            System.out.println("Inside implicit validate\n");
            if(!name.equalsIgnoreCase("harshit"))
            {
                addFieldError("name","Only Harshit is allowed in name field");
            }
        }



}

1 个答案:

答案 0 :(得分:1)

感谢@AleksandrM和@AndreaLigios提供答案。以下是一个详细的描述:

即使不必使用基于Struts2的表单标记,也可以使用Struts2框架提供的隐式validate()方法。您需要做的就是在要显示错误消息的相应jsp / html页面中使用<s:fielderror>标记,然后使用<param>标记指定哪个参数,错误必须是显示。参数名称应与Action类中使用的相同。请参阅上面代码中的validate()方法,了解如何为特定参数定义错误消息。我们可以使用html / jsp中的以下代码段来显示错误消息:

<s:fielderror>
    <s:param> name</s:param>
</s:fielderror>

此处,name是已完成验证的参数。