0% found this document useful (0 votes)
2 views

advanced java program

The document contains several Java and JSP programs demonstrating various functionalities such as addition of two numbers using a servlet, checking if a number is prime, creating and reading cookies, displaying current date and time, counting page visits using HttpSession, generating Fibonacci series, and storing book information in a database using Hibernate annotations. Each section includes the relevant Java or JSP code along with HTML forms for user input. The document serves as a comprehensive guide for implementing basic web applications using Java technologies.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

advanced java program

The document contains several Java and JSP programs demonstrating various functionalities such as addition of two numbers using a servlet, checking if a number is prime, creating and reading cookies, displaying current date and time, counting page visits using HttpSession, generating Fibonacci series, and storing book information in a database using Hibernate annotations. Each section includes the relevant Java or JSP code along with HTML forms for user input. The document serves as a comprehensive guide for implementing basic web applications using Java technologies.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

1)Write a java servlet program of addition of two

numbers.
my java file is as follows-----

package servletjsp;

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)
{
int i=Integer.parseInt(req.getParameter("num1"));
int j=Integer.parseInt(req.getParameter("num2"));

int k=i+j;
System.out.println("the result is "+ k);
}
}
My html file is as follows----

<!DOCTYPE html>
<html>
<body>
<form action="add">
Enter 1st number: <input type="text" name=num1><br>
Enter 2nd number: <input type="text" name=num1><br>
<input type="submit">
</form>
</body>
</html>
my web.xml file is as follows----

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID"
version="3.1">
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>servletjsp.AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
</web-app>

2)Write a jsp program to print whether number is prime or not

source file name: Primeno.html

<html>

<head>

<title>Prime no JSP program</title>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width">

</head>

<body>

<form action="http://localhost:8080/JspPrograms/PrimeNumber.jsp" method="post">

enter any no:

<input type="text" name="t1" >

<br>

<input type="submit" >

</form>

</body>

</html>
output:

source file name: PrimeNumber.jsp

<%
int n=Integer.parseInt(request.getParameter("t1"));

out.println(" given number is: "+n);

int d=2;

while(d<n)

if(n%d==0)

out.println("<br> "+n+" is not Prime no.");

break;

else

d++;

if(n==d)

out.println("<br>"+n+" is Prime no.");

%>
output:

3)Write a program to create cookie in java servlet.


package com.example;

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

@WebServlet("/CreateCookieServlet")
public class CreateCookieServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Create a cookie
String cookieName = "user";
String cookieValue = "JohnDoe"; // Example value
Cookie cookie = new Cookie(cookieName, cookieValue);

// Set the cookie's maximum age (e.g., 1 day)


cookie.setMaxAge(24 * 60 * 60);

// Add the cookie to the response


response.addCookie(cookie);

// Notify the user that the cookie has been created


out.println("<html><body>");
out.println("<h1>Cookie Created</h1>");
out.println("<p>A cookie named <strong>" + cookieName + "</strong> with value <strong>" +
cookieValue + "</strong> has been created.</p>");
out.println("<p>It will expire in 1 day.</p>");
out.println("<a href='ReadCookieServlet'>Click here to read the cookie</a>");
out.println("</body></html>");

out.close();
}
}
package com.example;

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

@WebServlet("/ReadCookieServlet")
public class ReadCookieServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Get cookies from the request


Cookie[] cookies = request.getCookies();

// Display the cookies


out.println("<html><body>");
out.println("<h1>Cookies Stored in Your Browser</h1>");
if (cookies != null) {
for (Cookie cookie : cookies) {
out.println("<p>Cookie Name: <strong>" + cookie.getName() + "</strong>, Value: <strong>" +
cookie.getValue() + "</strong></p>");
}
} else {
out.println("<p>No cookies found.</p>");
}
out.println("<a href='CreateCookieServlet'>Back to create a new cookie</a>");
out.println("</body></html>");
out.close();
}
}
4)Write a program for date and time using JSP
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Current Date and Time</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 50px;
text-align: center;
}
h1 {
color: #4CAF50;
}
p{
font-size: 18px;
}
</style>
</head>
<body>
<h1>Current Date and Time</h1>
<p>
<%
// Import necessary classes
import java.text.SimpleDateFormat;
import java.util.Date;

// Get current date and time


Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE, dd MMMM
yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss a");

// Display date and time


out.println("Today's Date: " + dateFormat.format(now) + "<br>");
out.println("Current Time: " + timeFormat.format(now));
%>
</p>
</body>
</html>
5)Write a program to count how many times user has accessed the
webpage using HttpSession.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="javax.servlet.http.HttpSession" %>
<!DOCTYPE html>
<html>
<head>
<title>Page Visit Counter</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 50px;
text-align: center;
}
h1 {
color: #4CAF50;
}
p{
font-size: 18px;
}
</style>
</head>
<body>
<h1>Welcome to Page Visit Counter</h1>
<p>
<%
// Get the current session or create a new one if none exists
HttpSession session = request.getSession();

// Retrieve the visit counter from the session


Integer visitCount = (Integer) session.getAttribute("visitCount");

// Initialize visit counter if not present


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

// Store the updated counter back in the session


session.setAttribute("visitCount", visitCount);
// Display the visit count to the user
out.println("You have accessed this page " + visitCount + " time(s).");
%>
</p>
</body>
</html>

6)Write jsp program to print fibonacci series.


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Fibonacci Series</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 50px;
text-align: center;
}
h1 {
color: #4CAF50;
}
p, form {
font-size: 18px;
}
</style>
</head>
<body>
<h1>Fibonacci Series Generator</h1>
<form method="post">
<label for="terms">Enter the number of terms:</label>
<input type="number" id="terms" name="terms" required min="1" />
<button type="submit">Generate</button>
</form>

<p>
<%
// Retrieve the number of terms from the user input
String termsInput = request.getParameter("terms");
if (termsInput != null) {
int terms = Integer.parseInt(termsInput);

// Generate the Fibonacci series


int a = 0, b = 1, next;
out.print("Fibonacci Series (" + terms + " terms):<br>");
for (int i = 1; i <= terms; i++) {
out.print(a + " ");
next = a + b;
a = b;
b = next;
}
}
%>
</p>
</body>
</html>
7)Write a program to store book information such as book_id,
book_name author, publisher, price, etc into Book_info table using
Hibernate annotation.
xml
Copy code
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property
name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_database</
property>
<property
name="hibernate.connection.username">your_username</property>
<property
name="hibernate.connection.password">your_password</property>

<!-- Hibernate properties -->


<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>

<!-- Annotated class -->


<mapping class="com.example.Book" />
</session-factory>
</hibernate-configuration>

2. Entity Class: Book

java
Copy code
package com.example;

import jakarta.persistence.*;
@Entity
@Table(name = "Book_info")
public class Book {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "book_id")
private int bookId;

@Column(name = "book_name", nullable = false)


private String bookName;

@Column(name = "author", nullable = false)


private String author;

@Column(name = "publisher", nullable = false)


private String publisher;

@Column(name = "price")
private double price;

// Getters and Setters


public int getBookId() {
return bookId;
}

public void setBookId(int bookId) {


this.bookId = bookId;
}

public String getBookName() {


return bookName;
}

public void setBookName(String bookName) {


this.bookName = bookName;
}

public String getAuthor() {


return author;
}

public void setAuthor(String author) {


this.author = author;
}

public String getPublisher() {


return publisher;
}

public void setPublisher(String publisher) {


this.publisher = publisher;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


this.price = price;
}

@Override
public String toString() {
return "Book [bookId=" + bookId + ", bookName=" + bookName + ",
author=" + author + ", publisher=" + publisher
+ ", price=" + price + "]";
}
}

3. Main Application: BookApp

java
Copy code
package com.example;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class BookApp {


public static void main(String[] args) {
// Create configuration
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");

// Create SessionFactory
SessionFactory sessionFactory = configuration.buildSessionFactory();

// Create a session
Session session = sessionFactory.openSession();

// Create transaction
Transaction transaction = session.beginTransaction();

// Create a new book object


Book book = new Book();
book.setBookName("Effective Java");
book.setAuthor("Joshua Bloch");
book.setPublisher("Addison-Wesley");
book.setPrice(45.99);

// Save book object


session.save(book);

// Commit transaction
transaction.commit();

// Close session
session.close();
System.out.println("Book information saved successfully!");
}
}

You might also like