开发者

Spring Validation

I have a java web application project with Spring framework in netbeans and I'm trying to use Spring validation.

What my application does is raise a support ticket.

I have read several tutorials and I've gotten the form is not sent until the fields are filled. The problem is that I can not get to show error messages which I defined in the class "Validator".

That is, if required fields are not filled the form is not sent, but the error message does not appear anywhere.

Can someone tell me what I'm doing wrong?

These are my codes:

SupportTicket Class:

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 class:

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 Class:

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;
    }

}

Dispatcher-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>
        开发者_如何学C                <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>

As I mentioned, the validation works (I think) because the form is not submited until i fill the required fields, but the error messages are not shown with that < form:errors > tags.

Can you give me an advice to solve my problem?



PART 1 OF 2


I have moved my app to Spring 3 style and i have been reading a lot about this new style.

Now my app looks a bit different.

The objective of the application is to integrate a Salesforce.com org with Java and allow users to create records of an object that acts as a support ticket. The user is presented with a form in which it must fill some fields to describe his request and contact information, once the form is validated, the information is sent to the Salesforce org and the record is created. In summary, the application is used to create records of a type called "Ticket_Soporte__c" in a Salesforce org, but can be easily adapted to other needs.

This is the JSP that shows the input form, it uses jquery mb Tooltips. The input is validated in both sides (client with JS and server with Spring validation utils) to ensure the data integrity if JS is not available or something like that. This form also allows file upload to a server, if a file is uploaded then an attachment will be created in salesforce and it will be linked to the ticket record as a "Note and Attachment" under a related list. The mail is validated on blur using regular expressions.

tickets.jsp

<%@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-\.])+@([\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>

The next JSP is shown when the ticket is registered succesfully in Salesforce:

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>

And this one is shown when something goes wrong in ticket registration:

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>

I have created packages in order to mantain sources under control.

"config" package is used to define constants. I have a class named Configuracion where i declare those constants:

Configuracion.java

package config;

/**
 *
 * @author JoseTlaseca
 */
public class Configuracion
{
    private static final String USERNAME = "user@domain.com";
    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;
    }


}

the "controller" package contains two classes (SupportTicket and 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);

    }

}


The Validator must be registered for your Controller:

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

BTW: Pay Attention to my comment about Spring 3.0



PART 2 OF 2


I have also created a package for my service code. It has two classes, an interface and its implementation.

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;
    }


}

I also have created a validator class:

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");
    }    

}

And this is my "messages.properties" file. It is under WEB-INF folder (I am using 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

This is my ApplicationContext file:

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>

And my dispatcher servlet that is named "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>

And finally, this is my web.xml file:

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>

NOTES:

I have used a jquery tooltip named "mb tooltip" in my "tickets.jsp" page. I have placed jar files in a folder named "Tooltip" under "Web Pages" folder.

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

This is the oficial tutorial i have used to connect Java with Salesforce:

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

I have used Apache commons file upload jar

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

And this is the Commons IO jar:

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

(Sorry, but i am a new user and i cant add more than 2 links.)

I hope this full example helps someone who has the same doubts I had.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜