A
servlet is a Java class that can be loaded dynamically into and run by a
special web server. This servlet-aware web server is called a servlet container, which also was called a servlet engine in the early days of the servlet
technology.
Sharing Information
As you start using servlets to create more complex websites you’ll discover a need to share information between servlets. In a traditional program, it’s easy to share information. But if your program consists of a number of different servlets, where is the information stored?
There are in fact a number of different places where information can be stored. These include:
ServletContext—In spite of its name, the ServletContext actually is shared by all servlets on your website. It therefore is the best place for information that you want to pass between servlets. You can get a hold of the ServletContext by calling getServletContext, which is a method of the Servlet class.
A database connection is an example of an object you might want to store in the ServletContext. The database connection could get initialized once, and then shared by different Servlets as needed
HttpSession—Each individual user accessing the webserver has their own HttpSession. Call getSession on the HttpServletRequest to retrieve the session.
Items in a shopping cart are an example of data you would want to store in the HttpSession, because this information is per user.
HttpServletRequest—As we’ve already seen each HTTP request has their own request object. We previously saw how a servlet can forward to an HTML file. Servlets can also forward to other servlets or to JSPs. In these cases, passing information on to the new JSP or servlet may be useful. The HttpServletRequest can be used to pass information in these cases.
The ServletContext, HttpSession, and HttpServletRequest can all act as essentially maps, where you pass in a name and an object and then later retrieve the object by passing in the name. For example we could ask the user to enter their name on one webpage, and then store it in the session like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
String userName = request.getParameter("name");
HttpSession session = request.getSession();
session.setAttribute("name",userName);
…
}
In another servlet we could retrieve the name like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String username = (String) session.getAttribute("name");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
…
out.println("<h1>Hello " + username + "</h1>");
…
}
There is one more place you can use to store information:
ServletConfig—Each servlet has its own ServletConfig. This object is used to set initial values on the servlet. The ServletConfig values in the servlet config are set in advance by the webserver, and cannot be changed while the program is running. The values come from a special configuration file called web.xml.
The name of the database to use is an example of something you might want to access through the ServletConfig. Suppose you wanted to be able to quickly switch your web server from accessing a testing database to using a production database. If your program looks up the name of the database in the ServletConfig, a simple change to the web.xml file would automatically change your server from one database to the other.
The ServletConfig only allows you to retrieve string values. You can retrieve a specific value by calling getInitParameter along with the name of the parameter you are asking for. You can retrieve the names of all the parameters available by calling getInitParameterNames.
Listeners
While the ServletContext and HttpSession can be used to exchange information between servlets, one issue you will run into is who sets an initial value for that information. One possible solution is to have each servlet check and see if the information has been initialized. If it hasn’t the servlet can go ahead and initialize the information itself. A better solution is to take advantage of a listener.
In Java Enterprise Edition, we can create a listener class. This class will listen for the creation of ServletContexts, HttpSessions, or ServletRequests. It can also listen for changes to attributes on these objects. Make sure you tell Eclipse specifically that you want to create a Listener (“New > Other …” and then “Web > Listener”). Eclipse needs to do some setup to make sure that your listener gets called automatically by the system when the events you are interested in occur.
Here we define a listener which will run code when an HttpSession is created:public class CityListener
implements HttpSessionListener, HttpSessionAttributeListener
public void sessionCreated(HttpSessionEvent event) {
HttpSession session = event.getSession();
session.setAttribute("city", "Palo Alto");
}
}
As you can see the sessionCreated code will set an initial value for the “city” attribute. This code will run before any of our servlets get a chance to interact with the HttpSession object. Therefore they can all assume that the “city” attribute has a reasonable value set, instead of the null which will be returned if we do not initialize the attribute.
Warning: Some students have not been able to get listeners working. Unfortunately we have not been able to track down the source of the problem. This error is rare, and may be tied to specific machine configurations. If you run into this error, use the technique mentioned at the start of this section (have each servlet check to see if the information is initialized and if it isn’t initialize it) otherwise use listeners.
This init, service, and destroy methods are known as life-cycle methods and are called in the following sequence.
1. The init method is called when the servlet is first created, and is not called again as long as the servlet is not destroyed. This resembles the applet’s init method, which is invoked when the applet is created, and is not invoked again as long as applet is not destroyed.
2. The service method is invoked each time the server receives a request for the servlet. The server spawns a new thread and invokes service.
3. The destroy method is invoked once all threads within the servlet's service method have exited or after a timeout period has passed. This method releases resources for the servlet.
When the servlet was first invoked, it displays
Constructor called
init called
doGet called
when the servlet was invoked for the second time, it displays
doGet called
when Tomcat is shut down
destroy called
Common gateway interface is a protocol for server-side programs to generate dynamic Web content.
Both GET and POST methods send requests to the Web server. The POST method always triggers the corresponding CGI program to be executed. The GET method may not cause the CGI program to be executed, if the previous same request is cached in the Web browser. Web browsers often cache Web pages so the same request can be quickly responded without contacting the Web server. The browser checks the request sent through the GET method as a URL query string. If the results for the exact same URL are cached on disk, then the previous Web pages for the URL might be displayed. To ensure a new Web page always to be displayed, use the POST method. For example, a POST method should be used if the request will actually update the database. If your request is not time-sensitive, such as finding an address of a student in the database, you should use the GET method to speed up the performance.
You can submit a GET request directly from a URL, but a POST request must always be submitted directly from an HTML form.
The differences between CGI and servlets are:
1. servlets are Java programs. You can use a vast collection of Java classes to develop servlets;
2. servlets are more efficient than CGI.
Getting Inputs
When a user enters information into a form and then submits it, their form information is either encoded into the URL if the form uses a GET request or sent as part of the body if the form uses a POST request. Regardless of the method used, we can get the information back out from the HttpServletRequest object which our doGet or doPost method receives as a parameter.
Call getParameter on the HttpServletRequest object to retrieve the value of a specific parameter. The value returned will always be a string. Here is an example where we retrieve the age sent to us from an HTML form:
Getting Inputs
When a user enters information into a form and then submits it, their form information is either encoded into the URL if the form uses a GET request or sent as part of the body if the form uses a POST request. Regardless of the method used, we can get the information back out from the HttpServletRequest object which our doGet or doPost method receives as a parameter.
Call getParameter on the HttpServletRequest object to retrieve the value of a specific parameter. The value returned will always be a string. Here is an example where we retrieve the age sent to us from an HTML form:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class InitCounter extends HttpServlet {
int count;
public void init(ServletConfig config) throws ServletException {
super.init(config);
String initial = config.getInitParameter("initial");
try {
count = Integer.parseInt(initial);
}
catch (NumberFormatException e) {
count = 0;
}
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
count++;
out.println("Since loading (and with a possible initialization");
out.println("parameter figured in), this servlet has been accessed");
out.println(count + " times.");
}
}
The init() method accepts an object that implements the ServletConfig interface. It uses the config object's getInitParameter() method to get the value for the init parameter named initial. This method takes the name of the parameter as a String and returns the value as a String. There is no way to get the value as any other type. This servlet therefore converts the String value to an int or, if there's a problem, defaults to a value of 0.Take special note that the first thing the init() method does is call super.init(config). Every servlet's init() method must do this!Why must the init() method call super.init(config)? The reason is that a servlet is passed its ServletConfig instance in its init() method, but not in any other method. This could cause a problem for a servlet that needs to access its config object outside of init(). Calling super.init(config) solves this problem by invoking the init() method of GenericServlet, which saves a reference to the config object for future use.So, how does a servlet make use of this saved reference? By invoking methods on itself. The GenericServlet class itself implements the ServletConfig interface, using the saved config object in the implementation. In other words, after the call to super.init(config), a servlet can invoke its own getInitParameter() method. That means we could replace the following call:String initial = config.getInitParameter("initial");with:String initial = getInitParameter("initial");This second style works even outside of the init() method. Just remember, without the call to super.init(config) in the init() method, any call to the GenericServlet's implementation of getInitParameter() or any other ServletConfig methods will throw a NullPointerException. So, let us say it again: every servlet's init() method should call super.init(config) as its first action. The only reason not to is if the servlet directly implements the javax.servlet.Servletinterface, where there is no super.init().
The ServletConfig parameter provided configuration information to the servlet, and thesuper.init(config) call passed the config object to the GenericServlet superclass where it was stored for use by the servlet. Specifically, the GenericServlet class used the passed-in config parameter to implement the ServletConfig interface itself (passing all calls to the delegate config), thus allowing a servlet to invoke ServletConfig methods on itself for convenience.The whole operation was fairly convoluted, and in Servlet API 2.1 it was simplified so that a servlet now needs only to implement the init( ) no-argument version and the ServletConfig and GenericServlet handling will be taken care of in the background.
The javax.servlet package contains seven interfaces, three classes, and two exceptionsThe seven interfaces are as follows:· ServletThe three classes are as follows:
And, finally, the exception classes are these:A protocol-independent servlet should subclassGenericServlet, while an HTTP servlet should subclass HttpServlet,which is itself a subclass of GenericServletwith added HTTP-specific functionality.
The getAttribute, setAttribute, and removeAttribute methods were added to the Servlet API in version 2.2. Prior to version 2.2, these methods were called getValue, putValue, and removeValue (with the same parameters). Although getValue, putValue, and removeValue are supported under version 2.2 of the ServletAPI, they are deprecated. Only use them if your servlets must run under Servlet API version2.1 or earlier.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package httpExamples;
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 Acer
*/
public class QuizServlet extends HttpServlet {
private static final String AUSTRALIA = "australia";
private static final String AUSTRALIA_CAPITAL = "Canberra";
private static final String BRAZIL = "brazil";
private static final String BRAZIL_CAPITAL = "Brasilia";
private static final String IRELAND = "ireland";
private static final String IRELAND_CAPITAL = "Dublin";
private static final String NAME = "name";
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
int count = 0;
String name = request.getParameter(NAME);
String answerAustralia = request.getParameter(AUSTRALIA);
String answerBrazil = request.getParameter(BRAZIL);
String answerIreland = request.getParameter(IRELAND);
out.println("<html>");
out.println("<head><title>QuizServlet</title></head>");
out.println("<body>");
if (name != null && name.trim().length() > 0) {
out.println("<h1>Welcome " + name + "</h1>");
} else {
out.println("<h1>Welcome</h1>");
}
count = count + doQuestion(out, 1, answerAustralia, AUSTRALIA_CAPITAL);
count = count + doQuestion(out, 2, answerBrazil, BRAZIL_CAPITAL);
count = count + doQuestion(out, 3, answerIreland, IRELAND_CAPITAL);
out.println("<hr width=\"25%\" align=\"left\">");
out.println("You scored " + count + " out of 3");
String userAgent = request.getHeader("user-agent");
if (userAgent != null && userAgent.indexOf("MSIE") != -1) {
out.println(" using Microsoft browser.");
} else if (userAgent != null) {
out.println(" using Non-Microsoft browser.");
}
out.println("</body></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
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
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
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
private int doQuestion(PrintWriter out, int number,
String answer, String solution) {
out.println("<h2>Question " + number + "</h2>");
if (answer != null &&
solution.equalsIgnoreCase(answer)) {
out.println("<b>Correct</b>");
return 1;
} else {
out.println("<b>Wrong:</b> The correct answer is " + solution);
return 0;
}
}
}
LAB Work
Web Application 1 Linking Between Servlet and Jsp
<%--
Document : index
Created on : Jan 10, 2015, 8:33:09 AM
Author : gyanendra
--%>
<%@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>
<form action="Sum">
<input type="text" name="n1" value="0" size="5" />
+<input type="text" name="n2" value="0" size="5" />
<input type="submit" value="Sum" />
</form>
</body>
</html>
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package NICT;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author gyanendra
*/
public class Sum extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String FirstNumber=request.getParameter("n1");
String SecondNumber=request.getParameter("n2");
int sum=Integer.parseInt(FirstNumber)+Integer.parseInt(SecondNumber);
request.setAttribute("foo", sum);
// HttpSession session = request.getSession(true);
//session.setAttribute("foo", sum);
getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
} 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
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
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
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
result.jsp
<%--
Document : result
Created on : Jan 10, 2015, 9:10:07 AM
Author : gyanendra
--%>
<%@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>
<h3> The Sum Of Two numbers is</h3>
<%= request.getAttribute("foo") %>
</body>
</html>
Web Application 2 Adding Two Number Using Java Bean
package Sum;
public class ADD {
private int a;
private int b;
private int sum;
/**
* @return the a
*/
public int getA() {
return a;
}
/**
* @param a the a to set
*/
public void setA(int a) {
this.a = a;
}
/**
* @return the b
*/
public int getB() {
return b;
}
/**
* @param b the b to set
*/
public void setB(int b) {
this.b = b;
}
/**
* @return the sum
*/
public int getSum() {
sum=a+b;
return sum;
}
}
<%--
Document : index
Created on : Jan 20, 2015, 8:55:43 AM
Author : gyanendra
--%>
<%@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>
<form action="a.jsp">
<input type="text" name="a" value="0" size="5" />
+<input type="text" name="b" value="0" size="5" />
<input type="submit" value="Sum" />
</form>
</body>
</html>
a.jsp
<%--
Document : a
Created on : Jan 20, 2015, 9:00:55 AM
Author : gyanendra
--%>
<%@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>
<jsp:useBean id="s" scope="session" class="Sum.ADD" />
<jsp:setProperty name="s" property="*" />
Sum = <jsp:getProperty name="s" property="sum" />
</body>
</html>
Web Application 3
errorJSP.jsp
<html>
<head>
</head>
<body>
<h3>Input is not valid! Please input your name again:</h3>
<%@ include file="index.html" %>
</body>
</html>
helloJSP.jsp
<html>
<body>
Hello <%=request.getParameter("userName")%>!
</body>
</html>
index.html
<html>
<head>
<title></title>
</head>
<body>
<h3>Please enter the user name :</h3><p>
<form action="test.jsp">
UserName : <input type="text" name="userName"><br><br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>
test.jsp
<html>
<head>
<title></title>
</head>
<body>
<%
if (!request.getParameter("userName").equals( "" ))
{
%>
<%@ include file="index.html" %>
<jsp:include page="helloJsp.jsp" />
<%
}
else
{
%>
<jsp:forward page="errorJSP.jsp" />
<%
}
%>
</body>
</html>
Web Application 4 Linking Between Servlet
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>forwardMethod.TestServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ForwardedServlet</servlet-name>
<servlet-class>ForwardedServlet.ForwardedServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ForwardedServlet</servlet-name>
<url-pattern>/ForwardedServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>doGetMethod</title>
</head>
<body>
<h3>Please enter Fahrenheit temperature :</h3><p>
<form action="TestServlet">
Temperature(F) : <input type="text" name="temperature"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package forwardMethod;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author gyanendra
*/
public class TestServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String temperature = request.getParameter("temperature");
DecimalFormat twoDigits = new DecimalFormat("0.00");
try {
double tempF = Double.parseDouble(temperature);
String tempC = twoDigits.format((tempF -32)*5.0/9.0);
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body>");
out.println("<h3>" + temperature + " degrees in Fahrenheit is converted to "
+ tempC + " degrees in Celsius</h3><p>");
out.println("</body>");
out.println("</html>");
} finally {
request.setAttribute("temperature", temperature);
request.getRequestDispatcher("/ForwardedServlet").forward(request, response);
return;
}
}
// <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
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
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
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ForwardedServlet;
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 gyanendra
*/
public class ForwardedServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String temp = (String) request.getAttribute("temperature");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head>");
pw.println("</head>");
pw.println("<body>");
pw.println("<h3>" + "Input " + temp + " is not valid! </h3><p>");
pw.println("</body>");
pw.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
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
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
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Web Application 5 Java Bean Example
<html>
<head>
<title></title>
</head>
<body>
<form action="check.jsp">
<h3>What do you prefer :</h3>
<input type=radio name="title" value="java">Java <br>
<input type=radio name="title" value="c">C# <p>
<input type=submit value="Submit">
</form>
</body>
</html>
check.jsp
<html>
<body>
<jsp:useBean id="survey" class="appScope.SurveyBean" scope="application" />
<jsp:setProperty name="survey" property="quantity"
value='<%= request.getParameter("title")%>' />
<form action="survey.jsp">
<h3> Thanks for your input </h3>
<h3> Please check the survery summary status if you want </h3> <br>
<input type=submit value="Check Status"></form>
</body>
</html>
survey.jsp
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<H1>Survey Summary</H1>
<jsp:useBean id="survey" class="appScope.SurveyBean" scope="application"/>
Java = <jsp:getProperty name="survey" property="javaQ" />
C# = <jsp:getProperty name="survey" property="cQ" />
<BODY>
</HTML>
package appScope;
public class SurveyBean
{
private int javaQ = 0;
private int cQ = 0;
public int getJavaQ()
{
return javaQ;
}
public int getCQ()
{
return cQ;
}
public void setQuantity(String bookTitle)
{
try
{
if (bookTitle.equals("java"))
{
javaQ++;
}
if (bookTitle.equals("c"))
{
cQ++;
}
}catch(Exception e){e.printStackTrace();}
}
}
Web Application 6 Linking Between Servlet and JSp
<head>
<title></title>
</head>
<body>
<h3> Conference Registration </h3>
//This means that URLs of the form:
//http://hostname/projectname/BasicServlet
//will be mapped to this Servlet. For example, if I am running tests using my computer as localhost and the name of my project is Examples, then the URL should be:1
//http://localhost:8080/Examples/BasicServlet
<form action="/servletDispatch/dispatch">
<h4> Name: </h4>
<input type="text" name="userName">
<h4> Status: </h4>
<input type=radio name="status" value="student">Student
<input type=radio name="status" value="faculty">Faculty <p>
     <input type=submit value="Submit">
</form>
</body>
</html>
package servletDispatch;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DispatchServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws javax.servlet.ServletException, java.io.IOException
{
String status = req.getParameter("status");
int orgFee = 500;
if(status != null && status.equals("student") )
{
int studentFee = 500 / 2;
req.setAttribute("regFee", "" + studentFee);
req.getRequestDispatcher("/output.jsp").forward(req, res);
return;
}
else if(status != null && status.equals("faculty") )
{
int facultyFee = 500 / 1;
req.setAttribute("regFee", "" + facultyFee);
req.getRequestDispatcher("/output.jsp").forward(req, res);
return;
}
}
}
output.jsp
<html>
<head>
<title></title>
</head>
<body>
<H3> Thank you, <%=request.getParameter("userName") %>.<br>
Your <%=request.getParameter("status") %> registration fee is
<%=request.getAttribute("regFee") %>.
</H3>
</body>
</html>







No comments:
Post a Comment