Lesson 09 - Servlet API (Web)

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 40

Lesson 9 – Servlet API (Web)

Lesson Goals
▷ Client-Server
▷ Static vs dynamic content
▷ Java HTTP Servlet
▷ Tomcat
▷ How to run Java Web app

2
Introduction to WEB

3
Transfer Protocols

4
HTTP – HyperText Transfer Protocol
▷ Uses Client-Sever architecture (aka Request-Response)
▷ HTTP resources aka URL(URI)
▷ HTTP Methods
▷ HTTP Headers
▷ HTTP Status Codes

5
Example of HTTP Request<->Response flow
▷ A person enters a URL string into the browser.
▷ The browser generates HTTP-request.
▷ The server receives a request, processes, and sends an
HTTP response.
▷ The browser receives a response and displays it.

6
Uniform Resource Locator

7
HTTP Methods
HTTP method Request has Body Response has Body Safe Idempotent Cacheable

GET Optional Yes Yes Yes Yes

HEAD Optional No Yes Yes Yes

POST Yes Yes No No Yes

PUT Yes Yes No Yes No

DELETE Optional Yes No Yes No

OPTIONS Optional Yes Yes Yes No

PATCH Yes Yes No No No

8
HTTP Headers
▷ Header Format: “Header-Name: header value text”

▷ Examples:
○ Host: some-website.com:8080
○ User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100
Safari/537.36
○ Accept: application/json; application/xml;
○ Authorization: Basic ZmFsa2VuOmpvc2h1YTU=

9
HTTP Status Codes
▷ Informational 1XX (indicates that the request was received and understood)
▷ Successful 2XX : (200 OK, 201 Created)
▷ Redirection 3XX (301 Moved Permanently)
▷ Client Error 4XX :
○ 400 Bad Request
○ 401 Unauthorized
○ 403 Forbidden
○ 404 Not Found
○ 405 Method Not Allowed
▷ Server Error 5XX (500 Internal Server Error, 503 Service Unavailable)
▷ More at List of HTTP status codes

10
HTTP Request-Response Example
GET https://google.com

HTTP/1.1 200 OK
Server: nginx
Date: Tue, 17 Dec 2019 18:33:15 GMT
Content-Type: text/html; charset=UTF-8
X-Powered-By: PHP/5.6.40
Last-Modified: Fri, 10 Apr 2023 10:26:17 GMT

<!DOCTYPE html>
<html lang="uk-UA">
<head>…</head>
<body>…</body>
</html>

11
Client-Server architecture

12
Client-Server architecture
• Web-server for static content: Nginx
• Application-server for dynamic content: Apache Tomcat

13
Java Web Server aka Servlet Container

14
Why Servlet Container

15
Java HTTP Servlet Example
@WebServlet(name = "helloServlet", urlPatterns = {"/hello"})
public class HelloServlet extends HttpServlet {
public void doGet(
HttpServletRequest request,
HttpServletResponse response
) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello World</h1>");
}
}

16
Java Http Servlet
Methods:
  - init(ServletConfig servletConfig)
  - service(HttpServletRequest req, HttpServletResponse resp)
  - destroy ()
- doGet, doPost and other HTTP methods

17
Java Servlet Lifecycle

18
HttpServletRequest
Container creates HttpServletRequest object and passes it as argument to
Servlet's service methods (doGet, doPost, etc.)

HttpServletRequest provides client request info to Servlet.

Passed to the service(...) method, doGet (...), doPost (...), do ... ().

19
HttpServletRequest
Methods:
  - getHeader (String)
  - getParameter (String)
  - getInputStream ()
  - getSession ()
  - getServletContext ()
- etc

20
HttpServletResponse
Container creates HttpServletResponse object and passes it to Servlet's
service methods (doGet, doPost, etc.)

HttpServletResponse assists a servlet in sending a response to the client.

As well as HttpServletRequest is passed in service(...) and do...(...)

21
HttpServletResponse
Methods:
  - addHeader (String, String)
  - setStatus (int)
  - sendError (int)
  - sendRedirect (String)
  - setHeader (String, String)
  - getWriter ()
  - etc

22
HttpSession and Cookies

23
HttpSession Methods
HttpSession session = request.getSession();
Main methods:
  - invalidate ()
  - getAttributeNames ()
  - getAttribute (String)
  - removeAttribute (String)
  - setAttribute (String, Object)
- etc

24
ServletContext
Servlet uses ServletContext to communicate with its servlet container,
access the servlet container.
ServletContext sc = request.getServletContext();
Main methods:
  - getAttributeNames ()
  - getAttribute (String)
  - removeAttribute (String)
  - setAttribute (String, Object)
- etc

25
Filter
@WebFilter(urlPatterns = {"/*"})
public class HelloFilter implements Filter {
public void init(FilterConfig cfg) {
}

public void doFilter(


ServletRequest req, ServletResponse resp, FilterChain chain
) throws ServletException, IOException {
chain.doFilter(req, resp);
}

public void destroy() {


}
}

26
Error Handling
@WebServlet("/error")
public class ErrorHandler extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html; charset=utf-8");
try (PrintWriter writer = resp.getWriter()) {
writer.write("<html><head><title>Error description</title></head><body>");
writer.write("<h2>Error description</h2>");
writer.write("<ul>");
List.of(
RequestDispatcher.ERROR_STATUS_CODE,
RequestDispatcher.ERROR_EXCEPTION_TYPE,
RequestDispatcher. ERROR_MESSAGE
).forEach(e -> writer.write("<li>" + e + ":" + req.getAttribute(e) + " </li>"));

writer.write("</ul>");
writer.write("</html></body>");
}
}
}
27
Error Handling
web.xml ->

<?xml version="1.0" encoding="UTF-8"?>


<web-app version="4.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">

<display-name>Web Project</display-name>

<error-page>
<exception-type>java.lang.RuntimeException</exception-type>
<location>/error</location>
</error-page>
</web-app>
28
WAR
Web application ARchive - is a JAR file used to distribute a collection
of Java Servlets, Java classes, XML files, libraries, static web pages
(HTML, JS, CSS, etc) and other resources…

29
Homework
▷ Create package edu.chnu.javaworweb.crypto.web - for storing classes related to
Web UI implementations
▷ Implement web version of Crypto Application using HTTP servlets
▷ Implement Login form for authentication of user(required only login field)
▷ Application should have 2 types of users:
○ “user” – regular application user with restricted access to endpoints
○ “admin” – administrator user which will have access to all endpoints
including CodingAudit functional and “delete” operations of CodingHistory
▷ In case of any error it should be logged and user redirected to custom error page
▷ Implement request logging filter. It will log endpoints path and total execution
time. Should measure all actions (even when request blocked).

30
Homework UI - Menu Page

31
Homework UI - Login Page

32
How to run Java Web App

▷ Download servlet container


`Apache Tomcat` (zip
archive)
▷ Extract downloaded data
somewhere
▷ Prepare run configuration

33
How to run Java Web App

▷ Choose folder with


extracted Tomcat files
▷ Run gradle build task
○ ./gradlew build

34
How to run Java Web App

▷ Fix the artifact for created


configuration

35
How to run Java Web App

▷ Fix the artifact for created


configuration

36
How to run Java Web App

▷ Fix the artifact for created


configuration

37
How to run Java Web App

▷ Run/Debug the application

38
Literature

○Servlets (by Baeldung)


○Servlets (by Tutorialspoint)
○How to Install Apache Tomcat
○What is servlet container
○Servlets (by Jetbrains)
○Introduction to Java Servlets
39
Thanks!
Any Questions?

40

You might also like