Skip to content

Using Servlets to Generate Pages

Matthew Green edited this page Aug 29, 2018 · 6 revisions

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

}

Clone this wiki locally