0% found this document useful (0 votes)
14 views14 pages

L03 - Servlet

Uploaded by

leanhtuan280704
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views14 pages

L03 - Servlet

Uploaded by

leanhtuan280704
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

10/9/2019

Servlet

JSP/SERVLET

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

1 2

Servlet Servlet
̵ Java Servlets are programs that run on a Web ̵ Easy to create content
or Application server and act as a middle ̵ Easy to build big application
layer between a request coming from a Web
browser or other HTTP client and databases or ̵ Easy to upgrade
applications on the HTTP server. ̵ Easy to use (client)
̵ Run in server tier.
̵ Managed by the Web container

3 4

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

3 4
10/9/2019

Servlet Life circle


HTTP REQUEST

SERVLET
ENGINE

HTML
CONTENT

HTTP RESPONSE

5 6

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

5 6

Servlet Servlet
̵ The lifecycle of a servlet is controlled by the ̵ The container invokes the service method,
container in which the servlet has been passing request and response objects. Service
deployed. When a request is mapped to a methods are discussed in Writing Service
servlet, the container performs the following Methods.
steps. ̵ If it needs to remove the servlet, the container
̵ If an instance of the servlet does not exist, the finalizes the servlet by calling the servlet's
web container: destroy method. For more information, see
 Loads the servlet class Finalizing a Servlet.
 Creates an instance of the servlet class ̵ When a servlet is first started up, its init(
 Initializes the servlet instance by calling the init ServletConfig config) method is called
method (initialization is covered in Creating and  init should perform any necessary initializations
Initializing a Servlet) 7
 init is called only once, and does not need to be thread-safe 8

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

7 8
10/9/2019

Servlet Servlet
̵ Every servlet request results in a call to
service(ServletRequest request, ServletResponse
response)
 service calls another method depending on the type of service
requested
 Usually you would override the called methods of interest, not
service itself
 service handles multiple simultaneous requests, so it and the
methods it calls must be thread safe
̵ When the servlet is shut down, destroy() is called
 destroy is called only once, but must be thread safe (because
other threads may still be running)

9 10

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

9 10

Servlet – getting start Servlet – First Demo


̵ Setup environments ̵ Open IDE and create new project
 JDK 1.8 or higher
 Tomcat 8.5 or higher
 IntelliJ IDEA Community or higher
 MySQL Server (can use XAMPP)
 Navicat

11 12

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

11 12
10/9/2019

Servlet – First Demo Servlet – First Demo

13 14

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

13 14

Servlet – First Demo Servlet – First Demo


̵ Add Lib Servlet.

15 16

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

15 16
10/9/2019

Servlet – First Demo Servlet – First Demo

17 18

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

17 18

Servlet – First Demo Servlet – First Demo


̵ Add Servlet Plugin -> Restart IED.

19 20

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

19 20
10/9/2019

Servlet – First Demo Servlet – First Demo


̵ Configure Tomcat server

21 22

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

21 22

Servlet – First Demo Requests, Responses and Headers


̵ HTTP is a simple, stateless protocol. A client,
such as a web browser, makes a request, the
web server responds, and the transaction is
done.
̵ When the client sends a request, the first thing
it specifies is an HTTP command, called a
method, that tells the server the type of action
it wants performed.
̵ After sending the request, the client can send
optional header information to tell the server
extra information about the request.
23 24

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

23 24
10/9/2019

GET and POST GET and POST


GET POST
̵ When a client connects to a server and makes BACK button Harmless Data will be re-submitted (the browser should
an HTTP request, the request can be of several /Reload alert the user that the data are about to be re-
submitted)
different types, called methods. Bookmarked Can be bookmarked Cannot be bookmarked
Cached Can be cached Not cached
̵ The most frequently used methods are GET Encoding type application/x-www-form-urlencoded application/x-www-form-urlencoded or
multipart/form-data. Use multipart encoding
and POST for binary data
History Parameters remain in browser history Parameters are not saved in browser history
 HTTP GET requests include all required data in the
URL. Restrictions on
data length
Yes, when sending data, the GET method
adds the data to the URL; and the length
No restrictions

 HTTP POST requests supply additional data from of a URL is limited (maximum URL length
is 2048 characters)
the client (browser) to the server in the message Restrictions on Only ASCII characters allowed No restrictions. Binary data is also allowed
body data type
Security GET is less secure compared to POST POST is a little safer than GET because the
because data sent is part of the URL parameters are not stored in browser history or
Never use GET when sending passwords in web server logs
or other sensitive information!
25 26
Visibility Data is visible to everyone in the URL Data is not displayed in the URL
08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

25 26

Servlet Servlet
̵ Every servlet must implement the
javax.servlet.Servlet interface.
̵ HTTP servlet usually overrides doGet() to
handle GET requests and doPost() to handle
POST requests. An HTTP servlet can override
either or both of these methods, depending on
the type of requests it needs to handle.

27 28

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

27 28
10/9/2019

Servlet HttpServletRequest
̵ doGet(HttpServletRequest req, ̵ The HttpServletRequest represents the client’s
HttpServletResponse resp) - Called by the request. This object gives a servlet access to
server (via the service method) to allow a information about the client, the parameters
servlet to handle a GET request. for this request, the HTTP headers passed
along with the request
̵ doPost(HttpServletRequest req,
HttpServletResponse resp) - Called by the
server (via the service method) to allow a
servlet to handle a POST request.

29 30

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

29 30

HttpServletRequest HttpServletRequest
̵ getAttribute(String name) - Returns the ̵ getRequestDispatcher(String path) -
value of the named attribute as an Object, or Returns a RequestDispatcher object that acts
null if no attribute of the given name exists. as a wrapper for the resource located at the
̵ getParameter(String name) - Returns the given path.
value of a request parameter as a String, or ̵ setCharacterEncoding(String env) -
null if the parameter does not exist. Overrides the name of the character encoding
̵ getParameterValues(String name) - used in the body of this request.
Returns an array of String objects containing ̵ getSession() - Returns the current session
all of the values the given request parameter associated with this request, or if the request
has, or null if the parameter does not exist. does not have a session, creates one.
31 32

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

31 32
10/9/2019

HttpServletRequest HTTP Request


̵ setAttribute(String name, Object o) - ̵ setAttribute(String name, Object o) -
Stores an attribute in this request. Stores an attribute in this request.
̵ removeAttribute(String name) - Removes ̵ removeAttribute(String name) - Removes
an attribute from this request. an attribute from this request.
̵ setCharacterEncoding(String env) - ̵ setCharacterEncoding(String env) -
Overrides the name of the character encoding Overrides the name of the character encoding
used in the body of this request. used in the body of this request.

33 34

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

33 34

HTTP Response HttpServletResponse


̵ The HttpServletResponse represents the ̵ sendRedirect(String location) - Sends a
servlet’s response. A servlet can use this object temporary redirect response to the client using
to return data to the client. This data can be of the specified redirect location URL.
any content type, though the type should be ̵ setCharacterEncoding(String charset) -
specified as part of the response. A servlet can Sets the character encoding (MIME charset) of
also use this object to set HTTP response the response being sent to the client, for
headers. example, to UTF-8.
̵ getWriter() - Returns a PrintWriter object
that can send character text to the client.

35 36

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

35 36
10/9/2019

Forward page Redirect page.


̵ Redirect page and attack data, keep old data. ̵ Redirect page to another web page with new
data.

Page A Page B Page C Page A Page B Page C


Add Keep old Receive data Add Processing Only receive
data to data from from page A data to of data from data from
request page A, add and B 37
request A, after page B 38
new data redirect to C
08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

37 38

Example Response Status Codes


protected void doGet(HttpServletRequest request, ̵ Status code is a code of server sent to client.
HttpServletResponse response) ̵ Status code is used to notify status of server
throws ServletException, IOException {

String uname = request.getParameter("uname");


String pass = request.getParameter("pass");
if(uname ??? && pass ???){
response.sendRedirect("index.jsp");
}else{
request.getRequestDispatcher("login.jsp")
.forward(request, response);
}
}

39 40

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

39 40
10/9/2019

Response Status Codes Response Status Codes


̵ Status codes for HTTP 1.1: ̵ Status code constants are defined in
 1xx Informational: Request received, continuing HttpServletResponse beginning with SC_
process (the client needs to respond in some way) • 200 (SC_OK)
 2xx Successful – Success and document follows
 3xx Redirection: Further action must be taken in – Default for servlets
order to complete the request • 302 (SC_MOVED_TEMPORARILY)
 4xx Incomplete: The request contains bad syntax – Requested document temporarily moved elsewhere
or some other client error – Browsers go to new location automatically
 5xx Server Error: The request is valid, but the – Servlets should use sendRedirect, not setStatus,
server failed to fulfill the request when setting this header
 Default status code is 200 (OK) • 401 (SC_UNAUTHORIZED)
– Browser tried to access password-protected page
̵ Status code constants are defined in without proper Authorization header
HttpServletResponse beginning with SC_ • 404 (SC_NOT_FOUND)
41 42
– No such page
08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

41 42

Response Status Codes web.xml File


How to set status code? ̵ Web.xml is called as deployment descriptor file
̵ Mothod and its is is an XML file that contains
 setStatus(int statusCode) information on the configuration of the web
application, including the configuration of
̵ Can use sendError method if status code from servlets.
form 400 - 599
 void sendError(int sc)
• The server may give the error special treatment
 void sendError(int code, String message)
• Wraps message inside small HTML document

43 44

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

43 44
10/9/2019

web.xml File Servlet Mapping


̵ Servlet Mapping Change Url servlet /login /dangnhap
̵ Default Welcome File List <servlet>
<servlet-name>login</servlet-name>
̵ Error page <servlet-class>login</servlet-class>
</servlet>
̵ Fitter <servlet-mapping>
<servlet-name>login</servlet-name>
̵ Context-param <url-pattern>/dangnhap</url-pattern>
̵ Permission </servlet-mapping>

Referring file that


web.xml
invokes servlet Java servlet class
url pattern  name
url pattern used with actual code
in FORM ACTION name  servlet class
45 46

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

45 46

Error page Initial Parameters


̵ Using to config some value using in application.
<error-page> You can config value using in a sigle page or using
<error-code>401</error-code> in all page.
<location>/error401.html</location>
</error-page> ̵ EX:
<error-page>  Using in sign page:
<error-code>404</error-code> <servlet>
<location>/error404.html</location> <servlet-name>login</servlet-name>
</error-page> <servlet-class>login</servlet-class>
<error-page> <init-param>
<error-code>500</error-code> <param-name>title</param-name>
<location>/error500.html</location> <param-value>Baby Shop</param-value>
</error-page> </init-param>
<error-page> </servlet>
<error-code>503</error-code>
<location>/error503.html</location>
 Using value: String title= getServletConfig()
.getInitParameter("title");
</error-page>
47  Use only in login page 48

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

47 48
10/9/2019

Servlet Fitter
̵ Value using in all page ̵ A filter is an object that is invoked at the
<context-param>
preprocessing and postprocessing of a request.
<param-name>title</param-name> ̵ It can also intercept the response and do post-
<param-value>Shop đồ trẻ em</param-value>
</context-param> processing before sending to the client in web
application.
̵ Using value ̵ Servlet Filters are pluggable java components
 Servlet: that we can use to intercept and process
ServletConfig config = getServletConfig(); requests before they are sent to servlets and
ServletContext context = config.getServletContext();
String value = context.getInitParameter("title"); response after servlet code is finished and
before container sends the response back to
 In jsp page the client.
String value = application.getInitParameter("title"); 49 50

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

49 50

Servlet Filter Fitter


̵ void init(FilterConfig paramFilterConfig)
method is called only once in the lifecycle of
filter and we should initialize any resources in <filter>
this method <filter-name>utf8</filter-name>
<filter-class>utf8</filter-class>
̵ doFilter(ServletRequest request, </filter>
ServletResponse response, FilterChain fe) <filter-mapping>
<filter-name>utf8</filter-name>
the method invoked every time by container <url-pattern>/*</url-pattern>
when it has to apply filter to a resource </filter-mapping>

̵ void destroy()

51 52

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

51 52
10/9/2019

̵ All of page in application (jsp and servlet) will


public class utf8 implements Filter {
run file utf8.java frist and request and respoint
@Override will encode to utf8.
public void destroy() {}
@Override
public void doFilter(ServletRequest request,
ServletResponse response,FilterChain arg2)
throws IOException, ServletException {

request.setCharacterEncoding("utf8");
response.setCharacterEncoding("utf8");
arg2.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws
ServletException {}
} 53 54

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

53 54

Q&A

DEMO
55 56

08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56 08/2019 KHOA CNTT - NLU LẬP TRÌNH WEB PHAN ĐÌNH LONG 56

55 56

You might also like