0% found this document useful (0 votes)
7 views33 pages

Web Tech Pratical

The document contains multiple Java Servlet examples demonstrating various functionalities such as printing 'Hello World', using cookies to track user visits, creating a login page, displaying today's date, and reading client request parameters. It also includes JSP examples for printing 'Hello World', creating checkboxes, performing arithmetic operations, and a KBC quiz game. Each example is structured with HTML and Java code to illustrate the use of Servlets and JSP in web applications.

Uploaded by

angelin272004
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)
7 views33 pages

Web Tech Pratical

The document contains multiple Java Servlet examples demonstrating various functionalities such as printing 'Hello World', using cookies to track user visits, creating a login page, displaying today's date, and reading client request parameters. It also includes JSP examples for printing 'Hello World', creating checkboxes, performing arithmetic operations, and a KBC quiz game. Each example is structured with HTML and Java code to illustrate the use of Servlets and JSP in web applications.

Uploaded by

angelin272004
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/ 33

CREATE SERVLET THAT PRINTS HELLO WORLD

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;

public class NewServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();


out.println("<!DOCTYPE html>");

out.println("<html>");

out.println("<head>");

out.println("<title>Servlet NewServlet</title>");

out.println("</head>");

out.println("<body>");

out.println("<h1><center>SERVLET PROGRAM TO PRINT </center></h1>");


out.println("<h1><center>HELLO WORLD </center></h1>");

out.println("</body>");

out.println("</html>");

}
OUTPUT:
CREATE SERVLET THAT USES COOKIES TO STORE THE NUMBER

OF TIMES A USER HAS VISITED THE SERVLET

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;
import java.io.IOException;
@WebServlet(name = "NewServlet", urlPatterns = "/NewServlet")
public class NewServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
Cookie visitCookie = null;
for (Cookie cookie : cookies != null ? cookies : new Cookie[0]) {
if (cookie.getName().equals("visitCount")) {
visitCookie = cookie;
break;
}
}
int visitCount = (visitCookie != null) ? Integer.parseInt(visitCookie.getValue()) + 1 : 1;
visitCookie = (visitCookie != null) ? visitCookie : new Cookie("visitCount",
String.valueOf(visitCount));
visitCookie.setValue(String.valueOf(visitCount));
visitCookie.setMaxAge(60 * 60 * 24 * 365);
response.addCookie(visitCookie);
response.setContentType("text/html");
response.getWriter().println("<h1>You have visited this page " + visitCount + "
times.</h1>");
}
}
OUTPUT:
LOGIN PAGE USING SERVLET

Index.html:

<html>

<head>

<title>LOGIN</title>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body><center><h1>LOGIN PAGE USING SERVLET</h1>

<form action="http://localhost:8080/WebApplication2/NewServlet">
Enter userId<input type="text" name="txtId"><br><br>

Enter Password<input type="password" name="txtPass"><br><br>

<input type="Reset">
<input type="submit" value="click to login">

</form></center>

</body>

</html>

NewServlet.java:

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;

public class NewServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html");

PrintWriter pw = response.getWriter();

pw.println("<!DOCTYPE html>");

pw.println("<html>");
pw.println("<head>");

pw.println("<title>Servlet Login</title>");

pw.println("</head>");

pw.println("<body bgcolor='white'>");

String uname = request.getParameter("txtId");

String upass = request.getParameter("txtPass");

if (uname == null || upass == null) {


pw.println("<h1><center> provide both username and password.</center></h1>");
} else {

if (uname.equals("Swetha") && upass.equals("12345")) {

pw.println("<h1><center>HELLO! " + uname + "</center></h1>");

} else if (uname.equals("Anna") && upass.equals("123")) {

pw.println("<h1><center>Welcome " + uname + "</center></h1>");

} else {

pw.println("<h1><center>Login failed!</center></h1>");
}

pw.println("</body>");

pw.println("</html>");

}
OUTPUT:
SERVLET PROGRAM TO PRINT TODAY’S DATE

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws
ServletException, IOException
{
PrintWriter pw = response.getWriter();
Date today = new Date();
pw.println("<html>");
pw.println("<body bgcolor='pink'>");
pw.println("<title> Todays date </title>");
pw.println("<h1><center>SERVLET PROGRAM TO PRINT TODAY'S
DATE</center></h1>");
pw.println("<h2><center>" + today + "</center></h2></html>");
}
}
OUTPUT:
SIMPLE SERVLET

NewServlet.java:

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;

public class NewServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

try (PrintWriter out = response.getWriter()) {


out.println("<!DOCTYPE html>");

out.println("<html>");

out.println("<head>");

out.println("<title>Servlet NewServlet</title>");

out.println("</head>");

out.println("<body>");

out.println("<h1>Servlet NewServlet at " + request.getContextPath() + "</h1>");

out.println("</body>");
out.println("</html>");

}
OUTPUT:
SERVLET PROGRAM TO READ THE CLIENT REQUEST
PARAMETERS

Index.html:
<!DOCTYPE html>

<html>

<head>

<title>Servlet Request Example</title>

</head>

<body>

<h2>Enter Your Details</h2>


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

Name: <input type="text" name="username"><br><br>

Email: <input type="email" name="email"><br><br>

<input type="submit" value="Submit">

</form>

</body>

</html>

RequestServlet.java:

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(name = "RequestServlet", urlPatterns = {"/RequestServlet"})


public class RequestServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {


// Redirect GET requests to index.html

response.sendRedirect("index.html");

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Read form parameters

String name = request.getParameter("username");

String email = request.getParameter("email");

// Display response

out.println("<html><body>");
out.println("<h2>Received Data</h2>");

out.println("Name: " + name + "<br>");

out.println("Email: " + email + "<br>");

out.println("</body></html>");

}
OUTPUT:
SERVLET PROGRAM TO DISPLAY COOKIE ID

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CookieServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

Cookie[] cookies = request.getCookies();

out.println("<html><body>");
out.println("<h2>Cookie ID Display</h2>");

if (cookies != null) {
boolean found = false;
for (Cookie cookie : cookies) {
if (cookie.getName().equals("cookieID")) {
out.println("<p>Cookie ID: " + cookie.getValue() + "</p>");
found = true;
break;
}
}

if (!found) {
out.println("<p>No 'cookieID' cookie found.</p>");
}
} else {
out.println("<p>No cookies present.</p>");
}
out.println("</body></html>");
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response); // For simplicity, reuse the GET logic
}
}
OUTPUT:
SERVLET PROGRAM TO GENERATE PLAIN TEXT

import java.io.*;

import javax.servlet.*;

import javax.servlet.annotation.*;

import javax.servlet.http.*;

@WebServlet("/hello")

public class HelloWorldServlet extends HttpServlet {


@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

response.setContentType("text/plain");

PrintWriter out = response.getWriter();

out.println("Hello, World!");

}
OUTPUT :-
JSP PROGRAM TO PRINT HELLO WORLD

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<title>JSP Page</title>

</head>

<body bgcolor="pink">
<%out.println("<h1><center>JSP PROGRAM TO PRINT HELLO
WORLD</center><h1>");%>

<%out.println("<h1><center>HELLO WORLD!</center></h1>");%>

</body>

</html>
OUTPUT :-
JSP PROGRAM TO CREATE CHECK BOXES

<%@ page contentType="text/html; charset=ISO-8859-1" language="java" %>

<html>

<head>

<title>Checkbox</title>

</head>

<body>

<h2>Choose Your Favorite Fruits</h2>

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

<label>

<input type="checkbox" name="fruit" value="Apple"> Apple

</label><br>

<label>

<input type="checkbox" name="fruit" value="Banana"> Banana

</label><br>

<label>

<input type="checkbox" name="fruit" value="Orange"> Orange

</label><br>

<label>

<input type="checkbox" name="fruit" value="Grapes"> Grapes

</label><br>

<label>

<input type="checkbox" name="fruit" value="Mango"> Mango

</label><br><br>

<input type="submit" value="Submit">

</form>
<%

String[] selectedFruits = request.getParameterValues("fruit");

if (selectedFruits != null) { out.println("<h3>You have

selected:</h3>"); for (String fruit : selectedFruits) {

out.println(fruit + "<br>");

%>

</body>

</html>
OUTPUT :-
JSP PROGRAM TO PERFORM BASIC ARITHMETIC FUNCTIONS

arithmetric.jsp

<html>
<head>
<title>Arithmetic functions</title>

<h1><center> Arithmetic Functions</center></h1>


</head>
<body>
<center>
<form action="Calc.jsp" method="get">
<label for="num1"><b>Number 1</b></label>
<input type="text" name="num1"><br><br>

<label for="num2"><b>Number 2</b></label>


<input type="text" name="num2"><br><br>

<input type="checkbox" name="operations" value="Add"> Addition <br>


<input type="checkbox" name="operations" value="Sub"> Subtraction <br>
<input type="checkbox" name="operations" value="Mul"> Multiplication <br>
<input type="checkbox" name="operations" value="Div"> Division <br><br>

<input type="submit" value="Submit">


</form>
</center>
</body>
</html>
Calc.jsp

<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-


8"%>
<!DOCTYPE html>
<html>
<head>
<title>Arithmetic Functions</title>

</head>
<body>
<%
try {
double num1 = Double.parseDouble(request.getParameter("num1"));
double num2 = Double.parseDouble(request.getParameter("num2"));
String[] operations = request.getParameterValues("operations");

if (operations != null) {
for (String operation : operations) {

double result = 0;
String message = "";
if (operation.equals("Add")) {
result = num1 + num2;
message = "Addition of two numbers: ";
} else if (operation.equals("Sub")) {
result = num1 - num2;
message = "Subtraction of two numbers: ";
} else if (operation.equals("Mul")) {
result = num1 * num2;
message = "Multiplication of two numbers: ";
} else if (operation.equals("Div")) {
if (num2 == 0) {
message = "Error: Division by zero is not allowed.";
} else {
result = num1 / num2;
message = "Division of two numbers: ";
}

}
out.println(message + result + "<br>");
}
} else {
out.println("No operations selected.");
}
} catch (NumberFormatException e) {
out.println("Error: Invalid input. Please enter valid numbers.");
}
%>

</body>
</html>
OUTPUT :-
KBC CREATE THE SERVLET FOR DEMO OF KBC GAME

newjsp.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>

<!DOCTYPE html>

<html>

<head>

<title>KBC Quiz</title>

</head>

<body>
<h2>Kaun Banega Crorepati Quiz</h2>

<%

String[] questions = {"What is the capital of India?", "Who wrote 'Hamlet'?", "What is
the square root of 64?"};

String[][] options = {{"Mumbai", "Delhi", "Kolkata", "Chennai"}, {"Shakespeare",


"Milton", "Wordsworth", "Keats"}, {"6", "7", "8", "9"}};

int[] answers = {1, 0, 2};

if (request.getMethod().equalsIgnoreCase("POST")) {

int score = 0;

for (int i = 0; i < questions.length; i++) {


String answer = request.getParameter("q" + i);
if (answer != null && Integer.parseInt(answer) == answers[i]) {

score++;

out.println("<h3>Your Score: " + score + " out of " + questions.length + "</h3>");

out.println("<a href='http://localhost:8080/WebApplication5/newjsp.jsp'>Play
Again</a>");
} else {

%>

<form method="post">

<% for (int i = 0; i < questions.length; i++) { %>


<p><%= questions[i] %></p>

<% for (int j = 0; j < options[i].length; j++) { %>

<input type="radio" name="q<%= i %>" value="<%= j %>"> <%= options[i][j]


%><br>

<% } %>

<% } %>

<br>

<input type="submit" value="Submit">

</form>

<% } %>
</body>

</html>
OUTPUT:

You might also like