Java EE,
Servlets
IT Academy
Agenda
• Java EE Architecture
• A Servlet’s Job
• Tomcat 7 and Servlet 3.0
• Custom URLs in web.xml (Servlets 2.5)
• The Servlet Life Cycle
• Creating Form Data: HTML Forms
• GET Form
• POST Form
• Reading Form Data In Servlets
• Forward and Redirect
• Servlet Filters
• Exception Handling
Java EE Multi-tier Applications
• The Java EE platform uses a distributed multitiered application
model for enterprise applications.
• Client-tier components run on the client machine.
• Web-tier components run on the Java EE server.
• Business-tier components run on the Java EE server.
• Enterprise information system (EIS)-tier software runs on the EIS server.
Web Module Structure
• In the Java EE architecture, a Web Module is the smallest deployable
and usable unit of web resources.
• The document root contains a subdirectory named WEB-INF, which can
contain the following files and directories:
• classes, a directory that contains server-
side classes: servlets, enterprise bean
class files, utility classes, and JavaBeans
components
• lib, a directory that contains JAR files that
contain enterprise beans, and JAR
archives of libraries called by server-side
classes
• deployment descriptors, such as
web.xml (the web application
deployment descriptor)
Java EE Web Application Request
Handling
• In the Java EE platform, Web Components provide the dynamic
extension capabilities for a web server. Web components can be:
• Java servlets,
• Web Pages implemented with JavaServer Faces technology,
• JSP pages.
Java EE typical Application Layer
• Java Enterprise applications typically use a next Layered Architecture:
Java EE MVC Template
• The Model can be some DAO layer or some Service layers which give
some information about request or requested information or Model can
be a POJO which encapsulates the application data given by the
Controller.
• The View is responsible for rendering the Model data and in general it
generates HTML output that the client's browser can interpret.
• The Controller is responsible for
processing user requests and
building appropriate Model and
passes it to the view for rendering.
Supports RESTful URLs.
Java Servlet
• A Java Servlet is a java software Component that extends the
capabilities of a Server.
• Although servlets can respond to many
types of requests, they most commonly
implement web containers for hosting
web applications on web servers and
thus qualify as a server-side servlet
web API.
• A Java servlet processes a Java class
in Java EE that conforms to the Java
Servlet API,[1] a standard for
implementing Java classes that
respond to requests.
A Servlet’s Job
• Read the explicit data sent by client (form data)
• Read the implicit data sent by client (request headers)
• Generate the results
• Send the explicit data back to client (HTML)
• Send the implicit data to client (status codes and response headers)
A Servlet That Generates Plain Text
import java.io.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet("/hello")
public class HelloWorld extends HttpServlet {
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
URL assumes you have deployed
from a project named “test-app”.
Interpreting HelloWorld Servlet
• @WebServlet("/address")
This is the URL relative to the app name. More later.
• doGet(...)
Code for an HTTP GET request. doPost(...) also common.
• HttpServletRequest
Contains anything that comes from the browser.
• HttpServletResponse
Used to send stuff to the browser. Most common is getWriter() for a
PrintWriter that points at browser.
• PrintWriter
Prints formatted representations of objects to a text-output stream.
A Servlet That Generates HTML
• Tell the browser that you’re sending it HTML
• response.setContentType("text/html");
• Modify the println statements to build a legal Web page
• Print statements should output HTML tags
• Check your HTML with a formal syntax validator
• http://validator.w3.org/
• http://www.htmlhelp.com/tools/validator/
A Servlet That Generates HTML
@WebServlet("/test1")
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>\n" + "<html>\n" +
"<head><title>A Test Servlet</title></head>\n" +
"<body bgcolor=\"#fdf5e6\">\n" +
"<h1>Test</h1>\n" +
"<p>Simple servlet for testing.</p>\n" +
"</body></html>");
}
}
Tomcat 7, 8 and Servlet 3.0
• Give address with @WebServlet
@WebServlet("/my-address")
public class MyServlet extends HttpServlet {…}
• Resulting URL
http://hostName/appName/my-address
• Omit web.xml entirely
• You are permitted to use web.xml even when using @WebServlet, but the
entire file is completely optional.
Defining Custom URLs in web.xml (Servlets
2.5)
• Java code
public class MyServlet extends HttpServlet {...}
• web.xml entry (in <web-app...>...</web-app>)
• Give name to servlet
<servlet>
<servlet-name>appName</servlet-name>
<servlet-class>myPackage.MyServlet</servlet-
class>
</servlet>
• Give address (URL mapping) to servlet
<servlet-mapping>
<servlet-name>appName</servlet-name>
<url-pattern>/my-address</url-pattern>
</servlet-mapping>
• Resultant URL: http://hostname/my-address
Defining Custom URLs
Don't edit this manually. Should
match version supported by your
<?xml version="1.0" encoding="UTF-8"?>server. If your server supports 3.0,
<web-app version="3.0" can omit web.xml totally and use
annotations.
... >
<!-- Use the URL http://hostName/appName/test2
for testPackage.TestServlet -->
<servlet> Fully qualified classname.
<servlet-name>Test</servlet-name>
<servlet-class>testPackage.TestServlet</
servlet-class>
Any arbitrary name. But must be the same both times.
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/test2</url-pattern>
</servlet The part of the URL that comes after the app (project)
</web-app> name. Should start with a slash.
Defining Custom URLs
• Project details:
• Name of project is “test-app”
• Servlet is in src/testPackage/TestServlet.java
The Servlet Life Cycle
• init()
• Executed once when the servlet is first loaded.
• Not called for each request.
• service()
• Called in a new thread by server for each request.
• Dispatches to doGet(), doPost(), etc.
• Do not override this method!
• doGet(), doPost()
• Handles GET, POST, etc. requests.
• Override these to provide desired behavior.
• destroy()
• Called when server deletes servlet instance.
• Not called after each request.
Why You Should Not Override service?
• The service method does other things besides just calling doGet
• You can add support for other services later by adding doPut, doDelete, etc.
• You can add support for modification dates by adding a getLastModified()
method (when the client app makes request to your servlet with "If-
Modified-Since" request-header)
• The service method gives you automatic support for:
• HEAD requests
• OPTIONS requests
• TRACE requests
Creating Form Data: HTML Forms
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<HTML>
You normally use a relative URL for the ACTION. This URL
<HEAD>
is just for testing because I am running a test server on
<TITLE>A Sample Form Using GET</TITLE>
port 8088 that echoes the data it receives.
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H2 ALIGN="CENTER">A Sample Form Using GET</H2>
<FORM ACTION="http://localhost:8080/SomeProgram">
<CENTER>
First name:
<INPUT TYPE="TEXT" NAME="firstName" VALUE="J.
Random"><BR>
Last name:
<INPUT TYPE="TEXT" NAME="lastName"
VALUE="Hacker"><P>
<INPUT TYPE="SUBMIT"> <!-- Press this to submit
form -->
</CENTER>
GET Form
• Initial Result
• Submission Result
Sending POST Data
<!DOCTYPE ... > The default method is GET. So, if a form says
<HTML> METHOD="GET" or it has no METHOD at all, GET is used.
<HEAD>
<TITLE>A Sample Form Using POST</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H2 ALIGN="CENTER">A Sample Form Using POST</H2>
<FORM ACTION="http://localhost:8080/SomeProgram"
METHOD="POST">
<CENTER>
First name:
<INPUT TYPE="TEXT" NAME="firstName" VALUE="J.
Random"><BR>
Last name:
<INPUT TYPE="TEXT" NAME="lastName" VALUE="Hacker"><P>
<INPUT TYPE="SUBMIT">
</CENTER>
</FORM>
</BODY></HTML>
POST Form
• Initial Result
• Submission Result
GET Request vs. POST Request
• Advantages of POST
• URL is simpler
• Data is hidden from people looking over your shoulder
• Larger amounts of data can be sent
• Can send special characters (e.g., in uploaded files)
• Browsers will not cache results
• Should always be used if the requests changes data on server (REST)
• Advantages of GET
• Data transfer using the GET method is faster
• Browsers can cache results
• Easier to test interactively
Reading Form Data In Servlets
• request.getParameter("name")
• Returns URL-decoded value of first occurrence of name in query string
• Works identically for GET and POST requests
• Returns null if no such parameter is in query data
• request.getParameterValues("name")
• Returns an array of the URL-decoded values of all occurrences of name in
query string
• Returns a one-element array if param not repeated
• Returns null if no such parameter is in query
• request.getParameterNames() or request.getParameterMap()
• Returns Enumeration or Map of request params
• Usually reserved for debugging
Reading Form Data In Servlets
@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws javax.servlet.ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws javax.servlet.ServletException, IOException {
PrintWriter out = response.getWriter();
Map<String, String[]> requestParams = request.getParameterMap();
for (Map.Entry<String, String[]> param : requestParams.entrySet()) {
out.println(param.getKey() + " => " + Arrays.toString(param.getValue()));
}
}
}
Forwards a Request to another
Resource
• forward(ServletRequest request, ServletResponse response)
• forwards a request from a servlet to another resource (servlet, JSP file, or
HTML file) on the server
RequestDispatcher rd = request.getRequestDispatcher("hello.jsp");
request.setAttribute("value", "Hello");
rd.forward(request, response);
Redirect from Servlet to another
Resource
• sendRedirect(String URL) throws IOException
• redirect response to another resource, it may be servlet, jsp or html file
String name = request.getParameter("value");
response.sendRedirect("https://www.google.com/search?q=" + value);
Difference between Forward and
Redirect
• There are many differences between the forward() method and
sendRedirect() method.
forward() method sendRedirect() method
The forward() method works at The sendRedirect() method
server side. works at client side.
It sends the same request and
response objects to another It always sends a new request.
servlet.
It can work within the server only. It can be used within and outside
the server.
Servlet Filters
• Servlet Filters are Java classes that can be used in Servlet Programming
for the following purposes:
• To intercept requests from a client before they access a resource at back
end.
• To manipulate responses from server before they are sent back to the
client.
• The Web application may define several different filters with a specific
purpose.
• The order of filter-mapping elements in web.xml determines the
order in which the web container applies the filter to the servlet.
Servlet Filters
@WebFilter(value = "/*")
public class MainFilter implements Filter {
private ServletContext context;
public void init(FilterConfig config) {
context = config.getServletContext();
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws ServletException, IOException {
context.setAttribute("time", new Date());
HttpServletResponse httpResponse = ((HttpServletResponse)resp);
httpResponse.setContentType("text/html");
chain.doFilter(req, resp);
}
}
Filter Configuration in web.xml
• Filters also can be configure in descriptor file web.xml and then map to
either servlet names or URL patterns in your application's deployment
descriptor.
<filter>
<filter-name>MainFilter</filter-name>
<filter-class>com.softserve.academy.MainFilter</filter-class>
<init-param>
<param-name>content-type</param-name>
<param-value>text/html</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MainFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Filter Configuration in web.xml
public class MainFilter implements Filter {
private ServletContext context;
private String contentType;
public void init(FilterConfig config) {
context = config.getServletContext();
contentType = config.getInitParameter("content-type");
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws ServletException, IOException {
context.setAttribute("time", new Date());
HttpServletResponse httpResponse = ((HttpServletResponse)resp);
httpResponse.setContentType(contentType);
chain.doFilter(req, resp);
}
}
Exception Handling
• When a servlet throws an exception, the web container searches the
configurations in web.xml that use the exception-type element for a
match with the thrown exception type.
<error-page>
<error-code>404</error-code>
<location>/error</location>
</error-page>
<error-page>
<exception-type>java.io.IOException</exception-type>
<location>/error</location>
</error-page>
Exception Handling
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
String servletName = (String) request.getAttribute("javax.servlet.error.servlet_name");
Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");
PrintWriter writer = response.getWriter();
if (throwable == null && statusCode == null) {
writer.println("Error Information Is Missing");
} else if (statusCode != 500) {
writer.println("Error Details:");
writer.println("\tStatus Code: " + statusCode);
writer.println("\tRequested URI: " + requestUri);
} else {
writer.println("Exception Details:");
writer.println("\tServlet Name: " + servletName);
writer.println("\tException Name: " + throwable.getClass().getName());
writer.println("\tRequested URI: " + requestUri);
writer.println("\tException Message: " + throwable.getMessage());
}
writer.close();
Useful Links
1. https://www.javatpoint.com/servlet-tutorial
2. https://www.javatpoint.com/jsp-tutorial
3. https://beginnersbook.com/2013/05/servlet-tutorial/
4. https://www.studytonight.com/servlet/
5. https://www.ntu.edu.sg/home/ehchua/programming/java/JavaServlets.html
Thanks for
attention!
IT Academy