Java Servlets 110317050338 Phpapp01 PDF
Java Servlets 110317050338 Phpapp01 PDF
Svetlin Nakov
Borislava Spasova
Contents
1. Java Servlets Technology Overview
• What is a Java Servlet?
• Servlet Services
• Why Use Servlets?
• Time Servlet – Example
• Deploying Servlets on Eclipse IDE
2. Servlets Architecture
• Servlets API
• Servlets Life-Cycle
Contents (2)
1. Servlet Examples
• Processing Parameters – Hello Servlet
• Image Counter Servlet
2. Using Sessions
• What is a Session?
• The Sessions API
• Session Timeout
3. Session Examples
• Login / Logout Application
• The Browser's Cache Problems
Java Servlets
Technology Overview
What is a Java Servlet?
• Servlets
• Provide a general framework for services built
on the request-response paradigm
• Portable to any Java application server
• Have access to the entire family of Java and
Java EE APIs
• JDBC, Persistence, EJB, JMS, JAX-WS,
JTA, JTS, RMI, JNDI, JAXP, ...
• Fundamental part of all Java Web
application technologies (JSP, JSF, ...)
Servlet Services
• Java Servlets provide many useful services
• Provides low-level API for building Internet
services
• Serves as foundation to JavaServer Pages (JSP)
and JavaServer Faces (JSF) technologies
• Can deliver multiple types of data to any client
• XML, HTML, WML, GIF, etc...
• Can serve as “Controller” of JSP/Servlet
application
Why Use Servlets?
• Portability
• Write once, serve everywhere
• Power
• Can take advantage of all Java APIs
• Elegance
• Simplicity due to abstraction
• Efficiency & Endurance
• Highly scalable
Why Use Servlets? (2)
• Safety
• Strong type-checking
• Memory management
• Integration
• Servlets tightly coupled with server
• Extensibility & Flexibility
• Servlets designed to be easily extensible, though
currently optimized for HTTP uses
• Flexible invocation of servlet (SSI, servlet-chaining,
filters, etc.)
Time Servlet – Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
doPost() doPut()
HelloServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
ServletOutputStream out = response.getOutputStream();
String userName = request.getParameter("user_name");
out.println("<html><head>");
out.println("\t<title>Hello Servlet</title>");
out.println("</head><body>");
out.println("\t<h1>Hello, " + userName + "</h1>");
out.println("</body></html>");
}
Creating The Form in Eclipse IDE
HTTP/1.1 200 OK
Content-Length: 100
Date: Fri, 26 Mar 2006 10:06:28 GMT
Server: Apache-Coyote/1.1
<html><head>
<title>Hello Servlet</title>
</head><body>
<h1>Hello, Nakov</h1>
</body></html>
Image Counter Servlet
• We want to create a servlet that displays an
image counter (as JPEG image)
• The servlet should maintain an internal counter
• Can be initialized in the init() method and
incremented in the doGet() method
• It should produce binary output (the JPEG)
image
• The content type should be set to "image/jpeg"
Image Counter Servlet (2)
import javax.servlet.*;
import javax.servlet.http.*;
...
Enumeration attributes =
request.getAttributeNames();
Storing Data In The Session
<html>
<head><title>Login</title></head>
<body>
<form method="POST" action="LoginServlet">
Please login:<br>
Username:
<input type="text" name="username"><br>
Password:
<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Login Servlet
LoginServlet.java
public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest req,
HttpServletResponse resp)
throws IOException, ServletException {
String username = req.getParameter("username");
String password = req.getParameter("password");
PrintWriter out = resp.getWriter();
if (isLoginValid(username, password)) {
HttpSession session = req.getSession();
session.setAttribute("USER", username);
response.sendRedirect("MainServlet");
} else {
response.sendRedirect("InvalidLogin.html");
}
}
}
Main Servlet
MainServlet.java
public class MainServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse resp)
throws ServletException, IOException {
HttpSession session = request.getSession();
String userName = (String)
session.getAttribute("USER");
if (userName != null) {
response.setContentType("text/html");
ServletOutputStream out = resp.getOutputStream();
out.println("<html><body><h1>");
out.println("Hello, " + userName + "! ");
out.println("</h1></body></html>");
} else {
response.sendRedirect("LoginForm.html");
}
}
}
Logout Servlet
LogoutServlet.java
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
session.invalidate();
response.setContentType("text/html");
ServletOutputStream out =
response.getOutputStream();
out.println("<html><head>");
out.println("<title>Logout</title></head>");
out.println("<body>");
out.println("<h1>Logout successfull.</h1>");
out.println("</body></html>");
}
}
Invalid Login Page
InvalidLogin.html
<html>
<head>
<title>Error</title>
</head>
<body>
<h1>Invalid login!</h1>
Please <a href="LoginForm.html">try again</a>.
</body>
</html>
The Browser's Cache Problems
response.setHeader("Pragma", "No-cache");
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-cache");
Problems
1. Create a servlet that prints in a table the numbers
from 1 to 1000 and their square root.
2. Create a servlet that takes as parameters two
integer numbers and calculates their sum.
Create a HTML form that invokes the servlet. Try
to use GET and POST methods.
4. Implement a servlet that plays the "Number
guess game". When the client first invoke the
servlet it generates a random number in the
range [1..100]. The user is asked to guess this
number. At each guess the servlet says only
"greater" or "smaller". The game ends when the
user tell the number.
Homework
1. Create a servlet that takes as a parameter a
number and displays it as image that is hard to
be recognized by OCR software. The image
should have intentionally inserted defects.
2. Create an HTML form and a servlet for performing
conversions of distances from one metric to
another. The metrics that should be supported
are: meter, centimeter, kilometer, foot, inch, yard,
mile.
1 cm = 0.01 meters 1 km = 1000 meters
1 foot = 0.3048 meters 1 inch = 0.0254 meters
1 yard = 0.9144 meters 1 mile = 1609.344 meters
Homework (2)
1. Create a sequence of HTML forms and servlets
that allow entering information about a student.
The information is entered in 3 steps in 3
separate forms:
Step 1: First name, last name, age
Step 2: Address (country, town, street)
Step 3: University, faculty, specialty
The data entered in the 3 steps should be stored
in the session and finally displayed.
• Create a servlet that reads an image (from WEB-
INF\img\logo.gif) and returns it.