Servlets
- Servlets are java programs that run on a web server. The
are typically invoked when the "submit" button is pressed on an HTML
web page form.
- Thus one servlet will exist for each html form.
- Servlets inherit the HttpServlet
class
- Can override three methods of this class
- init() - called when the servelt is first created and loaded
into memory. for database applications, this is a good place to
establish the connection.
- service() - is called each time the server receives a request
for the servlet to process
- destory() - is called when the servlet is unloaded from
memory, in database applications this is a good place to close the
connection.
- Servlets implement the ServletRequest
and HttpServletRequest
Interfaces
- as part of this, they are required to process the following
methods
- doGet() process a "get" request
- doPost() process a "post" request
- When a servlet is created in Netbeans, Netbeans will create a
processRequest method that handles both get and post requests.
Therefore, the processRequest method is where you put your code.
- Creating a Servlet in Netbeans
- First, create a web application
- Next, create your html forms on web pages.
- Then, select File-New-File, then select "Web" as
the category and "Servlet" as the File type.
- Fill in the servlet name and package name and press Next,
then finish
- note, the next screen will show the servlet name and
the url pattern. Note, if you leave this screen alone (for now,
please do), then the url you use to access the servlet will not include
the package name.
- Your servlet code will be created in the Source packages (SRC)
folder of the project within a package folder.
- Now you can edit the code within the processRequest method.
- This method is passed a HTTPServletRequest and a
HTTPServletResponse object.
- HTTPServletRequest object (in the request variable)
- Useful methods:
- getParameter(String name) - returns the form data associated
with the field specified by name
- getSession() - gets the current session object.
- HttpServletResponse object (in the response variable)
- Useful methods
- getWriter() - returns an output stream (of type PrintWriter)
that can be used to send output (in HTML format) as a response to the
request.
- Session tracking in Servlets
- A session is a sequence of actions that invoke the same
servlet. Sessions store information (objects) on the web server
that is carried forward from one servlet invocation to the next.
- Sessions can be maintained using one of three methods
- Hidden values, a form element of type "hidden" is used to
give the sesession a name
- Cookies, the inital request creates a cookie for
subsequent requests to process
- Using the servlet API (preferred), see below
Servlet API - HttpSession class
- a servlet can create a new session or access an existing session
by adding the following line of code:
HttpSession session = request.getSession();
- if the session associated with the web user exists, it is
returned, if not, a new one is created.
- HttpSession is a "container" type class, it is used to
store objects (Java beans) across requests within the same session.
- you'll have to import javax.servlet.http.HttpSession to use it..
- to store an object in a HttpSession, use the setAttribute method,
e.g.
session.setAttribute("name","Fred Flintstone");
// sets a string object to the attribute called "name"
- to get the attribute back in subsequent requests, use
getAttribute method, this method returns null if the attribute is not
associated with the session, e.g.
String name = session.getAttribute("name");
- you should always set the inactive timeout interval (in seconds)
for your session, e.g.
session.setMaxInactiveInterval(600); //
timeout and destroy the session and its attributes after 10 minutes
- Other useful methods:
- session.getLastAccessedTime(); // returns the time the
client last sent a request assoicatied with the session (long)
- session.invalidate(); // has the effect of removing
all attributes objects from the session
- session.removeAttribute("name"); // removes the attribute
object with the specified name
- session.isNew(); // returns true if the session was
just created
JavaBeans and Servlets
- Javabean objects can be created with the "new" operator just like
any other objects.
- When you organize your source, you may want to have
servlets in one package and java beans in another, e.g.
name one package "beans" the other "servlets"
- If the java bean is in a different package from the servlet, then
you will need to import the package, or fully qualify the class name of
the bean
- For example, if you had java bean class named "Customer" are in a
package called beans, then you could create a new Customer object using
beans.Customer customer = new
beans.Customer();
or
import beans.*;
...
Customer customer = new Customer();
- To make a Javabean object live throughout the lifetime of the
session, you need to add it to the session during the request
that it was created, then access it other requests., eg.
session.setAttribute("Customer",customer);
// add in the servlet that created the bean
Customer customer =
(Customer)session.getAttribute("Customer");
if(customer == null) // session timed out or bean doesn't
exist
{
// handle it
}
Simple
calculator index.jsp
<%--
Document : index
Created on : Oct 27, 2008, 5:34:04 PM
Author : Mark Pendergast
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta
http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP
Page</title>
</head>
<body>
<h2>Calculator</h2>
<form name="calculator" method = "get"
action = "Calculator">
X : <input type = text
name = "x" size = 10><br>
Y : <input type = text
name="y" size = 10><br>
<br>
<input type = submit
name="operation" value = "+">
<input type = submit
name="operation" value = "-">
<input type = submit
name="operation" value = "*">
<input type = submit
name="operation" value = "/">
<input type = reset>
</form>
</body>
</html>
simple
calculator Calculator.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Mark Pendergast
*/
public class Calculator extends HttpServlet {
/**
* Processes requests for both HTTP
<code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest
request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out =
response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Answer</title>");
out.println("</head>");
out.println("<body>");
String xStr = request.getParameter("x");
String yStr = request.getParameter("y");
String operation = request.getParameter("operation");
double answer = 0;
double x = Double.parseDouble(xStr);
double y = Double.parseDouble(yStr);
if(operation.equals("+"))
answer = x + y;
else if(operation.equals("-"))
answer = x - y;
else if(operation.equals("*"))
answer = x * y;
else if(operation.equals("/"))
answer = x / y;
out.println("x "+operation+" y = "+answer+"<br>");
out.println("<input type='button' value='click here to try again'
onclick='javascript:history.back()'>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed"
desc="HttpServlet methods. Click on the + sign on the left to edit the
code.">
/**
* Handles the HTTP <code>GET</code>
method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,
response);
}
/**
* Handles the HTTP <code>POST</code>
method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,
response);
}
/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}