Tuesday, January 29, 2013

Connecting to servlet from Java client

Code as below. Hope it is easily understandable

Servlet Code:
public class MyServlet extends HttpServlet 
{
 public void init(ServletConfig config)
 {
  //Servlet Init code here
 }
 
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyServlet() {
        super();
        // TODO Auto-generated constructor stub
        
    }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception
 {
  ObjectInputStream resultStream = null;
  String results = null;
  System.out.println("Got Data......");
  resultStream = new ObjectInputStream(request.getInputStream());
  System.out.println("Got Result Stream......");
  results = resultStream.readObject();
  resultStream.close();
  sendResponse(response, results);
 }

 public void sendResponse(HttpServletResponse response, String results) throws IOException 
 {
  ObjectOutputStream sendStream = null;
  sendStream = new ObjectOutputStream(response.getOutputStream());
  sendStream.writeObject(results);
  sendStream.flush();
  sendStream.close();
 }
}

Client Code:

public class MyClient 
{
 public String callServlet(String dataToSend)
 {
  String responseData = "";
  try 
  {
   URL serverURL = new URL("http://localhost:8080/MyServlet");
   URLConnection serverConnection = serverURL.openConnection();
   serverConnection.setDoInput(true);
   serverConnection.setDoOutput(true);
   serverConnection.setUseCaches(false);
   serverConnection.setDefaultUseCaches(false);
   serverConnection.setRequestProperty("Content-Type", "text/plain");
   
   ObjectOutputStream out = new ObjectOutputStream(serverConnection.getOutputStream());
   out.writeObject(Compressor.compress(dataToSend));
   out.flush();
   out.close();
   ObjectInputStream in = new ObjectInputStream(serverConnection.getInputStream());
   responseData = (String) in.readObject();
   System.out.println("Records received...");
  } 
  catch (MalformedURLException e) 
  {
   e.printStackTrace();
  } 
  catch (IOException e) 
  {
   e.printStackTrace();
  } 
  catch (ClassNotFoundException e) 
  {
   e.printStackTrace();
  }
  return responseData;
 }
}

No comments :