2.83M
Категория: ПрограммированиеПрограммирование

Java EE, Servlets

1.

Java EE
Servlets
IT Academy

2.

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

3.

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.

4.

Web Module Structure
In the Java EE architecture, a Web
Module is the smallest deployable and
usable unit of web resources.

5.

Web Module Structure
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 with JAR files that contain enterprise beans, and JAR archives of libraries called by serverside classes
• deployment descriptors, such as web.xml (the web application deployment descriptor)

6.

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.

7.

Java EE typical Application Layer
Java Enterprise applications typically
use a next Layered Architecture:

8.

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.

9.

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.
• A Java servlet processes a Java class
in Java EE that conforms to the Java
Servlet API, a standard for
implementing Java classes that
respond to requests.

10.

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)

11.

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”.

12.

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.

13.

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/

14.

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

15.

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.

16.

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

17.

Defining Custom URLs
Don't edit this manually. Should
match version supported by your
server. If your server supports 3.0,
can omit web.xml totally and use
annotations
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
... >
<!-- 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>
</servlet>
Any arbitrary name. But must be the same both times
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/test2</url-pattern>
</servlet
</web-app>
The part of the URL that comes after the app (project)
name. Should start with a slash

18.

Defining Custom URLs
• Project details:
• Name of project is “test-app”
• Servlet is in src/testPackage/TestServlet.java

19.

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.

20.

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

21.

Creating Form Data: HTML Forms
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
You normally use a relative URL for the ACTION. This
<TITLE>A Sample Form Using GET</TITLE>
URL is just for testing because I am running a test server
</HEAD>
on port 8088 that echoes the data it receives.
<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>
</FORM>
</BODY>
</HTML>

22.

GET Form
• Initial Result
• Submission Result

23.

Sending POST Data
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
The default method is GET. So, if a form says
<HEAD>
METHOD="GET" or it has no METHOD at all, GET is used.
<TITLE>A Sample Form Using GET</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H2 ALIGN="CENTER">A Sample Form Using GET</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"> <!-- Press this to submit form -->
</CENTER>
</FORM>
</BODY>
</HTML>

24.

POST Form
• Initial Result
• Submission Result

25.

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

26.

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

27.

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

28.

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

29.

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

30.

Difference between Forward and Redirect
• There are many differences between the forward() method and sendRedirect() method.
forward() method
The forward() method works at server side.
sendRedirect() method
The sendRedirect() method works at client
side.
It sends the same request and response objects to
It always sends a new request.
another servlet.
It can work within the server only.
It can be used within and outside the server.

31.

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.

32.

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

33.

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>

34.

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

35.

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>

36.

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

37.

Practical task
1.
Create maven web application (maven-archetype-webapp)
2.
Add tomcat7-maven-plugin plugin to pom.xml file
3.
Create model Book with author, title and totalPageNumbers fields
4.
Create repository which contains list with registered books and methods for access and manage of these books
5.
Create controllers for displaying all books, editing, deleting any existing book and registering new book
6.
Create jsp-pages in WEB-INF/pages folder
7.
Run project on the server (mvn tomcat7:run) and test it

38.

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
English     Русский Правила