Skip to content

Using Servlets to Generate Pages

Matthew Green edited this page Sep 9, 2018 · 6 revisions

Servlets?

A Java class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers.

Servlets

  • Receive web (i.e., HTTP) requests
  • In the case of a web application, request contains data submitted from HTML forms
  • Process the request (logic, data model, database, other services)
  • Respond with an HTTP response
  • In the case of a web application, the response is HTML

NOTE: servlets are singletons Q: How does a web server handle multiple simultaneous requests? A: Threads Therefore: DO NOT store state (instance data) which should not be shared between requests

Request/response

HTTP Verbs

GET

Data can be sent on the same line as the URL

POST

  • Another way to request a response from the server
  • Data is sent as part of the request message itself

HTTP GET Example

https://www.google.com/search?source=hp&ei=Ii1uWvb0HMG10ASQz7eYBQ&q=html5+doctype&oq=&gs_l=psy-ab.3.0.35i39k1l6.12164.13002.0.17705.5.4.0.0.0.0.329.329.3-1.2.0..2..0...1.1.64.psy-ab..3.2.1564.6..0j0i20i264k1j0i131i67k1j0i67k1j0i131k1.1235.yvXebgTk2Qw

HTTP POST Example

POST / HTTP/1.1 Host: foo.com Content-Type: application/x-www-form-urlencoded Content-Length: 13

say=Hi&to=Mom

eb.xml and add servlet mapping

<servlet-mapping>
     
<servlet-name>FirstServlet</servlet-name>
  
<url-pattern>/first</url-pattern>

</servlet-mapping>

Implement doGet and doPost

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
   String html = "<html><body>Hi. I received param1=" +
 request.getParameter("param1") +
 " via POST</body><html>";

    
   response.getOutputStream().println(html);

}



protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
   String html = "<html><body>Hi. I received param1=" +
 request.getParameter("param1") +
 " via GET</body><html>";

    
   response.getOutputStream().println(html);

}

Extend the class: javax.servlet.http.HttpServlet;

package us.matt;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

Example

 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response) 
                throws ServletException, IOException {
     String user = request.getParameter("user");
     if(user == null) user = Servlet.DEFAULT_USER;
     response.setContentType("text/html");
     response.setCharacterEncoding("UTF-8");
     PrintWriter writer = response.getWriter();
     writer.append("<!DOCTYPE html>\r\n")
           .append("<html><head><title>Hello User</title></head>\r\n")
           .append("    <body>\r\n")
           .append("        Hello, ").append(user).append("!<br/><br/>\r\n")
           .append("        <form action=\"greeting\" method=\"POST\">\r\n")
           .append("            Enter your name:<br/>\r\n")
           .append("            <input type=\"text\" name=\"user\"/><br/>\r\n")
           .append("            <input type=\"submit\" value=\"Submit\"/>\r\n")
           .append("        </form>\r\n")
           .append("    </body></html>\r\n");
 }

public class Servlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        this.doGet(request, response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
             throws ServletException, IOException {
        PrintWriter writer = response.getWriter();
        writer.append("This is text!");
    }
    @Override
    public void init() throws ServletException
    {
        System.out.println("Servlet " + this.getServletName() + " has started.");
    }
    @Override
    public void destroy()
    {
        System.out.println("Servlet " + this.getServletName() + " has stopped.");
    }
}

Servlets – Init Parameters

@WebServlet(name = "Servlet",
   urlPatterns = {"/greeting", "/salutation","/wazzup"},
     initParameters = {
         @webInitParam(name = "user", value = "Bob")
         @webInitParam(name = "company", value = "Inc.")
     }
)

Servlets – Utilizing Request Arguments

Get Parameter
 String user = request.getParameter("user");
 if(user == null)
    user = Servlet.DEFAULT_USER;

Servlets

Class Declaration (What is a Servlet?)

public class SimpleServlet extends HttpServlet   

doGet vs. doPost

Request and Response Objects
protected void doGet(HttpServletRequest request, 
           HttpServletResponse response) throws   
           ServletException, IOException {

Response

HttpServletResponse

Referencing the HttpServletResponse Writer

PrintWriter out = response.getWriter(); 
String docType = "<!DOCTYPE html>\n";
out.println(docType + "<html>\n);  

Setting HttpServletResponse Content type

response.setContentType("text/html");

Request

HttpServletRequest request

http://site.com/simple?full_name=Bob&toppings=Olives&toppings=Anchovies&toppings=Mango

Accessing HttpServletRequest parameters

String fullName = request.getParameter("full_name");

Accessing multiple values from a parameter (Checkbox)

String[] paramValues = 
     request.getParameterValues("toppings");

List of HttpServletRequest parameter names

Enumeration paramNames = request.getParameterNames();

Dealing with unknown parameter names

List of HttpServletRequest parameter names
Enumeration paramNames = request.getParameterNames();

Working through the parameter name list

while(paramNames.hasMoreElements()) {
    String paramName = (String)paramNames.nextElement();

Clone this wiki locally