1 Explain the importance of RequestDispatcher Interface in
javax.servlet. Add suitable example to explain the methods of the
interface. (NOV 2018)
Resquestdispatcher ● Request Dispatcher interface
The RequestDispatcher interface provides the facility of dispatching
the request to another resource it may be html, servlet or jsp. This
interface can also be used to include the content of another resource
also. It is one of the way of servlet collaboration.
● There are two methods defined in the RequestDispatcher interface.
1. public void forward(ServletRequest request,ServletResponse
response)throws
ServletException,java.io.IOException:Forwards a request from a
servlet to another resource (servlet, JSP file, or HTML file) on the
server.
2. public void include(ServletRequest request,ServletResponse
response)throws
ServletException,java.io.IOException:Includes the content of a
resource (servlet, JSP page, or HTML file) in the response.
o Requestdispatcher Application
o index.html file: for getting input from the user.
o Login.java file: a servlet class for processing the response. If
password is servet, it will forward
the request to the welcome servlet.
o WelcomeServlet.java file: a servlet class for displaying the welcome
message.
o web.xml file: a deployment descriptor file that contains the
information about the servlet
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
.
Login.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response); }
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}}}
WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n); } }
2 What is cookie? Explain the need of the creation of the same. Explain the methods of cookie
class
Define following methods of Cookie class. (APR 2023)
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number. How Cookie works By default, each
request is considered as a new request. In cookies technique, we add cookie with response
from the servlet. So cookie is stored in the cache of the browser. After that if request is sent
by the user, cookie is added with request by default. Thus, we recognize the user as the old
user.
o Kinds/Types Of Cookies
The two types of cookies follow:
● Session cookies – Session cookies are stored in memory and are accessible as long as the
user is using the web application. Session cookies are lost when the user exits the web
application. Such cookies are identified by a session ID and are most commonly used to store
details of a shopping cart.
● Permanent cookies – Permanent cookies are used to store long-term information such as
user preferences and user identification information. Permanent cookies are stored in
persistent storage and are not lost when the user exits the application. Permanent cookies
are lost when they expire.
● Where Cookies Are Used
● Cookies are a convenient way to carry information from one session on a website to
another, or between sessions on related websites, without having to burden a server machine
with massive amounts of data storage.
● Storing the data on the server without using cookies would also be problematic because it
would be difficult to retrieve a particular user's information without requiring a login on each
visit to the website.
● If there is a large amount of information to store, then a cookie can simply be used as a
means to identify a given user so that further related information can be looked up on a
server-side database.
● For example the first time a user visits a site they may choose a username which is stored in
the cookie, and then provide data such as password, name, address, preferred font size, page
layout, etc.
● this information would all be stored on the database using the username as a key.
Subsequently when the site is revisited the server will read the cookie to find the username,
and then retrieve all the user's information from the database without it having to be re-
entered. Methods of Cookie class
● public void setComment(String purpose): This method is used for setting up comments
in the cookie. This is basically used for describing the purpose of the cookie.
● public String getComment(): Returns the comment describing the purpose of this cookie,
or null if the cookie has no comment.
● public void setMaxAge(int expiry): Sets the maximum age of the cookie in seconds.
● public int getMaxAge(): Gets the maximum age in seconds of this Cookie. By default, -1 is
returned, which indicates that the cookie will persist until browser shutdown.
● public String getName(): Returns the name of the cookie. The name cannot be changed
after creation.
● public void setValue(String newValue): Assigns a new value to this Cookie.
● public String getValue(): Gets the current value of this Cookie.
● getSecure() : Returns true if the browser is sending cookies only over a secure protocol, or
false if the browser can send cookies using any protocol.
● getValue() : Gets the current value of this Cookie.
● setPath(String uri) : Specifies a path for the cookie to which the client should return the
cookie. Creating Cookies Using Servlet
How to send Cookies to the Client
1. Create a Cookie object. 2. Set the maximum Age. 3. Place the Cookie in HTTP response
header. Create a Cookie object:
● Cookie c = new Cookie("userName","weit"); set the maximum Age: By using setMaxAge ()
method we can set the maximum age for the particular cookie in seconds.
● c.setMaxAge(1800); Place the Cookie in HTTP response header: We can send the cookie to
the client browser through response.addCookie() method.
● response.addCookie(c); How to read cookies
Cookie c[]=request.getCookies();
//c.length gives the cookie count
for(int i=0;i<c.length;i++)
{
out.print("Name: "+c[i].getName()+" & Value: "+c[i].getValue());
}
● Dynamically Changing The Colors Of A Page
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class setcookieservlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Cookie[] allcookies = request.getCookies();
boolean cookiepresent = false;
int cookieindex = 0;
if(allcookies != null)
{
for (int i = 0; i < allcookies.length; i++)
{
if(allcookies[i].getName().equals("colour"))
{
cookiepresent = true;
cookieindex = i;
break; } } }
if(cookiepresent==true)
{
out.print("<html><body bgcolor="+ allcookies[cookieindex].getValue()
+"></body></html>");
}
else
{
System.out.println("cook not pre");
if(request.getParameter("color")!= null)
{
Cookie setcolour = new Cookie("colour", request.getParameter("color"));
setcolour.setMaxAge(60*60); // 1 hour
response.addCookie(setcolour); }
else
{
out.print("<html><body><form method='post' action='setcookieservlet'>"
+ "<input type='text' name='color'><input type='submit'>"
+ "</form></body></html>");
}}}
catch(Exception x)
{
System.out.println(x.getMessage()); } }
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response); }
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response) }
3 Explain how java handles session management of a servlet application through
HTTPSession. (NOV 2018) session session session session session session
session session session
● What Are Sessions?
Session simply means a particular interval of time. Session Tracking is a way to
maintain state (data) of an user. It is also known as session management in
servlet. Http protocol is a stateless so we need to maintain state using session
tracking techniques. Each time user requests to the server, server treats the
request as the new request. So we need to maintain the state of an user to
recognize to particular user. HTTP is stateless that means each request is
considered as the new request. It is shown in the figure given below
: HttpSession interface
container creates a session id for each user.The container uses this id to identify
the particular user.An object of HttpSession can be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.
How to get the HttpSession object
The HttpServletRequest interface provides two methods to get the object of
HttpSession:
1. public HttpSession getSession():Returns the current session associated with
this request, or if the request does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current
HttpSession associated with this request or, if there is no current session and
create is true, returns a new session. Commonly used methods of HttpSession
interface
1. public String getId():Returns a string containing the unique identifier value.
2. public long getCreationTime():Returns the time when this session was
created, measured in
milliseconds since midnight January 1, 1970 GMT.Write a servlet code to
download a file. (NOV 2022)
3. public long getLastAccessedTime():Returns the last time the client sent a
request associated with this session, as the number of milliseconds since
midnight January 1, 1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects
bound to it.
● Lifecycle Of Http Session
o Every request is associated with an HttpSession object. It can be retrieved
using getSession(boolean create) available in HttpServletRequest. It returns the
current HttpSession associated with this request or, if there is no current session
and create is true, and then returns a new session. A session can be uniquely
identified using a unique identifier assigned to this session, which is called
session id. getId() gives you the session id as String. o isNew() will be handy in
quite a lot of situations. It returns true if the client does not know about the
session or if the client chooses not to join the session. getCreationTime() returns
the time when this session was created. getLastAccessedTime() returns the last
time the client sent a request associated with this session.
▪ public boolean HttpSession.isNew()
● This method returns whether the session is new. A session is considered new
if it has been created by the server but the client has not yet acknowledged
joining the session. For example, if a server supports only cookie-based sessions
and a client has completely disabled the use of cookies, calls to the getSession()
method ofHttpServletRequest always return new sessions.
▪ public void HttpSession.invalidate()
● This method causes the session to be immediately invalidated. All objects
stored in the session are unbound.
▪ public long HttpSession.getCreationTime()
● This method returns the time at which the session was created, as a long value
that represents the number of milliseconds since the epoch (midnight, January
1, 1970, GMT).
▪ public long HttpSession.getLastAccessedTime()
● This method returns the time at which the client last sent a request associated
with this session, as a long value that represents the number of milliseconds
since the epoch.
● Session Tracking with the Servlet API
The Servlet API has its own built-in support for session tracking. The HttpSession
object provides this
functionality. In this section, I focus on four of the HttpSession's session tracking
methods
● The setAttribute() method binds a name/value pair to store in the current
session. If the name
already exists in the session, it is replaced. The method signature for
setAttribute() is listed as follows:
● public void setAttribute(String name, Object value)
● The getAttribute() method, which is used to get an object that is stored in the
session. The getAttribute() method takes a string representing the name that the
desired object is bound to. Its signature is listed as follows:
● public Object getAttribute(String name)
● The getAttributeNames() method returns an array of the current bound names
stored in the
session.
● public String[ ] getAttributeNames()
● removeAttribute() method. As its name suggests, it removes a binding from
the current session. It takes a string parameter representing the name
associated with the binding. Its method signature is listed as follows:
● public void removeAttribute(String name)
● A Servlet Session Example
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Telegram | youtube | Android App | website | instagram | whatsapp | e-next
For detailed Video Lecture Download The Shikshak Edu App
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);} } }
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);} } }***web.xml**<web-
app>**<servlet> <servlet-name>s1</servlet-name>**<servlet-
class>FirstServlet</servlet-class>**</servlet> <servlet-mapping>**<servlet-
name>s1</servlet-name>**<url-pattern>/servlet1</url-pattern>**</servlet-
mapping > <servlet>**<servlet-name>s2</servlet-name>**<servlet-
class>SecondServlet</servlet-class> </servlet>**<servlet-mapping>**<servlet-
name>s2</servlet-name>**<url pattern>/servlet2</url-pattern>**</servlet-
mapping> **</web-app>
4 Explain about the file uploading feature of a servlet. (NOV 2018)
Which points are important while uploading a file? (APR 2019)
Explain the following wrt. working with files in Servlet. (NOV 2019)
i) @MultipartConfigure ii).fileSizeThreshold iii) location iv) maxFileSize v)
Which things needs to be carefully checked and understood while writing file
uploading code in servlet?
1. http://commons.apache.org/proper/commons-io/download_io.cgi
(commons-io-x.x.jar )
2.http://commons.apache.org/proper/commonsfileupload/download_fileuploa
d.cgi (commons- fileupload.x.x.jar)
3. needs to be carefully checked and understood
● The form method attribute should be set to POST method and GET method
can not be used
● The form enctype attribute should be set to multipart/form-data.
● The form action attribute should be set to a servlet file which would handle
file uploading at backend server. Following example is using UploadServlet
servlet to upload file.
● To upload a single file you should use a single <input .../> tag with attribute
type="file". To allow multiple files uploading, include more than one input tags
with different values for the name attribute. The browser associates a Browse
button with each of them.
1. Following example depends on FileUpload, so make sure you have the latest
version of commons- fileupload.x.x.jar file in your classpath. You can download
it from https://commons.apache.org/fileupload/.
2. FileUpload depends on Commons IO, so make sure you have the latest version
of commons-io- x.x.jar file in your classpath. You can download it from
https://commons.apache.org/io/.
● Uploading Files
public class DiskFileItemFactory extends java.lang.Object implements
FileItemFactory
● The default FileItemFactory implementation. This implementation creates
FileItem instances which keep their content either in memory, for smaller items,
or in a temporary file on disk, for larger items. The size threshold, above which
content will be stored on disk, is configurable, as is the directory in which
temporary files will be created. public class ServletFileUpload extends
FileUpload
● High level API for processing file uploads.
● This class handles multiple files per single HTML widget, sent using
multipart/mixed encoding type, as specified by RFC 1867. Use
parseRequest(HttpServletRequest) to acquire a list of FileItems associated with a
given HTML widget.
● How the data for individual parts is stored is determined by the factory used
to createthem;
a given part may be in memory, on disk, or somewhere else.
● methods of ServletFileUpload
o public static final boolean isMultipartContent(HttpServletRequest request)
▪ Utility method that determines whether the request contains multipart
content.
o public List<FileItem> parseRequest(HttpServletRequest request) throws
FileUploadException
▪ Processes an RFC 1867 compliant multipart/form-data stream.
● Creating an Upload File Application
1. Html file(fileupload.html)
2. servletfile (fileupload.java)
note : add jar files as explained in classroom / or configure maven and web.xml
fileupload.html
<html>
<body>
<form action="fileupload" method="post" enctype = "multipart/form-data">
Telegram | youtube | Android App | website | instagram | whatsapp | e-next
For detailed Video Lecture Download The Shikshak Edu App
<input type="file" name="fiup">
<input type="submit">
</form>
</body>
</html>
fileupload.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class fileupload extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse
response)
throws ServletException, IOException {
// refer https://commons.apache.org/proper/commons-fileupload/using.html
DiskFileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
File f1 = new File("f:\\testupload\\"+fi.getName());
fi.write(f1);
}
}
(response.getWriter()).print("Done");
}
catch(Exception ex)
{
System.out.println("oops check log for exception "+ex);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}
}
another way
javax.servlet.annotation.MultipartConfig is used to indicate that the servlet on
which it is declared expects requests to made using the multipart/form-data
MIME type @MultipartConfig
● A servlet can be annotated with ©MultipartConfig in order to handle
multipart/form-data requests which contain file upload data.
● Servlets annotated with @MultipartConfig may retrieve the Part components
of agiven multipart/form-data request by calling getPart() or getParts()
● @MultipartConfig annotation supports the following optional attributes:
fileSizeThreshold
● The fileSizeThreshold attribute holds the file size in bytes after which the file
will be temporarily stored on disk.
● The default size is 0 bytes. location
● The location attribute holds an absolute path to a directory on the file system.
● The location attribute does not support a path relative to the application
context. this location is used to store file temporarily while the parts are
processed on when the size of the file exceeds the specified fileSizeThreshold.
● The default location is "" maxFileSize
● the maxFileSize attribute holds the maximum size allowed for multipart/form-
data request, in bytes
● The default size is unlimited. maxRequestSize
● the maxRequestSize attribute holds the maximum size allowed for a
multipart/form-data request, in bytes.
● default size is unlimited
5 Write a servlet code to download a file. (NOV 2022)
● Downloading Files servlet file that reads the content of the file and writes it
into the stream to send as a response. For this purpose, we need to inform the
server, so we are setting the content type as APPLICATION/OCTET-STREAM .
● Creating a Download File Application
filedownload.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class filedownload extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// refer https://www.javatpoint.com/example-of-downloading-file-from-the-
server-in-servlet
String downloadas = "mybook.pdf";
String absfilepath = "F:\\testupload\\iot1.pdf";
response.setContentType("APPLICATION/OCTET-STREAM"); // set the MIME
type to be binary
type
response.setHeader("Content-Disposition","attachment; filename=\"" +
downloadas + "\"");
// handles the response based on the content type set in HTTP headers
FileInputStream fileInputStream = new FileInputStream(absfilepath); // Read
the file on the
server
PrintWriter out = response.getWriter();
int i;
while ((i=fileInputStream.read()) != -1) {
out.write(i); }
fileInputStream.close();***out.close();*** }***
***@Override***protected void doGet(HttpServletRequest request,
HttpServletResponse response)**throws ServletException, IOException***
{***processRequest(request, response);*** }**@Override***protected void
doPost(HttpServletRequest request, HttpServletResponse response)***throws
ServletException, IOException {***processRequest(request, response);**}***}
6 What is Non-Blocking I/O? Explain WriteListener and ReadListener performing
in Non- Blocking I/O? Explain the working of Non-Blocking I/O. (NOV 2018)
Explain the working of Non-Blocking I/O. (APR 2019)
Explain using a code snippet the onDataAvailable() and onAIIDataRead()
● Whats non-blocking i/o
Web containers in application servers normally use a server thread per client
request. To develop scalable web applications, you must ensure that threads
associated with client requests are never sitting idle waiting for a blocking
operation to complete. **Asynchronous Processing provides a mechanism to
execute application-specific blocking operations in
a new thread, returning the thread associated with the request immediately to
the container.
Even if you use asynchronous processing for all the application-specific blocking
operations inside your service methods, threads associated with client requests
can be momentarily sitting idle because of input/output considerations.
For example, if a client is submitting a large HTTP POST request over a slow
network connection, the server can read the request faster than the client can
provide it. Using traditional I/O, the container thread associated with this
request would be sometimes sitting idle waiting for the rest of the request. Java
EE provides nonblocking I/O support for servlets and filters when processing
requests in asynchronous mode. The following steps summarize how to use
nonblocking I/O to process requestsand write responses inside service methods.
1. Put the request in asynchronous mode as described in Asynchronous
Processing. 2. Obtain an input stream and/or an output stream from the request
and response objects in the service method.
3. Assign a read listener to the input stream and/or a write listener to the output
stream.
4. Process the request and the response inside the listener's callback methods
NIO allows you to manage multiple channels (network connections or files)
using only a single (or few) threads, but the cost is that parsing the data might
be somewhat more complicated than when reading data from a blocking
stream. If you need to manage thousands of open connections simultanously,
which each only send a little data, for instance a chat server, implementing the
server in NIO is probably an advantage. Similarly, if you need to keep a lot of
open connections to other computers, e.g. in a P2P network, using a single
thread to manage all of your outbound connections might be an advantage. This
one thread, multiple connections design is illustrated in this diagram: Example:
add <async-supported>true</async-supported> in web.xml servlet block
<servlet>
<servlet-name>nonbio</servlet-name>
<servlet-class>nonbio</servlet-class>
<async-supported>true</async-supported>
</servlet>
nonbio.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class nonbio extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
IOException
{
doPost(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
IOException
{
final AsyncContext context = req.startAsync(); // set async
final ServletInputStream sis = req.getInputStream();
sis.setReadListener(new ReadListener() {
byte buffer[] = new byte[4*1024];
StringBuilder sbuilder = new StringBuilder(); // mutable string
public void onDataAvailable() throws IOException
{
System.out.println(".onDataAvailable()");
do {
int length = sis.read(buffer);
Telegram | youtube | Android App | website | instagram | whatsapp | e-next
For detailed Video Lecture Download The Shikshak Edu App
sbuilder.append(new String(buffer, 0, length));
} while(sis.isReady());
System.out.println(sbuilder);
}
public void onAllDataRead() throws IOException
{
System.out.println(".onAllDataRead()");
context.complete(); // it will stop async content and process will stop listening;
}
public void onError(Throwable t)
{
System.out.println(".onError()");
}
});
}
7 Write a servlet program to create a session and display the following: i)
Session ID ii) New or Old iii) CreationTime (NOV 2019)
package session_program;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import javafx.scene.chart.PieChart;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name = "SessionExp", urlPatterns = {"/SessionExp"})
public class SessionExp extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException,
IOException {
resp.getContentType();
PrintWriter printWriter=resp.getWriter();
String name=req.getParameter("name");
HttpSession hs=req.getSession();
hs.setAttribute("name1", name);
String s_id=hs.getId();
//printWriter.print(s_id);//get the session id
Date createTime =new Date(hs.getCreationTime());//get the time and date
session
if(hs.isNew()){ //check the session is new or not
printWriter.print("new session") }
printWriter.print("<html>");
printWriter.print("<body>");
printWriter.print("<h1>"+hs.getAttribute("name1")+"<h1>");
printWriter.print("</body>");
printWriter.print("</html>");
}
}
8 Write a servlet program GradeServlet.java that accepts Grade through radio
buttons from index.html page, if
the string is “A", “B", “C” OR “D”, the program should dispatch the direct to the
Succcss.html page containing
message “Congratulations !!!, You Passed SEM V exam”, else display “Try Again"
and load index.html page in
current servlet. (Make suitable assumptions, Only Write the Servlet Code) (NOV
2019)
HTML code
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="MyServlet" method="post">
<input type="radio" value="A" name="grade">A
<input type="radio" value="B" name="grade">B
<input type="radio" value="C" name="grade">C
<input type="radio" value="C" name="grade">D
<input type="radio" value="others" name="grade">others
<input type="submit" value="SUBMIT">
</form>
</body>
</html>
SERVLET code
package servletsprogram;
import java.io.IOException;
import java.lang.*;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"})
public class MyServlet extends HttpServlet {
String grade;
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException,
IOException {
resp.setContentType("text/html");
Telegram | youtube | Android App | website | instagram | whatsapp | e-next
For detailed Video Lecture Download The Shikshak Edu App
PrintWriter printWriter =resp.getWriter();
try
{
grade =req.getParameter("grade");
}
catch(NullPointerException ex)
{
ex.getMessage();
}
if(grade.equalsIgnoreCase("A")||
grade.equalsIgnoreCase("B")||grade.equalsIgnoreCase("C")||grade.equalsIgnor
eCase("D")){
RequestDispatcher rd=req.getRequestDispatcher("Succcss.html");
rd.forward(req, resp);
} else{
printWriter.print("Try Again");
RequestDispatcher rd=req.getRequestDispatcher("index.html");
rd.include(req, resp);