Creating a servlet

In this section, we will create a servlet to process an Ajax request. Select File | New | Other, and in New, select Web | Servlet, which is shown as follows. Then, click on Next.

Creating a servlet

The Create Servlet wizard gets started. Select Project as jboss-ajax, Source folder as srcmainjava, Java package as org.jboss.ajax.controller, Class name as AjaxFormServlet, and Superclass as javax.servlet.http.HttpServlet, as shown in the following screenshot. Then click on Next.

Creating a servlet

Specify URL mappings as AjaxFormServlet and click on Next, as shown in the following screenshot:

Creating a servlet

Select the doGet and doPost methods to create the servlet, as shown in the following screenshot. Once this is done, click on Finish.

Creating a servlet

AjaxFormServlet gets created and the servlet gets configured in web.xml, including a URL mapping to /AjaxFormServlet. We included /AjaxFormServlet in the URL to send an XMLHttpRequest request to invoke AjaxFormServlet. The web.xml file is listed as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="..." version="3.1">
  <display-name>jboss-ajax</display-name>
  <servlet>
    <description></description>
    <display-name>AjaxFormServlet</display-name>
    <servlet-name>AjaxFormServlet</servlet-name>
    <servlet-class>org.jboss.ajax.controller.AjaxFormServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>AjaxFormServlet</servlet-name>
    <url-pattern>/AjaxFormServlet</url-pattern>
  </servlet-mapping>
</web-app>

As the HTTP method is GET, the doGet() method of the servlet gets invoked. In the doGet method, retrieve the value of the catalogId parameter, as shown in the following line of code:

String catalogId = request.getParameter("catalogId");

Apply the business logic on the catalogId value to validate the value. We have used the business logic that the value must be unique to be valid, which implies the same value must not already be in the database. Create a DataSource object using a JNDI lookup with an InitialContext object on the java:jboss/datasources/MySQLDS data source.

Create a Connection object from the DataSource object using the getConnection() method. Using the CatalogId value specified in the input form, create a SQL query to retrieve the data from the database. Create a PreparedStatement object from the Connection object using the prepareStatement(String) method. Run the SQL query using the executeQuery() method to obtain a ResultSet object. If the ResultSet object is empty, it implies that the CatalogId field value is not defined in the Catalog database table; the CatalogId field value is valid. If the ResultSet object contains data, it implies that the CatalogId value already exists in the database; the CatalogId field value is not valid.

Next, construct an XML string to return to the server. If CatalogId is not valid, construct an XML string that includes the different field values for the catalog entry as XML elements. The XML string is required to have a root element, catalog, for example. Include a <valid> </valid> element that specifies the validity of the CatalogId field value with a boolean value. If the CatalogId value is valid, add only the <valid> </valid> element to the XML string, as shown in the following code snippet (the variable rs represents ResultSet):

if (rs.next()) {
  out.println("<catalog>" + "<valid>false</valid>" + "<journal>" +
  rs.getString(2) + "</journal>" + "<publisher>" +
  rs.getString(3) + "</publisher>" + "<edition>" +
  rs.getString(4) + "</edition>" + "<title>" +
  rs.getString(5) + "</title>" + "<author>" +
  rs.getString(6) + "</author>" + "</catalog>");
} else {
  out.println("<valid>true</valid>");
}

Set the content type of HttpServletResponse to text/xml because the response to an Ajax request is in the XML format, and set the Cache-Control header to no-cache to prevent JSPs and servlets from being cached. As the Ajax response is updated with each request, caching must be disabled to prevent a cached response from being reserved, as follows:

response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");

If the CatalogId field value does not exist in the database, the input form with field values for a new catalog entry can be submitted using the POST method. In the doPost method in the servlet, create a JDBC connection to the MySQL database as in the doGet method, and add a catalog entry with an INSERT SQL statement.

The FormServlet.java Ajax is listed as follows:

package org.jboss.ajax.controller;

import java.io.*;
import java.sql.*;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

public class AjaxFormServlet extends HttpServlet {

The doGet method is invoked with an asynchronous request sent using the HTTP GET method. Run a SQL query using Catalog Id, which is specified in the input form to generate a result set. Set headers for the HttpServletResponse object, and create a PrintWriter object from the HttpServletResponse object. Construct an output as an XML response, as shown in the following code:

public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    try {
      // Obtain value of Catalog Id field to be validated.
      String catalogId = request.getParameter("catalogId");
      
      // Obtain Connection
      InitialContext initialContext = new InitialContext();
      DataSource ds = (DataSource)initialContext.lookup("java:jboss/datasources/MySQLDS");
      java.sql.Connection conn = ds.getConnection();
      
      // Obtain result set
      PreparedStatement pstmt = conn.prepareStatement("SELECT * from CATALOG WHERE CatalogId = ?");
      pstmt.setString(1, catalogId);
      
      ResultSet rs = pstmt.executeQuery();
      
      // set headers before accessing the Writer
      response.setContentType("text/xml");
      response.setHeader("Cache-Control", "no-cache");
      
      PrintWriter out = response.getWriter();
      
      // then send the response
      // If result set is empty set valid element to true
      if (rs.next()) {
        out.println("<catalog>" + "<valid>false</valid>" + "<journal>"
        + rs.getString(2) + "</journal>" + "<publisher>"
        + rs.getString(3) + "</publisher>" + "<edition>"
        + rs.getString(4) + "</edition>" + "<title>"
        + rs.getString(5) + "</title>" + "<author>"
        + rs.getString(6) + "</author>" + "</catalog>");
      } else {
        out.println("<valid>true</valid>");
      }
      
      rs.close();
      stmt.close();
      conn.close();
      
    } catch (javax.naming.NamingException e) {System.err.println(e.getMessage());
    } catch (SQLException e) {System.err.println(e.getMessage());
    }
  }

The doPost() method is used to create a new catalog entry. Create an InitialContext object. With a JNDI lookup, create a DataSource object. Obtain a Connection object from the DataSource object using the getConnection() method. Create a Statement object using the createStatement() method of the Connection class. PreparedStatement can be used instead of Statement. Create a SQL string from values retrieved from the input form. Run the SQL statement using the execute() method. If the SQL statement runs without error, redirect the response to catalogentrycreated.jsp. If an error is generated, redirect the response to error.jsp, as shown in the following code:

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    try {
      // Obtain Connection
      InitialContext initialContext = new InitialContext();
      DataSource ds = (DataSource) initialContext.lookup("java:jboss/datasources/MySQLDS");
      java.sql.Connection conn = ds.getConnection();
      
      String catalogId = request.getParameter("catalogId");
      String journal = request.getParameter("journal");
      String publisher = request.getParameter("publisher");
      String edition = request.getParameter("edition");
      String title = request.getParameter("title");
      String author = request.getParameter("author");
      
      Statement stmt = conn.createStatement();
      String sql = "INSERT INTO Catalog VALUES(" + "'" + catalogId
      + "'" + "," + "'" + journal + "'" + "," + "'"
      + publisher + "'" + "," + "'" + edition + "'" + ","
      + "'" + title + "'" + "," + "'" + author + "'" + ")";
      
      stmt.execute(sql);
      
      response.sendRedirect("catalogentrycreated.jsp");
      
      stmt.close();
      conn.close();
      
    } catch (javax.naming.NamingException e) {
      response.sendRedirect("error.jsp");
    } catch (SQLException e) {
      response.sendRedirect("error.jsp");
    }
  }
}

The AjaxFormServlet class is shown in Package Explorer in the following screenshot. The errors shown in the listing will be removed in the next section once the dependencies are satisfied through Maven.

Creating a servlet
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset