2011-10-12 62 views
0

我有一个NetBeans中的Spring框架的Java Web应用程序项目,我试图使用Spring验证。Spring验证

我的应用程序所做的是提出一张支持票。

我已经阅读了几个教程,并且我得到了表单直到填充字段才发送。问题是我无法显示我在“Validator”类中定义的错误消息。

也就是说,如果必填字段未填写,表单不会发送,但错误消息不会出现在任何地方。

有人能告诉我我做错了什么吗?

这是我的代码:

SupportTicket类:

package controller; 


public class SupportTicket 
{ 
    private String SubmissionStatus; 
    private String ReportNumber; 
    private String SupportType; 
    private String WithContract; 
    private String Priority; 
    private String SupportTicketID; 
    private String CustomerName; 
    private String SenderName; 
    private String SenderLastName; 
    private String ContactMail; 
    private String ContactPhone; 
    private String Description; 



    public String submitTicket() 
    { 
     //Do something 
    } 


    //setters and getters for private members 

    public String getContactMail() { 
     return ContactMail; 
    } 

    public void setContactMail(String ContactMail) { 
     this.ContactMail = ContactMail; 
    } 

    public String getContactPhone() { 
     return ContactPhone; 
    } 

    public void setContactPhone(String ContactPhone) { 
     this.ContactPhone = ContactPhone; 
    } 

    public String getCustomerName() { 
     return CustomerName; 
    } 

    public void setCustomerName(String CustomerName) { 
     this.CustomerName = CustomerName; 
    } 

    public String getSenderName() { 
     return SenderName; 
    } 

    public void setSenderName(String SenderName) { 
     this.SenderName = SenderName; 
    } 

    public String getDescription() { 
     return Description; 
    } 

    public void setDescription(String Description) { 
     this.Description = Description; 
    } 

    public String getSubmissionStatus() { 
     return SubmissionStatus; 
    } 

    public void setSubmissionStatus(String SubmissionStatus) { 
     this.SubmissionStatus = SubmissionStatus; 
    } 

    public String getReportNumber() { 
     return ReportNumber; 
    } 

    public void setReportNumber(String ReportNumber) { 
     this.ReportNumber = ReportNumber; 
    } 

    public String getSupportTicketID() { 
     return SupportTicketID; 
    } 

    public void setSupportTicketID(String SupportTicketID) { 
     this.SupportTicketID = SupportTicketID; 
    } 

    public String getPriority() { 
     return Priority; 
    } 

    public void setPriority(String Priority) { 
     this.Priority = Priority; 
    } 

    public String getSupportType() { 
     return SupportType; 
    } 

    public void setSupportType(String SupportType) { 
     this.SupportType = SupportType; 
    } 

    public String getWithContract() { 
     return WithContract; 
    } 

    public void setWithContract(String WithContract) { 
     this.WithContract = WithContract; 
    } 


    public String getSenderLastName() { 
     return SenderLastName; 
    } 

    public void setSenderLastName(String SenderLastName) { 
     this.SenderLastName = SenderLastName; 
    } 

} 

SupportTicketValidator类:

package controller; 

import org.springframework.validation.Errors; 
import org.springframework.validation.ValidationUtils; 
import org.springframework.validation.Validator; 

public class SupportTicketValidator implements Validator 
{ 
    @Override 
    public boolean supports(Class aClass) 
    { 
     return SupportTicket.class.equals(aClass); 
    } 


    @Override 
    public void validate(Object target, Errors errors) 
    { 
     ValidationUtils.rejectIfEmptyOrWhitespace(errors, "SenderName", "SenderName.required", "Sender Name is required"); 
     ValidationUtils.rejectIfEmptyOrWhitespace(errors, "SenderLastName", "SenderLastName.required", "Sender Last Name is required"); 
     ValidationUtils.rejectIfEmptyOrWhitespace(errors, "ContactMail", "ContactMail.required", "E-mail is required"); 
     ValidationUtils.rejectIfEmptyOrWhitespace(errors, "CustomerName", "CustomerName.required", "Customer Name is required"); 
     ValidationUtils.rejectIfEmptyOrWhitespace(errors, "ContactPhone", "ContactPhone.required", "Phone is required"); 
    } 

} 

SupportTicketController类:

package controller; 

import org.springframework.web.servlet.ModelAndView; 
import org.springframework.web.servlet.mvc.SimpleFormController; 
import service.SupportTicketService; 

public class SupportTicketController extends SimpleFormController 
{ 

    public SupportTicketController() 
    { 
     setCommandClass(SupportTicket.class); 
     setCommandName("supportTicket"); 
     setSuccessView("resultView"); 
     setFormView("inputView"); 
    } 


    @Override 
    protected ModelAndView onSubmit(Object command) throws Exception 
    { 
     SupportTicket supportTicket = (SupportTicket)command; 
     ModelAndView mv = new ModelAndView(getSuccessView()); 
     mv.addObject("SubmissionStatus", supportTicket.submitTicket()); 
     mv.addObject("ReportNumber", supportTicket.getReportNumber()); 
     mv.addObject("CustomerName", supportTicket.getCustomerName()); 
     mv.addObject("SupportType", supportTicket.getSupportType()); 
     mv.addObject("WithContract", supportTicket.getWithContract()); 
     mv.addObject("SenderName", supportTicket.getSenderName()); 
     mv.addObject("SenderLastName", supportTicket.getSenderLastName()); 
     mv.addObject("ContactMail", supportTicket.getContactMail()); 
     mv.addObject("ContactPhone", supportTicket.getContactPhone()); 
     mv.addObject("Description", supportTicket.getDescription()); 
     mv.addObject("Priority", supportTicket.getPriority()); 

     return mv; 
    } 

} 

调度-servlet.xml中:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:p="http://www.springframework.org/schema/p" 
     xmlns:aop="http://www.springframework.org/schema/aop" 
     xmlns:tx="http://www.springframework.org/schema/tx" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> 

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/> 

    <bean id="supportTicketValidator" class="controller.SupportTicketValidator" /> 

    <bean class="controller.SupportTicketController" p:supportTicketService-ref="supportTicketService" p:validator-ref="supportTicketValidator"/> 

    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> 
     <property name="mappings"> 
      <props> 
       <prop key="index.htm">indexController</prop> 
      </props> 
     </property> 
    </bean> 

    <bean id="viewResolver" 
      class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
      p:prefix="/WEB-INF/jsp/" 
      p:suffix=".jsp" /> 

    <bean name="indexController" 
      class="org.springframework.web.servlet.mvc.ParameterizableViewController" 
      p:viewName="index" /> 

</beans> 

InputView.jsp:

<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %> 

<%@page contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> 

<!DOCTYPE html> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 

     <style type="text/css"> 
      h1 { 
       color: #3990bd; 

       font-size: 22px; 
       line-height: 22px; 
       font-family: Arial, Helvetica, sans-serif; 
       font-weight: normal; 

       text-decoration: none; 
       font-family: Arial, Helvetica, sans-serif; 
      } 

      p {font-family:Arial, Helvetica, sans-serif ; font-size: 12px;color:#666; font-weight:bold} 

      .blue {font-family:Arial, Helvetica, sans-serif ; font-size: 12px;color: #3990bd} 
      .error {font-family:Arial, Helvetica, sans-serif; font-size: 9px; color:#F00} 

     </style> 

    </head> 

    <body> 

     <h1>Please give us some information:</h1> 
     <p>&nbsp;</p> 

     <spring:nestedPath path="supportTicket"> 

      <form id="inputForm" action="" method="post"> 
       <form:errors path="*" cssClass="error"/> 

       <table width="640" border="0" cellpadding="5" cellspacing="5"> 
        <tr> 
         <td><p>Name:</p></td> 
         <td><spring:bind path="SenderName"> 
           <input type="text" name="${status.expression}" class="blue" value="${status.value}" size="50"> 
          </spring:bind> 

          <form:errors path="SenderName" cssClass="error"/> 

         </td> 
        </tr> 
        <tr> 
         <td><p>Last Name</p></td> 
         <td><spring:bind path="SenderLastName"> 
           <input type="text" name="${status.expression}" class="blue" value="${status.value}" size="50"> 
          </spring:bind> 
         </td> 
        </tr> 
        <tr> 
         <td><p>Email:</p></td> 
         <td><spring:bind path="ContactMail"> 
           <input type="text" name="${status.expression}" class="blue" value="${status.value}" size="50"> 
          </spring:bind> 
         </td> 
        </tr> 
        <tr> 
         <td><p>Customer name:</p></td> 
         <td></p> 
          <spring:bind path="CustomerName"> 
           <input type="text" name="${status.expression}" class="blue" value="${status.value}" size="50"> 
          </spring:bind> 
         </td> 
        </tr> 
        <tr> 
         <td><p>Phone:</p></td> 
         <td><spring:bind path="ContactPhone"> 
           <input type="text" name="${status.expression}" class="blue" value="${status.value}" size="50"> 
          </spring:bind> 
         </td> 
        </tr> 
        <tr> 
         <td><p>Support needed:</p></td> 
         <td><spring:bind path="SupportType"> 
           <select name="${status.expression}" class="blue" value="${status.value}"> 
            <option>App error</option> 
            <option>New app</option> 
            <option>Wrong result</option> 
            <option>Other</option> 
           </select> 
          </spring:bind> 
         </td> 
        </tr> 
        <tr> 
         <td><p>Do you have a support contract?</p></td> 
         <td><spring:bind path="WithContract"> 
           <select name="${status.expression}" class="blue" value="${status.value}"> 
            <option>No</option> 
            <option>Yes</option> 
           </select> 
          </spring:bind> 
         </td> 
        </tr> 
        <tr> 
         <td><p>Priority:</p></td> 
         <td><spring:bind path="Priority"> 
           <select name="${status.expression}" class="blue" value="${status.value}"> 
            <option>Low</option> 
            <option>Medium</option> 
            <option>High</option> 
           </select> 
          </spring:bind> 
         </td> 
        </tr> 
        <tr> 
         <td><p>Requirement description:</p></td> 
         <td> <spring:bind path="Description"> 
           <textarea name="${status.expression}" class="blue" value="${status.value}" rows="5" cols="52"> 
           </textarea> 
          </spring:bind> 
         </td> 
        </tr> 

        <tr> 
         <td>&nbsp;</td> 
         <td><div align="right"> 
           <input type="submit" class="blue" value="Submit Ticket"> 
          </div> 
         </td> 
        </tr> 
       </table> 
       <p><br> 
       </p> 
      </form> 

     </spring:nestedPath> 
    </body> 

</html> 

正如我提到的,验证工作(我认为),因为形式是不submited直到我填写所需的字段,但错误消息不显示与<窗体:错误>标签。

你能给我一个建议来解决我的问题吗?

+0

控制器是Spring 2.0风格,如果您没有特定的理由使用这种方式,我强烈建议使用Spring MVC应用程序的Spring 3.0风格。 @见http://viralpatel.net/blogs/2010/06/spring-3-mvc-create-hello-world-application-spring-3-mvc.html – Ralph

回答

1

1 PART注意我的评论

我已将应用程序移至Spring 3样式,并且我一直在阅读有关此新样式的很多内容。

现在我的应用程序看起来有点不同。

该应用程序的目标是将Salesforce.com组织与Java集成,并允许用户创建充当支持票证的对象的记录。 向用户呈现一个表格,其中必须填写一些字段来描述他的请求和联系信息,一旦表格经过验证,信息将发送到Salesforce组织并创建记录。 总之,应用程序用于在Salesforce组织中创建名为“Ticket_Soporte__c”类型的记录,但可以轻松地适应其他需求。

这是显示输入表单的JSP,它使用jquery mb Tooltips。输入在双方验证(客户端与JS和服务器与Spring验证使用情况),以确保数据的完整性,如果JS不可用或类似的东西。这种形式还允许文件上传到服务器,如果上传文件,则将在salesforce中创建附件,并将其作为相关列表下的“注释和附件”链接到票据记录。 使用正则表达式对邮件进行模糊验证。

tickets.jsp的时候,车票是在Salesforce成功地注册

<%@page contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> 
<%@ page session="false"%> 
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> 
<!DOCTYPE html> 
<html> 
    <head> 
     <META http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"> 

     <title>Support Ticket</title> 

     <script type="text/javascript" src="Tooltip/jquery.timers.js"></script> 
     <script type="text/javascript" src="Tooltip/jquery.dropshadow.js"></script> 

     <script type="text/javascript"> 
      $(function() 
      { 
       $("[title]").mbTooltip({ 
        opacity : .90, //opacity 
        wait:500, //before show 
        ancor:"mouse", //"parent" 
        cssClass:"default", // default = default 
        timePerWord:70, //time to show in milliseconds per word 
        hasArrow:false, 
        color:"white", 
        imgPath:"images/", 
        shadowColor:"black", 
        fade:500 
       }); 
      }) 


      function IsValidMail(email) 
      { 
       var formato = /^([\w-\.])[email protected]([\w-]+\.)+([a-z]){2,4}$/; 
       var comparacion = formato.test(email); 
       return comparacion; 
      } 


      function ValidateMail(f, x) 
      { 
       if(f.value != '') 
       { 
        if(!IsValidMail(f.value)) 
        { 
         showdiv(x); 
        } 
        else 
        { 
         hidediv(x); 
        } 
       } 
       else 
        hidediv(x); 

      } 


      function hidediv(x) 
      { 
       if (document.getElementById) 
       { // DOM3 = IE5, NS6 
        document.getElementById(x).style.visibility = 'hidden'; 
       } 
       else 
       { 
        if (document.layers) 
        { // Netscape 4 
         document.hideShow.visibility = 'hidden'; 
        } 
        else 
        { // IE 4 
         document.all.hideShow.style.visibility = 'hidden'; 
        } 
       } 
      } 


      function showdiv(x) 
      { 
       if (document.getElementById) 
       { // DOM3 = IE5, NS6 
        document.getElementById(x).style.visibility = 'visible'; 
       } 
       else 
       { 
        if (document.layers) 
        { // Netscape 4 
         document.hideShow.visibility = 'visible'; 
        } 
        else 
        { // IE 4 
         document.all.hideShow.style.visibility = 'visible'; 
        } 
       } 
      } 


      function ValidateRequiredFields(form) 
      { 
       fields = form.elements; 
       arrayLength = form.elements.length; 

       for(i=0;i<arrayLength;i++) 
       { 
        if (fields[i].value == '' && (fields[i].type=='text' || fields[i].type=='textarea')) 
        { 
         showdiv('hideShowError'); 
         showdiv('hideShowError2'); 
         return false; 
        } 
       } 

       return true; 
      }    
     </script> 


     <style type="text/css"> 
      h1 { 
       color: #3990bd; 

       font-size: 22px; 
       line-height: 22px; 
       font-family: Arial, Helvetica, sans-serif; 
       font-weight: normal; 

       text-decoration: none; 
       font-family: Arial, Helvetica, sans-serif; 
      } 

      .label {font-family:Arial, Helvetica, sans-serif ; font-size: 12px;color:#666; font-weight:bold} 
      .blue {font-family:Arial, Helvetica, sans-serif ; font-size: 12px;color: #3990bd} 
      .errorMsg {font-family:Arial, Helvetica, sans-serif; font-size: 12px; color:#F00; vertical-align: top;} 
      .errorblock {color: #000; background-color: #ffEEEE; border: 3px solid #ff0000; padding: 8px; margin: 16px;} 
     </style> 
    </head> 

    <body> 
     <form:form modelAttribute="supportTicket" name="frm" method="post" enctype="multipart/form-data" onsubmit="return ValidateRequiredFields(this)"> 
      <form:errors path="*" cssClass="errorblock" element="div" /> 

      <fieldset class="blue"> 
       <legend>Please provide the following information:</legend> 

       <div id="hideShowError" style="visibility:hidden" class="errorMsg"><strong>Error:</strong> Please fill all the required fields.</div>    

       <table width="640" border="0" cellpadding="5" cellspacing="5"> 
        <tr> 
         <td> 
          <form:label path="senderName" cssClass="label">First Name:</form:label> 
         <td> 
         <form:input path="senderName" cssClass="blue" size="50" title="Please type your First Name."/><span class="errorMsg">*</span> 
         </td> 
        </tr> 
        <tr> 
         <td></td> 
         <td> 
          <form:errors path="SenderName" cssClass="errorMsg" /> 
         </td> 
        </tr> 

        <tr></tr> 

        <tr> 
         <td> 
          <form:label path="senderLastName" cssClass="label">Last Name:</form:label> 
         </td> 
         <td> 
          <form:input type="text" id="senderLastName" path="senderLastName" cssClass="blue" size="50" title="Plaease type your Last Name."/><span style="color: red;">*</span> 
         </td> 
        </tr> 
        <tr> 
         <td></td> 
         <td> 
          <form:errors path="SenderLastName" cssClass="errorMsg" /> 
         </td> 
        </tr> 

        <tr></tr> 

        <tr> 
         <td> 
          <form:label path="contactMail" cssClass="label">Email:</form:label> 
         </td> 
         <td> 
          <form:input type="text" id="contactMail" path="contactMail" cssClass="blue" size="50" onblur="ValidateMail(this, 'hideShowMail');" title="Please type an email address in order to contact you."/><span style="color: red;">*</span> 
          <div id="hideShowMail" style="visibility:hidden" class="errorMsg"><font color="red"><strong>Error:</strong> Email is not valid.</font></div> 
         </td> 
        </tr> 
        <tr> 
         <td></td> 
         <td> 
          <form:errors path="ContactMail" cssClass="errorMsg" /> 
         </td> 
        </tr> 

        <tr></tr> 

        <tr> 
         <td> 
          <form:label path="customerName" cssClass="label">Company:</form:label> 
         </td> 
         <td> 
          <form:input type="text" id="customerName" path="customerName" cssClass="blue" size="50" title="Please type the name of your company"/><span style="color: red;">*</span> 
         </td> 
        </tr> 
        <tr> 
         <td></td> 
         <td> 
          <form:errors path="CustomerName" cssClass="errorMsg" /> 
         </td> 
        </tr> 

        <tr></tr> 

        <tr> 
         <td> 
          <form:label path="contactPhone" cssClass="label">Phone number:</form:label> 
         </td> 
         <td> 
          <form:input type="text" id="contactPhone" path="contactPhone" cssClass="blue" size="50" title="Please type your phone number."/><span style="color: red;">*</span> 
         </td> 
        </tr> 
        <tr> 
         <td></td> 
         <td> 
          <form:errors path="ContactPhone" cssClass="errorMsg" /> 
         </td> 
        </tr> 

        <tr></tr> 

        <tr> 
         <td> 
          <form:label path="supportType" cssClass="label">Support needed:</form:label> 
         </td> 
         <td> 
         <form:select path="supportType" cssClass="blue" title="Please select the type of the needed support."> 
           <form:option value="App error" label="App error" /> 
           <form:option value="New functionality" label="New functionality" /> 
           <form:option value="Unexpected behaviour" label="Unexpected behaviour" /> 
           <form:option value="Comment" label="Comment" /> 
          </form:select> 
         </td> 
        </tr> 

        <tr></tr> 

        <tr> 
         <td> 
          <form:label path="withContract" cssClass="label">Does your company have a support contract with us?:</form:label> 
         </td> 
         <td> 
          <form:select path="withContract" cssClass="blue" title="Please select yes or no."> 
           <form:option value="No" label="No" /> 
           <form:option value="Yes" label="Yes" /> 
          </form:select> 
         </td> 
        </tr> 

        <tr></tr> 

        <tr> 
         <td> 
          <form:label path="priority" cssClass="label">Priority:</form:label> 
         </td> 
         <td> 
          <form:select path="priority" cssClass="blue" title="Pleasy select the priority level of your requirement."> 
           <form:option value="Low" label="Low" /> 
           <form:option value="Medium" label="Medium" /> 
           <form:option value="High" label="High" /> 
          </form:select> 
         </td> 
        </tr> 

        <tr></tr> 

        <tr> 
         <td> 
          <form:label path="description" cssClass="label">Requirement description:</form:label> 
         </td> 
         <td> 
          <form:textarea id="description" path="description" cssClass="blue" rows="5" cols="52" title="Please describe your requirement."/><span style="color: red;">*</span> 
         </td> 
        </tr> 
        <tr> 
         <td></td> 
         <td> 
          <form:errors path="Description" cssClass="errorMsg" /> 
         </td> 
        </tr> 

        <tr></tr> 

        <tr> 
         <td> 
          <form:label path="attachment" cssClass="label">Attachment:</form:label> 
         </td> 
         <td> 
          <div class="blue">Max file size = 5 MB.</div> 
          <form:input path="attachment" type="file" cssClass="blue" title="You can attach a file if necessary."/> 
         </td> 
        </tr> 

        <tr></tr> 

        <tr> 
         <td>&nbsp;</td> 
         <td><div align="right"> 
           <input type="submit" class="blue" value="Submit Ticket"> 
          </div> 
         </td> 
        </tr> 
       </table> 

       <div id="hideShowError2" style="visibility:hidden" class="errorMsg"><strong>Error:</strong> Please fill all the required fields.</div>          
      </fieldset> 
     </form:form> 
    </body> 
</html> 

下一个JSP显示:

sucess.jsp

<%--<%@page contentType="text/html" pageEncoding="UTF-8"%>--%> 
<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<!DOCTYPE html> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <title>Thanks</title> 

     <style type="text/css"> 
      .blue {font-family:Arial, Helvetica, sans-serif ; font-size: 12px;color: #3990bd} 
     </style> 

    </head> 
    <body> 
     <fieldset class="blue"> 
      <legend>Your ticket has been registered successfully.</legend> 

      <br> 

      Dear: <b>${ticket.senderName}</b><br><br> 
      Your ticket has been raised and shortly we will contact you to follow up.<br><br> 

      <b>Contact info:</b>:<br> 
      Company: ${ticket.customerName}<br> 
      Email: ${ticket.contactMail}<br> 
      Phone: ${ticket.contactPhone}<br><br> 

      <b>Ticket info</b>:<br> 
      Númber: ${ticket.reportNumber}<br><br> 

      Thanks for contact us. 

      <br><br> 
     </fieldset> 
    </body> 
</html> 

而这一次当票证注册出现问题时显示:

error.jsp文件

<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<!DOCTYPE html> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <title>Error in ticket registration</title> 

     <style type="text/css"> 
      h1 { 
       color: #3990bd; 

       font-size: 22px; 
       line-height: 22px; 
       font-family: Arial, Helvetica, sans-serif; 
       font-weight: normal; 

       text-decoration: none; 
       font-family: Arial, Helvetica, sans-serif; 
      } 

      .blue {font-family:Arial, Helvetica, sans-serif ; font-size: 12px;color: #3990bd} 
     </style> 

    </head> 
    <body> 
     <fieldset class="blue"> 
      <legend>Your ticket has not been registered.</legend> 

      <h1 style="color: #F00">There was an error creating the Support Ticket.</h1><br> 

      <b>Please try again later.</b><br><br> 
     </fieldset> 
    </body> 
</html> 

我都以十个分量受到控制的源代码打包。

“config”包用于定义常量。我有一个名为Configuracion类,其中i宣布这些常量:

Configuracion.java

package config; 

/** 
* 
* @author JoseTlaseca 
*/ 
public class Configuracion 
{ 
    private static final String USERNAME = "[email protected]"; 
    private static final String PASSWORD = "salesforcePasswordAndToken"; 

    private static final String DIRECTORIO_DESTINO = "/home/josetla/tmp/"; 
    //this directory needs to be adapted to your needs. 


    public static String getPASSWORD() 
    { 
     return PASSWORD; 
    } 

    public static String getUSERNAME() 
    { 
     return USERNAME; 
    } 

    public static String getDIRECTORIO_DESTINO() { 
     return DIRECTORIO_DESTINO; 
    } 


} 

“控制器” 包包含两个类(SupportTicket和SupportTicketController)。

SupportTicket.java

package controller; 

import org.springframework.web.multipart.commons.CommonsMultipartFile; 

import java.io.File; 

/** 
* 
* @author JoseTlaseca 
*/ 
public class SupportTicket 
{ 
    private String reportNumber; 
    private String supportType; 
    private String withContract; 
    private String priority; 
    private String supportTicketID; 
    private String supportTicketName; 
    private String customerName; 
    private String senderName; 
    private String senderLastName; 
    private String contactMail; 
    private String contactPhone; 
    private String description; 
    private CommonsMultipartFile attachment; 
    private String attachmentID; 
    private String attachmentName; 
    private File uploadedFile; 

    public CommonsMultipartFile getAttachment() { 
     return attachment; 
    } 

    public void setAttachment(CommonsMultipartFile attachment) { 
     this.attachment = attachment; 
    } 

    public String getAttachmentID() { 
     return attachmentID; 
    } 

    public void setAttachmentID(String attachmentID) { 
     this.attachmentID = attachmentID; 
    } 

    public String getAttachmentName() { 
     return attachmentName; 
    } 

    public void setAttachmentName(String attachmentName) { 
     this.attachmentName = attachmentName; 
    } 

    public String getContactMail() { 
     return contactMail; 
    } 

    public void setContactMail(String contactMail) { 
     this.contactMail = contactMail; 
    } 

    public String getContactPhone() { 
     return contactPhone; 
    } 

    public void setContactPhone(String contactPhone) { 
     this.contactPhone = contactPhone; 
    } 

    public String getCustomerName() { 
     return customerName; 
    } 

    public void setCustomerName(String customerName) { 
     this.customerName = customerName; 
    } 

    public String getDescription() { 
     return description; 
    } 

    public void setDescription(String description) { 
     this.description = description; 
    } 

    public String getPriority() { 
     return priority; 
    } 

    public void setPriority(String priority) { 
     this.priority = priority; 
    } 

    public String getReportNumber() { 
     return reportNumber; 
    } 

    public void setReportNumber(String reportNumber) { 
     this.reportNumber = reportNumber; 
    } 

    public String getSenderLastName() { 
     return senderLastName; 
    } 

    public void setSenderLastName(String senderLastName) { 
     this.senderLastName = senderLastName; 
    } 

    public String getSenderName() { 
     return senderName; 
    } 

    public void setSenderName(String senderName) { 
     this.senderName = senderName; 
    } 

    public String getSupportTicketID() { 
     return supportTicketID; 
    } 

    public void setSupportTicketID(String supportTicketID) { 
     this.supportTicketID = supportTicketID; 
    } 

    public String getSupportTicketName() { 
     return supportTicketName; 
    } 

    public void setSupportTicketName(String supportTicketName) { 
     this.supportTicketName = supportTicketName; 
    } 

    public String getSupportType() { 
     return supportType; 
    } 

    public void setSupportType(String supportType) { 
     this.supportType = supportType; 
    } 

    public File getUploadedFile() { 
     return uploadedFile; 
    } 

    public void setUploadedFile(File uploadedFile) { 
     this.uploadedFile = uploadedFile; 
    } 

    public String getWithContract() { 
     return withContract; 
    } 

    public void setWithContract(String withContract) { 
     this.withContract = withContract; 
    } 

} 

SupportTicketController.java

package controller; 

import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.ui.ModelMap; 
import org.springframework.validation.BindingResult; 
import org.springframework.web.multipart.MultipartFile; 
import org.springframework.web.servlet.ModelAndView; 
import org.springframework.web.bind.annotation.ModelAttribute; 
import org.springframework.beans.factory.annotation.Autowired; 
import java.io.File; 

import config.Configuracion; 

import validator.SupportTicketValidator; 
import service.SupportTicketService; 


/** 
* 
* @author JoseTlaseca 
*/ 

@Controller 
@RequestMapping(value = "/tickets") 
public class SupportTicketController 
{ 

    private SupportTicketService service; 


    @Autowired 
    public void setSupportTicketService(SupportTicketService supportTicketService) 
    { 
     this.service = supportTicketService; 
    } 





    @RequestMapping(method = RequestMethod.GET) 
    public String getUploadForm(ModelMap model) 
    { 
     SupportTicket ticket = new SupportTicket(); 
     model.addAttribute(ticket); 

     return "/tickets"; 
    } 




    @RequestMapping(method = RequestMethod.POST) 
    public ModelAndView onSubmit(@ModelAttribute("supportTicket") SupportTicket ticket, BindingResult result) throws Exception 
    { 
     SupportTicketValidator validator = new SupportTicketValidator(); 

     validator.validate(ticket, result); 

     if (result.hasErrors()) 
     { 
      return new ModelAndView("/tickets","ticket",ticket); 
     } 


     if(!ticket.getAttachment().isEmpty()) 
     { 
      MultipartFile attachment = ticket.getAttachment(); 

      File destino = new File(Configuracion.getDIRECTORIO_DESTINO() + attachment.getOriginalFilename()); 

      attachment.transferTo(destino); 

      ticket.setUploadedFile(destino); 

      System.err.println("-------------------------------------------"); 
      System.err.println("Uploaded file: " + ticket.getUploadedFile().getName()); 
      System.err.println("-------------------------------------------"); 
     } 

     if(service.submitTicket(ticket)) 
     { 
      return new ModelAndView("/success","ticket",ticket); 
     } 
     else 
      return new ModelAndView("/error","ticket",ticket); 

    } 

} 
0

确认者必须注册为您的控制器:

<bean name="indexController" 
     class="org.springframework.web.servlet.mvc.ParameterizableViewController" 
     p:viewName="index" 
     p:validator-ref="supportTickedValidator" /> 

BTW:关于Spring 3.0

+0

嗨@Ralph。 感谢您的建议和答复。 当我添加** p:validator =“supportTickedValidator”**作为indexController bean的属性时,我得到: 'org.springframework.beans.NotWritablePropertyException:bean类的无效属性'validator'[org.springframework.web。 servlet.mvc.ParameterizableViewController]:Bean属性'validator'不可写,或者具有无效的setter方法。 setter的参数类型是否与getter的返回类型相匹配?' – JoseTlaseca

+0

对不起我的错:这是'p:validator-ref'而不是'p:validator' - 我更新了答案。 – Ralph

+0

嗨Ralph: 错误是一样的。 请注意,我已在Dispatcher-Servlet中添加了: ** ** 。 这与你所暗示的相同吗? – JoseTlaseca

0

部2的2


我也为我的服务代码创建了一个包。它有两个类,一个接口和它的实现。

SupportTicketService.java

package service; 

import controller.SupportTicket; 


/** 
* 
* @author JoseTlaseca 
*/ 
public interface SupportTicketService 
{ 
    public boolean submitTicket(SupportTicket supportTicket); 
} 

SupportTicketServiceImpl。java的

package service; 

//Salesforce org 
import com.sforce.soap.enterprise.Connector; 
import com.sforce.soap.enterprise.EnterpriseConnection; 
import com.sforce.soap.enterprise.Error; 
import com.sforce.soap.enterprise.QueryResult; 
import com.sforce.soap.enterprise.SaveResult; 
import com.sforce.ws.ConnectionException; 
import com.sforce.ws.ConnectorConfig; 
import com.sforce.soap.enterprise.sobject.Ticket_Soporte__c; 
import com.sforce.soap.enterprise.sobject.Attachment; 

//Utilities 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 

//Classes 
import controller.SupportTicket; 
import config.Configuracion; 




/** 
* 
* @author josetlaseca 
*/ 

public class SupportTicketServiceImpl implements SupportTicketService 
{ 
    static EnterpriseConnection connection; 
    ConnectorConfig config; 




    @Override 
    public boolean submitTicket(SupportTicket ticket) 
    { 
     connectToSalesforce(); 


     if(createSupportTicket(ticket)) 
     { 
      ticket.setReportNumber(queryReportNumber(ticket.getSupportTicketID())); 

      if(!ticket.getAttachment().isEmpty()) 
      { 
       //Validating the attachment size 
       if(ticket.getAttachment().getSize() <= 5000000) 
       { 
        createAttachment(ticket); 
       } 
       else 
        System.err.println("Attachment was not created: " + ticket.getUploadedFile() + " because is greater than 5 MB"); 
      } 

      return true; 
     } 
     else 
     { 
      System.err.println("Could not create your support ticket."); 
      return false; 
     } 

    } 




    public void connectToSalesforce() 
    { 
     config = new ConnectorConfig(); 
     config.setUsername(Configuracion.getUSERNAME()); 
     config.setPassword(Configuracion.getPASSWORD()); 
     config.setTraceMessage(true); 

     try 
     { 
      System.err.println("-------------------------------------------"); 
      System.err.println("Connecting to Salesforce..."); 
      System.err.println("-------------------------------------------"); 

      connection = Connector.newConnection(config); 

      // display some current settings 
      System.out.println("Auth EndPoint: "+config.getAuthEndpoint()); 
      System.out.println("Service EndPoint: "+config.getServiceEndpoint()); 
      System.out.println("Username: "+config.getUsername()); 
      System.out.println("SessionId: "+config.getSessionId()); 
     } 
     catch (ConnectionException e) 
     { 
      e.printStackTrace(); 
     }   
    } 







    public boolean createSupportTicket(SupportTicket ticket) 
    { 
     boolean success = false; 

     System.err.println("-------------------------------------------"); 
     System.err.println("Creating the support ticket..."); 
     System.err.println("-------------------------------------------"); 

     Ticket_Soporte__c[] records = new Ticket_Soporte__c[1]; 

     try 
     { 
      for (int i=0;i<1;i++) 
      { 
       Ticket_Soporte__c supportTicket = new Ticket_Soporte__c(); 

       supportTicket.setCompania__c(ticket.getCustomerName()); 
       supportTicket.setTipo_de_soporte__c(ticket.getSupportType()); 
       supportTicket.setCon_contrato__c(ticket.getWithContract()); 
       supportTicket.setNombre__c(ticket.getSenderName()); 
       supportTicket.setApellidos__c(ticket.getSenderLastName()); 
       supportTicket.setEmail__c(ticket.getContactMail()); 
       supportTicket.setTelefono__c(ticket.getContactPhone()); 
       supportTicket.setDescripcion__c(ticket.getDescription()); 
       supportTicket.setPrioridad__c(ticket.getPriority()); 


       records[i] = supportTicket; 
      } 

      // creating records in salesforce 
      SaveResult[] saveResults = connection.create(records); 

      // checking for errors 
      for (int i=0; i< saveResults.length; i++) 
      { 
       if (saveResults[i].isSuccess()) 
       { 
        ticket.setSupportTicketID(saveResults[i].getId()); 
        ticket.setSupportTicketName(records[i].getName()); 

        System.err.println("Ticket created successfully!!!"); 
        System.err.println("ID: " + ticket.getSupportTicketID()); 

        success = true; 
       } 
       else 
       { 
        Error[] errors = saveResults[i].getErrors(); 
        for (int j=0; j< errors.length; j++) 
        { 
         System.err.println("ERROR while creating ticket: " + errors[j].getMessage()); 
        } 

        success = false; 
       }  
      } 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 

     return success; 

    } 






    public void createAttachment(SupportTicket ticket) 
    { 
     System.err.println("-------------------------------------------"); 
     System.err.println("Creating attachment for the support ticket..."); 
     System.err.println("-------------------------------------------"); 

     Attachment attachmentRecords[] = new Attachment[1]; 

     try 
     { 
      InputStream inputStream = new FileInputStream(ticket.getUploadedFile()); 

      byte[] inbuff = new byte[(int)ticket.getUploadedFile().length()]; 
      inputStream.read(inbuff); 

      for (int i=0;i<1;i++) 
      { 
       Attachment att = new Attachment(); 

       att.setParentId(ticket.getSupportTicketID()); 
       att.setName(ticket.getAttachment().getOriginalFilename()); 
       att.setBody(inbuff); 

       attachmentRecords[i] = att; 
      } 

      // creating records in Salesforce.com 
      SaveResult[] saveAttachmentResults = connection.create(attachmentRecords); 

      // Checking for errors 
      for (int i=0; i< saveAttachmentResults.length; i++) 
      { 
       if (saveAttachmentResults[i].isSuccess()) 
       { 
        ticket.setAttachmentID(saveAttachmentResults[i].getId()); 
        ticket.setAttachmentName(attachmentRecords[i].getName()); 

        System.err.println("Attachment created successfully!!!"); 
        System.err.println("ID: " + ticket.getAttachmentID()); 
        System.err.println("Name: " + ticket.getAttachmentName()); 
       } 
       else 
       { 
        Error[] errors = saveAttachmentResults[i].getErrors(); 
        for (int j=0; j< errors.length; j++) 
        { 
         System.err.println("ERROR while creating the attachment: " + errors[j].getMessage()); 
        } 
       }  
      } 
     } 
     catch (FileNotFoundException fnf) 
     { 
      System.err.println("File not found: " +fnf.getMessage()); 
     } 
     catch (IOException io) 
     { 
      System.err.println("IO: " +io.getMessage()); 
     } 
     catch (ConnectionException ce) 
     { 
      System.err.println(ce.getMessage()); 
     } 
    } 






    public String queryReportNumber(String ticketID) 
    { 
     System.err.println("-------------------------------------------"); 
     System.err.println("Requesting ticket info..."); 
     System.err.println("-------------------------------------------"); 

     String rn = ""; 
     String query = ""; 

     try 
     { 
      query = "SELECT Id, Name FROM Ticket_Soporte__c WHERE Id = '" + ticketID + "'"; 
      //System.err.println("Query: " + query); 

      QueryResult queryResults = connection.query(query); 

      if (queryResults.getSize() > 0) 
      { 
       for (int i=0;i<queryResults.getRecords().length;i++) 
       { 
        Ticket_Soporte__c supportTicket = (Ticket_Soporte__c)queryResults.getRecords()[i]; 

        rn = supportTicket.getName(); 

        System.err.println("Ticket ID: " + supportTicket.getId() + " - Report number: " + rn); 
       } 
      } 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 

     return rn; 
    } 


} 

我还创建了一个验证器类:

SupportTicketValidator.java

package validator; 

import org.springframework.validation.Validator; 
import org.springframework.validation.ValidationUtils; 
import org.springframework.validation.Errors; 
import org.springframework.stereotype.Component; 

import controller.SupportTicket; 

/** 
* 
* @author josetlaseca 
*/ 
@Component 
public class SupportTicketValidator implements Validator 
{ 
    @Override 
    public boolean supports(Class clazz) 
    { 
     return SupportTicket.class.isAssignableFrom(clazz); 
    } 

    @Override 
    public void validate(Object target, Errors errors) 
    { 
     ValidationUtils.rejectIfEmptyOrWhitespace(errors, "SenderName", "SenderName.required"); 
     ValidationUtils.rejectIfEmptyOrWhitespace(errors, "SenderLastName", "SenderLastName.required"); 
     ValidationUtils.rejectIfEmptyOrWhitespace(errors, "ContactMail", "ContactMail.required"); 
     ValidationUtils.rejectIfEmptyOrWhitespace(errors, "CustomerName", "CustomerName.required"); 
     ValidationUtils.rejectIfEmptyOrWhitespace(errors, "ContactPhone", "ContactPhone.required"); 
     ValidationUtils.rejectIfEmptyOrWhitespace(errors, "Description", "Description.required"); 
    }  

} 

这是我的 “messages.properties” 文件。它是在WEB-INF文件夹(我用的Netbeans IDE):

SenderName.required = The name is required 
SenderLastName.required = The last name is required 
ContactMail.required = The email is required 
CustomerName.required = The company name is required 
ContactPhone.required = The phone is required 
Description.required = The requirement description is required 

这是我的ApplicationContext的文件:

的applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:p="http://www.springframework.org/schema/p" 
     xmlns:aop="http://www.springframework.org/schema/aop" 
     xmlns:tx="http://www.springframework.org/schema/tx" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> 

</beans> 

我的分发程序Servlet是命名为“spring-servlet”:

spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 

    <!-- Scans the classpath of this application for @Components to deploy as beans --> 
    <context:component-scan base-package="controller" /> 
    <context:component-scan base-package="validator" /> 


    <bean id="viewResolver" 
     class="org.springframework.web.servlet.view.UrlBasedViewResolver"> 
     <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> 
     <property name="prefix" value="/WEB-INF/jsp/" /> 
     <property name="suffix" value=".jsp" /> 
    </bean> 


    <bean id="supportTicketService" class="service.SupportTicketServiceImpl" /> 

    <bean id="messageSource" 
     class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> 
     <property name="basename" value="/WEB-INF/messages" /> 
    </bean>  

    <bean id="multipartResolver" 
     class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
    </bean> 

    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> 

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />  

</beans> 

最后,这是我的web.xml文件:

的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_2_5.xsd" 
    id="WebApp_ID" version="2.5"> 
    <display-name>Spring3MVC</display-name> 
    <welcome-file-list> 
     <welcome-file>redirect.jsp</welcome-file> 
    </welcome-file-list> 

    <servlet> 
     <servlet-name>spring</servlet-name> 
     <servlet-class> 
      org.springframework.web.servlet.DispatcherServlet 
     </servlet-class> 
     <load-on-startup>1</load-on-startup> 
    </servlet> 
    <servlet-mapping> 
     <servlet-name>spring</servlet-name> 
     <url-pattern>*.html</url-pattern> 
    </servlet-mapping> 
</web-app> 

注:

我已经使用名为“MB提示一个jQuery提示“在我的”tickets.jsp“页面中。 我已经将jar文件放在名为“Tooltip”的“Web Pages”文件夹下的文件夹中。

http://pupunzi.open-lab.com/2009/02/07/mbtooltip/ 

这是公报教程我已经使用到Java与Salesforce连接:

http://wiki.developerforce.com/page/Introduction_to_the_Force.com_Web_Services_Connector 

我已经使用Apache的百科全书文件上传罐子

http://commons.apache.org/fileupload/download_fileupload.cgi 

这是下议院IO罐子:

http://commons.apache.org/io/download_io.cgi 

(对不起,但我是新用户,我不能添加2个以上的链接。)

我希望这个完整的例子可以帮助有同样怀疑的人。