Here are the steps to build a basic servlet project in Java:
1. Create a dynamic web project in your IDE (e.g. Eclipse) and set up the required dependencies like Servlet API jar.
2. Create a class that extends HttpServlet. This will be your servlet class.
3. Implement the init(), doGet(), doPost() and destroy() methods. Add your servlet logic in doGet()/doPost().
4. Map the servlet class to a URL pattern in web.xml deployment descriptor.
5. Deploy the war/ear file to a servlet container like Tomcat and test via browser.
This provides a basic skeleton to get
prashanth updated resume 2024 for Teaching Profession
BITM3730Week12.pptx
1. Java JSPs and Servlets
BITM 3730
Developing Web Applications
2. Previous Work Review
• http://pirate.shu.edu/~marinom6/work.html
• Please Note only previously due HW assignments are posted on my
pirate.shu.edu web space
• Begin organizing your creating files for this course into an easy to find folder
on your desktop for easy FTP later on
3. Basics
• Java programming language can be embedded into JSP
• JSP stands for Java Server Pages
• JSP is compiled on servlets
• JSP is a server-side web technology
• The primary function of JSP is rendering content
• The primary function of a servlet is processing
4. JSP – Java Server Page
• Based on HTML. JSP pages can be based on HTML pages, just change
the extension
• Server-side web technology
• Compiled into servlets at runtime
• Allows for embedding of Java code directly into the script using
<%.....%>
• Requires Apache Tomcat installation on server
5. Servlet
• Compiled code used to deliver content over the HTTP protocol
• Developed as a Java class conforming to the Java Servlet API
• Typically used in conjunction with JSPs for more extensive processing
6. JSP vs Servlet
• JSPs are more geared towards rendering content
• Servlets are better suited for processing since they are pre-compiled
• Consider the concept of Model-View-Controller (MVC)
• Model is your business model which houses all of the business logic
• View is your users’ view into your application. In this case it would be JSPs
• Controller is the glue between the model and the view
• Spring and Struts are two popular MVCs used in Java web applications
• Servlets will typically process request data, enrich it (process it) and forward the request
onto a JSP for display
7. Working Together
• JavaServer Pages (JSP) is a Java standard technology that enables you to write
dynamic, data-driven pages for your Java web applications.
• JSP is built on top of the Java Servlet specification.
• The two technologies typically work together, especially in older Java web
applications.
• From a coding perspective, the most obvious difference between them is that with
servlets you write Java code and then embed client-side markup (like HTML) into
that code, whereas with JSP you start with the client-side script or markup, then
embed JSP tags to connect your page to the Java backend.
8. JSP vs. Everyone Else
• JSP vs. Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic part
is written in Java, not Visual Basic or other MS specific language, so it is more powerful and
easier to use. Second, it is portable to other operating systems and non-Microsoft Web servers.
• JSP vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to
have plenty of println statements that generate the HTML.
• JSP vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for
"real" programs that use form data, make database connections, and the like.
• JSP vs. JavaScript: JavaScript can generate HTML dynamically on the client but can hardly
interact with the web server to perform complex tasks like database access and image processing
etc.
• JSP vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.
9. Methods to Set HTTP Status Code
S.N
o.
Method & Description
1
public void setStatus ( int statusCode )
This method sets an arbitrary status code. The setStatus method
takes an int (the status code) as an argument. If your response
includes a special status code and a document, be sure to
call setStatus before actually returning any of the content with
the PrintWriter.
2
public void sendRedirect(String url)
This method generates a 302 response along with a Location header
giving the URL of the new document.
3
public void sendError(int code, String message)
This method sends a status code (usually 404) along with a short
message that is automatically formatted inside an HTML document
and sent to the client.
10. Applications of Servlet
• Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page
or it could also come from an applet or a custom HTTP client program.
• Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media
types and compression schemes the browser understands, and so forth.
• Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response directly.
• Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in
a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
• Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or
other clients what type of document is being returned (e.g., HTML), setting cookies and caching
parameters, and other such tasks.
12. init
public void init(ServletConfig config)
throws ServletException
• Called by the servlet container to indicate to a servlet that the servlet is being placed into service.
• The servlet container calls the init method exactly once after instantiating the servlet. The init
method must complete successfully before the servlet can receive any requests.
• The servlet container cannot place the servlet into service if the init method
• Throws a ServletException
• Does not return within a time period defined by the Web server
13. destroy
public void destroy()
• Called by the servlet container to indicate to a servlet that the servlet is being taken
out of service. This method is only called once all threads within the servlet's
service method have exited or after a timeout period has passed. After the servlet
container calls this method, it will not call the service method again on this servlet.
• This method gives the servlet an opportunity to clean up any resources that are
being held (for example, memory, file handles, threads) and make sure that any
persistent state is synchronized with the servlet's current state in memory.
14. Servlet Life Cycle
• Servlet life cycle is governed by init(), service(), and destroy().
• The init() method is called when the servlet is loaded and executes only once.
• After the servlet has been initialized, the service() method is invoked to process a
request.
• The servlet remains in the server address space until it is terminated by the server.
Servlet resources are released by calling destroy().
• No calls to service() are made after destroy() is invoked.
15. GUIs
• A GUI (graphical user interface) is a system of interactive visual components
for computer software.
• A GUI displays objects that convey information and represent actions that
can be taken by the user.
• The objects change color, size, or visibility when the user interacts with them
16. Building Assignment 12
<html>
<head><title>First JSP</title></head>
<body>
<%
double num = Math.random();
if (num > 0.99) {
%>
<h2>You'll have a lucky day!</h2><p>(<%= num
%>)</p>
<%
} else {
%>
<h2>Well, life goes on ... </h2><p>(<%= num
%>)</p>
<%
}
%>
<a href="<%= request.getRequestURI() %>"><h3>Try
Again</h3></a>
</body>
</html>
17. Building Project 5
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ...Servlet extends HttpServlet {
// Runs when the servlet is loaded onto the server.
public void init() {
......
}
18. Building Project 5
// Runs on a thread whenever there is HTTP GET request
// Take 2 arguments, corresponding to HTTP request and response
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Set the MIME type for the response message
response.setContentType("text/html");
// Write to network
PrintWriter out = response.getWriter();
// Your servlet's logic here
out.println("<html>");
out.println( ...... );
out.println("</html>");
}
19. Building Project 5
// Runs as a thread whenever there is HTTP POST request
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// do the same thing as HTTP GET request
doGet(request, response);
}
20. Building Project 5
// Runs when the servlet is unloaded from the server.
public void destroy() {
......
}
// Other instance variables and methods
}