It is common in web applications to pass data or parameters from one to another page. To retrieve the values of various elements in a HTML form or from another page, we can use the following methods which are available in HttpServletRequest object:
- String getParameter(String name)
- Enumeration getParameterNames()
- String[] getParamterValues(String name)
Following example demonstrates retrieving data from a login page to a servlet:
login.html
<!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=ISO-8859-1">
<title>Login</title>
</head>
<body>
<form action="auth.html" method="get">
Username: <input type="text" name="txtuser" /><br />
Password: <input type="password" name="txtpass" /><br />
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>Authenticate</servlet-name>
<servlet-class>Authenticate</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Authenticate</servlet-name>
<url-pattern>/auth.html</url-pattern>
</servlet-mapping>
</web-app>
Authenticate.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Authenticate
*/
public class Authenticate extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Authenticate() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("txtuser");
String password = request.getParameter("txtpass");
if(username.equals("vishnu") && password.equals("college"))
{
response.getWriter().print("Valid user!");
}
else
{
response.getWriter().print("Bad username or password");
}
}
}
In the above example we are retrieving the data from login page using the getParameter() method.
Video: Retrieving Parameters
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply