0% found this document useful (0 votes)
15 views15 pages

Javaservlet - Assignment (Rajat)

The document provides code examples for creating various servlet applications, including a simple calculator, a login page, and session management. It covers functionalities such as cookie usage for visit counting, password validation, and auto-refreshing pages. Additionally, it includes a registration form with validation rules for user inputs, demonstrating the interaction between HTML forms and servlets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views15 pages

Javaservlet - Assignment (Rajat)

The document provides code examples for creating various servlet applications, including a simple calculator, a login page, and session management. It covers functionalities such as cookie usage for visit counting, password validation, and auto-refreshing pages. Additionally, it includes a registration form with validation rules for user inputs, demonstrating the interaction between HTML forms and servlets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

1

1. Create a simple calculator application using servlet.


Code:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Create a simple calculator application using servlet.</title>
</head>
<body>
<form action="add" method="get">
<label for="num1">Number 1 : </label>
<input type="text" name="num1" id="num1">
<br>
<br>
<label for="num2">Number 2 : </label>
<input type="text" name="num2" id="num2">
<br>
<br>
<button type="submit">Result</button>
</form>
</body>
</html>

package addServlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class addServlet extends HttpServlet {


public void service(HttpServletRequest req,HttpServletResponse res)
throws IOException
{
int num1=Integer.parseInt(req.getParameter("num1"));
int num2=Integer.parseInt(req.getParameter("num2"));
int result=num1+num2;
PrintWriter out=res.getWriter();
out.println(num1+" + "+num2+" = "+result);
}
}
2

Output:

2. Create a servlet for a login page. If the username and password are correct, then
it says message “Hello” else a message “login failed”.
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Create a servlet for a login page</title>
</head>
<body>
<form action="add" method="get">
<label for="username">Username : </label>
<input type="text" name="username" id="username">
<br>
<br>
<label for="password">Password : </label>
<input type="password" name="password" id="password">
<br>
<br>
<button type="submit">Login</button>
</form>
</body>
</html>

package addServlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class addServlet extends HttpServlet {


public void service(HttpServletRequest req,HttpServletResponse res)
3

throws IOException
{

PrintWriter out=res.getWriter();

String username=req.getParameter("username");
String password=req.getParameter("password");
String savePassword="1234";
String saveUsername="admin";

if(username.equals(saveUsername) && password.equals(savePassword) ) {

out.println("Hello Admin");
}else {
out.println("Login Failed");
}

}
}

Output:

3. Using Request Dispatcher Interface create a Servlet which will validate the
password entered by the user, if the user has entered "Servlet" as password, then
he/she will be forwarded to Welcome Servlet else the user will stay on the
index.html page and an error message will be displayed.
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
4

<form action="AuthServlet" method="post">


<label for="username">User Name : </label>
<input type="text" name="username" id="username">
<br>
<br>
<label for="password">Password : </label>
<input type="password" name="password" id="password">
<br>
<br>
<button type="submit">Login</button>
</form>
</body>
</body>
</html>

AuthServlet.java
package AuthServlet;

import java.io.IOException;
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("/Auth")
public class AuthServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException{
String password = req.getParameter("password");
String prePassword="Servlet";
if(prePassword.equals(password)) {
RequestDispatcher dispatcher = req.getRequestDispatcher("WelcomeServlet");
dispatcher.forward(req, res);
}else {
PrintWriter out=res.getWriter();
out.println("<h1>Invalid Password</h1>");
RequestDispatcher dispatcher = req.getRequestDispatcher("/index.html");
dispatcher.include(req, res);
}
}
}
5

WelcomeServlet.java
package WelcomeServlet;

import java.io.IOException;
import java.io.PrintWriter;

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("/Welcome")
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
IOException{
PrintWriter out=res.getWriter();
res.setContentType("text/html");
out.println("<h1>Welcome Servlet</h1>");
}

Output:

4. Create a servlet that uses Cookies to store the number of times a user has visited
servlet.
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
6

</body>
</html>

package VisitedServlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/VisitedServlet")
public class VisitedServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();

Cookie[] cookies = req.getCookies();


Cookie visitCookie = null;
int visitCount = 0;

if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("visitCount")) {
visitCookie = cookie;
visitCount = Integer.parseInt(cookie.getValue());
break;
}
}
}

if (visitCookie == null) {
visitCount = 1;
} else {
visitCount++;
}

visitCookie = new Cookie("visitCount", Integer.toString(visitCount));


visitCookie.setMaxAge(24 * 60 * 60);
res.addCookie(visitCookie);

out.println("<html><body>");
out.println("<h1>Visit Count: " + visitCount + "</h1>");
out.println("</body></html>");
}
}
7

Output:

5. Create a servlet demonstrating the use of session creation and destruction. Also
check whether the user has visited this page first time or has visited earlier also
using sessions.
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

</body>
</html>

package SessionServlet;

import java.io.IOException;
import java.io.PrintWriter;

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("/")
public class SessionServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException{
res.setContentType("text/html");
8

PrintWriter out = res.getWriter();


HttpSession session=req.getSession(true);
Boolean isVisited= (Boolean) session.getAttribute("isVisited");
if(isVisited==null) {
session.setAttribute("isVisited", false);
out.println("<html><body>");
out.println("<h1>Welcome!</h1>");
out.print("<a href='SessionServlet?killSession=ok'><button>Kill
session</button></a>");
out.println(" ");
out.print("<a href='SessionServlet'><button>Refresh</button></a>");
out.println("</body></html>");
}else {
out.println("<html><body>");
out.println("<h1>Already Visited</h1>");
out.print("<a href='SessionServlet?killSession=ok'><button>Kill
session</button></a>");
out.println(" ");
out.print("<a href='SessionServlet'><button>Refresh</button></a>");
out.println("</body></html>");
}
String killSession = req.getParameter("killSession");
if("ok".equals(killSession)) {
session.invalidate();
out.println("<html><body>");
out.println("<h1>Session end</h1>");
out.println("<a href='SessionServlet'>click here</a>");
out.println("</body></html>");
}
}
}

Output:

7. Write a servlet application to print the current date and time.


Code:
<!DOCTYPE html>
9

<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="CurrentDateTime">
<button>Click here</button>
</a>
</body>
</html>

package CurrentDateTime;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

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("/CurrentDateTime")
public class CurrentDateTime extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
Date now = new Date();
PrintWriter out = res.getWriter();
out.println("<html><body>");
out.println("<h1>Current Date and Time</h1>");
out.println("<p>The current date and time is: " + now + "</p>");
out.println("</body></html>");
}

Output:
10

8. Write a servlet application to establish communication between html and servlet


page using hyperlink.
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<nav>
<a href="DemoServlet">
<button>Home</button>
</a>
<a href="DemoServlet?page=about">
<button>About</button>
</a>
<a href="DemoServlet?page=contact">
<button>Contact</button>
</a>
</nav>
</body>
</html>

package DemoServlet;

import java.io.IOException;
import java.io.PrintWriter;

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("/DemoServlet")
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String page=req.getParameter("page");
out.println("<html><body>");
if("about".equals(page)) {
out.println("<h1>About Page</h1>");
}else if("contact".equals(page)) {
out.println("<h1>Contact Page</h1>");
11

}
else {
out.println("<h1>Home Page</h1>");
}
out.println("</body></html>");
}
}

Output:

9. Write an application to auto refresh a page in servlet.


Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
</body>
</html>

package AutoRefresh;

import java.io.IOException;
import java.io.PrintWriter;

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("/")
public class AutoRefresh extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html;charset=UTF-8");
12

PrintWriter out = res.getWriter();


out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Auto Refresh</title>");
res.setHeader("refresh","5;url=reloadedpage");
out.println("</head>");
out.println("<body>");
out.println("This webpage will be reloaded to a new page in 5 seconds ...");
out.println("</body>");
out.println("</html>");
}
}

Output:

10. For this assignment you have to develop a simple servlet application. Construct
a simple HTML form for registration to an email service. The fields in the form are 1.
First name 2. Middle name 3. Last name 4. Desired login 5. Password 6. Confirm
Password 7. Location 8. Education 9. Phone number The fields 1,3,4,5 and 6 are
compulsory for registration others are optional. There are some restrictions on the
fields 1. The First name, middle name and last name fields should contain only
alphabets 2. Passwords should contain alphabets and alteast one numbers and
special character. Passwords should contain atleast 6 characters On pressing the
submit button the form should pass the data to a servlet which check the
restrictions and returns a successful registration message in case all restrictions are
fulfilled otherwise display back a appropriate error message. The checking of
restrictions should be done on servlet side not in the form itself. Also, use of Java
script is not allowed.

Code:
13

<!DOCTYPE html>
<html>

<head>
<meta charset="ISO-8859-1" />
<title>Insert title here</title>
</head>

<body>
<form action="Registration">
<label for="firstName">First Name : </label>
<input type="text" name="firstName" id="firstName" placeholder="Enter Your First Name
.." />
<br />
<br />
<label for="MiddleName">Middle Name : </label>
<input type="text" name="middleName" id="MiddleName" placeholder="Enter Your Middle
Name .." />
<br />
<br />
<label for="lastName">Last Name : </label>
<input type="text" name="lastName" id="lastName" placeholder="Enter Your Last Name .."
/>
<br />
<br />
<label for="Password">Password : </label>
<input type="password" name="password" id="Password" placeholder="Enter Your Password
.." />
<br />
<br />
<label for="confirmPassword">Confirm Password : </label>
<input type="password" name="confirmPassword" id="confirmPassword" placeholder="Enter
Your Confirm Password .." />
<br />
<br />
<label for="Location">Location : </label>
<textarea type="password" name="location" id="Location" placeholder="Enter Your
Location .."></textarea>
<br />
<br />
<label for="Education">Education : </label>
<input type="text" name="education" id="Education" placeholder="Enter Your Education
.." />
<br />
<br />
<label for="phoneNumber">Phone number : </label>
<input type="text" name="phoneNumber" id="phoneNumber" placeholder="Enter Your Phone
number .." />
<br />
<br />
<button type="submit">Register</button>
</form>
14

</body>

</html>

package Registration;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;

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("/Registration")
public class Registration extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String firstName = req.getParameter("firstName");
String middleName = req.getParameter("middleName");
String lastName = req.getParameter("lastName");
String password = req.getParameter("password");
String confirmPassword = req.getParameter("confirmPassword");
String location = req.getParameter("location");
String education = req.getParameter("education");
String phoneNumber = req.getParameter("phoneNumber");

res.setContentType("text/html");
PrintWriter out = res.getWriter();
String error="";
Boolean valid = true;
if (firstName == null || firstName.trim().isEmpty() ||
middleName == null || middleName.trim().isEmpty() ||
lastName == null || lastName.trim().isEmpty() ||
password == null || password.trim().isEmpty() ||
confirmPassword == null || confirmPassword.trim().isEmpty() ||
location == null || location.trim().isEmpty() ||
education == null || education.trim().isEmpty() ||
phoneNumber == null || education.trim().isEmpty()) {
valid=false;
error="All Field required";
}
if(!Pattern.matches("[a-zA-Z]+",firstName)) {
valid=false;
error="First name should only contain Alphabet <br/>";
}
if(!Pattern.matches("[a-zA-Z]+",middleName)) {
valid=false;
15

error="Middle name should only contain Alphabet <br/>";


}
if(!Pattern.matches("[a-zA-Z]+",lastName)) {
valid=false;
error="Last name should only contain Alphabet <br/>";
}

if(!Pattern.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-
Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$",password) || password.length() < 6)
{
valid=false;
error="Password must be at least 6 characters long and contain alphabets,
numbers, and special characters.<br>";

}
if(!password.equals(confirmPassword)) {
valid=false;
error="Passwords do not match.<br>";
}
if (valid) {
out.println("<html><body>");
out.println("<h2>Registration Successful</h2>");
out.println("</body></html>");
} else {
out.println("<html><body>");
out.println("<h2>Registration Failed</h2>");
out.println(error);
out.println("</body></html>");
}
}
}

Output:

You might also like