31.
Write a java servlet which accepts two numbers from an HTML form and displays their sum
and diffference on another page.
Html
<form action="CalcServlet" method="get">
Enter First Number: <input type="text" name="num1"><br>
Enter Second Number: <input type="text" name="num2"><br>
<input type="submit" value="Calculate">
</form>
CalcServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CalcServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
{
int a = Integer.parseInt(req.getParameter("num1"));
int b = Integer.parseInt(req.getParameter("num2"));
int sum = a + b;
int diff = a - b;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("Sum: " + sum + "<br>Difference: " + diff);
32. Write a servlet displaying the current date and time.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateTimeServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
{
Date date = new Date();
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("Current Date and Time: " + date.toString());
33. Write a program to add two numbers using JSP.
Html
<form action="add.jsp" method="post">
Number 1: <input type="text" name="num1"><br>
Number 2: <input type="text" name="num2"><br>
<input type="submit" value="Add">
</form>
Add.jsp
<%
int a = Integer.parseInt(request.getParameter("num1"));
int b = Integer.parseInt(request.getParameter("num2"));
int sum = a + b;
%>
<h2>Sum = <%= sum %></h2>
34. Create a JSP page to accept a number from an user and display it in words: Example:
123 – One Two Three.
Html
<form action="numberWords.jsp" method="post">
Enter Number: <input type="text" name="num">
<input type="submit" value="Show in Words">
</form>
numberWords.jsp
<%
String num = request.getParameter("num");
String[] words = {"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
%>
<h2>Number in Words:</h2>
<%
for(char ch : num.toCharArray()) {
if(Character.isDigit(ch)) {
out.print(words[Character.getNumericValue(ch)] + " ");
} else {
out.print("? ");
%>
35. Write a JSP program to perform Arithmetic operations such as Addition, Subtraction,
Multiplication and Division. Design a HTML to accept two numbers in text box and radio
buttons to display operations. On submit display result as per the selected operation on next
page using JSP.
Html
<form action="arithmetic.jsp" method="post">
Number 1: <input type="text" name="num1"><br>
Number 2: <input type="text" name="num2"><br>
Operation:<br>
<input type="radio" name="op" value="add">Add<br>
<input type="radio" name="op" value="sub">Subtract<br>
<input type="radio" name="op" value="mul">Multiply<br>
<input type="radio" name="op" value="div">Divide<br>
<input type="submit" value="Calculate">
</form>
Arithmetic.jsp
<%
int a = Integer.parseInt(request.getParameter("num1"));
int b = Integer.parseInt(request.getParameter("num2"));
String op = request.getParameter("op");
int result = 0;
switch(op) {
case "add": result = a + b; break;
case "sub": result = a - b; break;
case "mul": result = a * b; break;
case "div": result = b != 0 ? a / b : 0; break;
%>
<h2>Result: <%= result %></h2>
36. Create a JSP page, which accepts user name in a text box and greets the user
according to the time on server side.
Example: If user name is Admin Output: If it is morning then display message in red color as,
Good morning Admin Today’s date: dd/mm/yyyy format Current time: hh:mm:ss format If it is
afternoon then display message in green color as, Good afternoon Admin Today’s date :
dd/mm/yyyy format Current time : hh:mm:ss format If it is evening then display message in
blue color as, Good evening Admin Today’s date: dd/mm/yyyy format Current time:
hh:mm:ss format (Hint: To display date and time use GregorianCalendar and Calendar class)
Html
<form action="greet.jsp" method="post">
Enter your name: <input type="text" name="username">
<input type="submit" value="Greet Me">
</form>
Greet.jsp
<%@ page import="java.util.*, java.text.*" %>
<%
String name = request.getParameter("username");
Calendar cal = new GregorianCalendar();
int hour = cal.get(Calendar.HOUR_OF_DAY);
String greeting = "";
String color = "";
if (hour < 12) {
greeting = "Good Morning";
color = "red";
} else if (hour < 17) {
greeting = "Good Afternoon";
color = "green";
} else {
greeting = "Good Evening";
color = "blue";
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
%>
<h2 style="color:<%= color %>;">
<%= greeting %> <%= name %><br>
Today’s date: <%= dateFormat.format(cal.getTime()) %><br>
Current time: <%= timeFormat.format(cal.getTime()) %>
</h2
37. Write a JSP program to display number of times user has visited the page. (Use cookies)
<%
int count = 1;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
if (c.getName().equals("visitCount")) {
count = Integer.parseInt(c.getValue()) + 1;
Cookie visitCookie = new Cookie("visitCount", Integer.toString(count));
visitCookie.setMaxAge(60 * 60 * 24 * 365); // 1 year
response.addCookie(visitCookie);
%>
<h2>You have visited this page <%= count %> times.</h2>
38. Create a simple Java Servlet that returns a "Hello, World!" message when accesses by a
web browser.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorldServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello, World!</h1>");
}
}
39. Write a JSP page that uses an expression to display the sum of two numbers entered by
the user through an HTML form
Html
<form action="sum.jsp" method="post">
Number 1: <input type="text" name="a"><br>
Number 2: <input type="text" name="b"><br>
<input type="submit" value="Get Sum">
</form>
Sum.jsp
<%
int a = Integer.parseInt(request.getParameter("a"));
int b = Integer.parseInt(request.getParameter("b"));
%>
<h2>Sum: <%= a + b %></h2>
40. Write a JSP page that connects to a MySQL database and retrieves a list of records from
a table (e.g., "Students").
Sql
CREATE TABLE Students (
id INT PRIMARY KEY,
name VARCHAR(100),
percentage FLOAT
);
studentList.jsp
<%@ page import="java.sql.*" %>
<%
String url = "jdbc:mysql://localhost:3306/your_db";
String user = "root";
String pass = "your_password";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, user, pass);
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM Students");
%>
<table border="1">
<tr><th>ID</th><th>Name</th><th>Percentage</th></tr>
<%
while(rs.next()) {
%>
<tr>
<td><%= rs.getInt("id") %></td>
<td><%= rs.getString("name") %></td>
<td><%= rs.getFloat("percentage") %></td>
</tr>
<%
%>
</table>
<%
} catch(Exception e) {
out.println("Database error: " + e.getMessage());
} finally {
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(conn != null) conn.close();
%>
41. Write a Spring MVC program for subtraction of two numbers.
42. Write a Spring MVC program for multiplication of two numbers.
Both in one program
SpringMVC_Calc/
├── src/
│ └── com.example.controller/
│ └── CalcController.java
├── WebContent/
│ ├── WEB-INF/
│ │ ├── views/
│ │ │ ├── calcForm.jsp
│ │ │ └── result.jsp
│ │ └── web.xml
│ └── index.jsp
├── applicationContext.xml
Web.xml
<web-app>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.example.controller"/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
index.jsp
<jsp:forward page="calcForm.jsp" />
calcForm.jsp
<h2>Spring MVC Calculator</h2>
<form action="calculate" method="post">
Enter First Number: <input type="text" name="num1"><br>
Enter Second Number: <input type="text" name="num2"><br><br>
Select Operation:
<select name="operation">
<option value="sub">Subtraction</option>
<option value="mul">Multiplication</option>
</select><br><br>
<input type="submit" value="Calculate">
</form>
Result.jsp
<h2>Result:</h2>
<p><strong><%= request.getAttribute("result") %></strong></p>
<a href="calcForm.jsp">Try Again</a>
CalcController.java
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
@Controller
public class CalcController {
@RequestMapping(value = "/calculate", method = RequestMethod.POST)
public String calculate(HttpServletRequest request) {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
String op = request.getParameter("operation");
int result = 0;
String output = "";
if (op.equals("sub")) {
result = num1 - num2;
output = "Subtraction: " + result;
} else if (op.equals("mul")) {
result = num1 * num2;
output = "Multiplication: " + result;
}
request.setAttribute("result", output);
return "result";
}
}