Recipe 7.6 Posting Data from a JSP


You want to send parameters and their values as an HTTP POST request from a JSP.


The easiest way to post data from a JSP is to do it the old fashioned way: use the HTML form tag and a Submit button. If you have to send the data dynamically (as in not relying on a user to press a form button), use a JavaBean that encapsulates the HttpClient code discussed in Recipe 7.5.


The simplest way to initiate a POST method in a JSP is to set up the HTML template text as shown in Example 7-1: provide an HTML form tag that the user fills out and submits. Since Example 7-1 already shows a typical HTML form, I'l use this space to show a JavaBean that allows a JSP to dynamically post data to another server-side process.

Example 7-10 shows a jspPost.jsp page that uses a PostBean utility class to send a set of parameters/values to another JSP. The receiving JSP, viewPost.jsp , processes the parameters that the PostBean object sends it, then returns some text for the JSP in Example 7-10 to display. The JSP passes the parameters that it wants to post as a java.util.Map to the PostBean class. The PostBean url property is the destination for the posted data (the address that you would otherwise place in the action attribute of a form HTML tag). The code:

 <jsp:setProperty name="postBean" property="parameters" value="<%= request. getParameterMap( )%>" /> 

gets a Map of the parameters that were passed to the jspPost.jsp page with the HttpServletRequest.getParameterMap( ) method, then passes that Map to the PostBean class to be reposted.

Example 7-10. A JSP that posts parameters and values dynamically
 <%@ taglib uri="" prefix="c" %> <%-- create an instance of the PostBean class if once does not exist --%>  <jsp:useBean id="postBean" class="com.jspservletcookbook.PostBean" />  <%-- set the PostBean parameters property to a Map type --%>  <jsp:setProperty name="postBean" property="parameters" value="<%= request. getParameterMap( )%>" /> <jsp:setProperty name="postBean" property="url" value="http://localhost:8080/home/ viewPost.jsp" />  <%-- Post the parameters and display the returned text --%>  <jsp:getProperty name="postBean" property="post"/>  

Example 7-11 shows the PostBean class that the JSP page uses to post data. This bean uses the Jakarta Commons HttpClient component to send an HTTP POST request. The sending action happens in the PostBean.getPost( ) method, which sends off the parameters and returns the text result from the receiving servlet (in this example, it's viewPost.jsp ). Because the bean method is called getPost( ) , using the JavaBean naming conventions for methods that return property values, we can call the method in the JSP with:

 <jsp:getProperty name="postBean" property="post"/> 

The latter code is then replaced with the String return value.

Example 7-11. A data-posting JavaBean for use by a JSP or servlet
 package com.jspservletcookbook;  import java.util.Map; import java.util.Iterator; import java.util.Map.Entry; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.HttpException; public class PostBean implements {  private Map parameters; private String url; public PostBean( ){ } public void setParameters(Map param){   if (param != null)       parameters = param; }  public Map getParameters( ){     return parameters; }      public void setUrl(String url){   if (url != null && !(url.equals("")))       this.url=url; }  public String getUrl( ){     return url; }    public String getPost( ) throws,HttpException{     if (url == null  url.equals("")  parameters == null)         throw new IllegalStateException(           "Invalid url or parameters in PostBean.getPost method.");     String returnData = "";  HttpClient httpClient = new HttpClient( );     PostMethod postMethod = new PostMethod(url);     //convert the Map passed into the bean to a NameValuePair[] type     NameValuePair[] postData = getParams(parameters);  //the 2.0 beta1 version has a    //PostMethod.setRequestBody(NameValuePair[])    //method, as addParameters is deprecated  postMethod.addParameters(postData);     httpClient.executeMethod(postMethod);     //A "200 OK" HTTP Status Code     if (postMethod.getStatusCode( ) == HttpStatus.SC_OK) {         returnData= postMethod.getResponseBodyAsString( );     } else {         returnData= "The POST action raised an error: " +             postMethod.getStatusLine( );     }     //release the connection used by the method     postMethod.releaseConnection( );     return returnData;  }//end getPost  private NameValuePair[] getParams(Map map){  NameValuePair[] pairs = new NameValuePair[map.size( )];           //Use an Iterator to put name/value pairs from the Map            //into the array           Iterator iter = map.entrySet( ).iterator( );           int i = 0;           while (iter.hasNext( )){                           Map.Entry me = (Map.Entry) );             //Map.Entry.getValue( ) returns a String[] array type             pairs[i] = new NameValuePair(                        (String)me.getKey( ),((String[]) me.getValue( ))[0]);             i++;           }           return pairs;  }//end getParams } 

The displayed results looks exactly like Figure 7-5, which also uses viewPost.jsp to show the name/value pairs that were fed to the JSP. Again, if you have to use a JSP to dynamically mimic an HTML form, it is a good idea to delegate the mechanics of posting data to a JavaBean so that the JSP remains a presentation component and the bean can be reused elsewhere.

Figure 7-5. Displaying parameters added from a forwarding JSP

See Also

Recipe 7.2 on handling a POST request in a JSP; Recipe 7.3 on setting the properties of a JavaBean to form input; Recipe 7.8 on using a JSP to add a parameter to a query string.

Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: