Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

AdvancedJava Lab Journal Report

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 28

1.write a java program for JSP request implicit object.

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Submit Name</title>
</head>
<body>
<form action="index.jsp" method="GET">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<button type="submit">Submit</button>
</form>
</body>
</html>

Index.jsp

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>
<body>
<h1>Hello<%=request.getparameter(“name”)%></h1>
</body>
</html>

Output

2.Write a java program for JSP response implicit object

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

<html>

<head>

<title>Response Implicit Object Example</title>

</head>

<body>

<%

response.getWriter().println("<h2>Response Implicit Object Example</h2>");

response.getWriter().println("<p>This is an example of using the response implicit object in


JSP.</p>");

%>

</body>

</html>

Output

3.Write a java program for JSP exception implicit object

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

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Division Result</title>

</head>

<body>

<%

try {

int num1 = Integer.parseInt(request.getParameter("num1"));

int num2 = Integer.parseInt(request.getParameter("num2"));

int result = num1 / num2;

%>

<h2>Result of Division</h2>

<p><%= num1 %> / <%= num2 %> = <%= result %></p>

<%

} catch (Exception e) {

response.sendRedirect("error.jsp?message=" +
java.net.URLEncoder.encode(e.getMessage(), "UTF-8"));

%>

</body>

</html>

Index.html

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Calculator</title>

</head>
<body>

<h2>Calculator</h2>

<form action="exceptionExample.jsp" method="post">

Enter first number: <input type="number" name="num1"><br>

Enter second number: <input type="number" name="num2"><br>

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

</form>

</body>

</html>

Output

4.Write a java program for Redirect


RedirectServlet.java

import java.io.IOException;

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("/redirect")

public class RedirectServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.sendRedirect("https://www.google.com");

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

Output
5.Write a java program to pass the parameters to next page

Page1.jsp

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

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Page 3</title>

</head>

<body>

<%

String name = (String) session.getAttribute("name");

%>

<h2>Hello again, <%= name %>!</h2>

</body>

</html>

Page2.jsp

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


<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Page 2</title>

</head>

<body>

<%

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

session.setAttribute("name", name);

%>

<h2>Hello, <%= name %>!</h2>

<a href="Page3.jsp">Go to Page 3</a>

</body>

</html>

Page3.jsp

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

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Page 3</title>

</head>

<body>

<%

String name = (String) session.getAttribute("name");

%>

<h2>Hello again, <%= name %>!</h2>

</body>

</html>
Output
6.write a java program for javabean

Index.jsp

<%--

Document : index

Created on : 16 Feb, 2024, 2:44:14 PM

Author : otaxa

--%>

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

<jsp:useBean id="obj" class="MCA.Calculator"/>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>JSP Page</title>

</head>
<body>

<%

int m=obj.cube(5);

out.println("Cube is"+m);

%>

</body>

</html>

Calculator.java

package MCA;

public class Calculator {

public int cube(int n)

return n*n*n;

Output
7.write a java program Session Management

Session.jsp

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

<%@page import="java.io.*"%>

<%@page import="java.util.*"%>

<%

Date createTime=new Date(session.getCreationTime());

Date lastAccessTime=new Date(session.getLastAccessedTime());

String title="welcome back";

Integer visitCount=new Integer(0);

String visitCountKey=new String("visitCount");

String userIDKey=new String("userID");

String userID=new String("ABCD");

if(session.isNew())

title="welcome";

session.setAttribute(userIDKey,userID);

session.setAttribute(visitCountKey,visitCount);

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

visitCount+=1;

userID=(String)session.getAttribute(userIDKey);

session.setAttribute(visitCountKey,visitCount);
%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>JSP Page</title>

</head>

<center>

<h1>Session tracking</h1>

</center>

<table border="1" align="center">

<tr bgcolor="#949494">

<th>session info</th>

<th>value</th>

</tr>

<tr>

<td>id</td>

<td><%out.print(session.getId());%></td>

</tr>

<tr>

<td>Creation Time</td>

<td><%out.print(createTime);%></td>

</tr>

<tr>

<td>Time of last access</td>

<td><%out.print(lastAccessTime);%></td>

</tr>

<tr>

<td>User ID</td>

<td><%out.print(userID);%></td>

</tr>

<tr>

<td>Number of visit</td>
<td><%out.print(visitCount);%></td>

</tr>

</table>

</body>

</html>

Output

8.Write a java program on RMI

HelloInterface.java

import java.rmi.Remote;

import java.rmi.RemoteException;

public interface HelloInterface extends Remote {

String sayHello() throws RemoteException;

}
HelloImpl.java

import java.rmi.RemoteException;

import java.rmi.server.UnicastRemoteObject;

public class HelloImpl extends UnicastRemoteObject implements HelloInterface {

public HelloImpl() throws RemoteException {

super();

@Override

public String sayHello() throws RemoteException {

return "Hello, world!";

Server.java

import java.rmi.Naming;

import java.rmi.registry.LocateRegistry;

public class Server {

public static void main(String[] args) {

try {

LocateRegistry.createRegistry(1099); // Start the RMI registry on port 1099

HelloImpl obj = new HelloImpl();

Naming.rebind("HelloServer", obj);

System.out.println("Server is running...");

} catch (Exception e) {

System.err.println("Server exception: " + e.toString());

e.printStackTrace();

}
Client.java

import java.rmi.Naming;

public class Client {

public static void main(String[] args) {

try {

HelloInterface obj = (HelloInterface) Naming.lookup("//localhost/HelloServer");

String message = obj.sayHello();

System.out.println("Message from server: " + message);

} catch (Exception e) {

System.err.println("Client exception: " + e.toString());

e.printStackTrace();

Output
9.write a java program for Hibernate

Hibernate.cfg.xml

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

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"


"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!--

<hibernate-configuration>

<session-factory>

<property name="hibernate.dialect">

org.hibernate.dialect.MySQLDialect

</property>

<property name="hibernate.connection.driver_class">

com.mysql.jdbc.Driver

</property>

<!-- Assume test is the database name -->

<property name="hibernate.connection.url">

jdbc:mysql://127.0.0.1:3306/emp

</property>

<property name="hibernate.connection.username">

root

</property>
<property name="hibernate.connection.password">

</property>

<!-- List of XML mapping files -->

<mapping resource="hibernatedemo1/Employee2.hbm.xml"/>

<mapping resource="hibernatedemo1/Employee2.hbm.xml"/>

<mapping resource="hibernatedemo1/Employee.hbm.xml"/>

</session-factory>

</hibernate-configuration>

Employee.hbm.xml

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

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"


"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!--

-->

<hibernate-mapping>

<class name = "hibernatedemo1.Employee1" table = "emp">

<meta attribute = "class-description">

This class contains the employee detail.

</meta>

<id name = "id" type = "int" column = "id">

<generator class="native"/>

</id>

<!--<property name = "id" column = "id" type = "int"/>-->

<property name = "firstName" column = "fname" type = "string"/>

<property name = "lastName" column = "lname" type = "string"/>

<property name = "salary" column = "salary" type = "int"/>


</class>

</hibernate-mapping>

Employee.java

/*

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

package hibernatedemo1;

/**

* @author otaxa

*/

public class Employee1 {

private int id;

private String firstName;

private String lastName;

private int salary;

public Employee1() {}

public Employee1(String fname, String lname, int salary) {

this.firstName = fname;

this.lastName = lname;

this.salary = salary;

public int getId() {

return id;

public void setId( int id ) {

this.id = id;
}

public String getFirstName() {

return firstName;

public void setFirstName( String first_name ) {

this.firstName = first_name;

public String getLastName() {

return lastName;

public void setLastName( String last_name ) {

this.lastName = last_name;

public int getSalary() {

return salary;

public void setSalary( int salary ) {

this.salary = salary;

HibernateDemo1.java

/*

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

package hibernatedemo1;
import java.util.List;

import java.util.Date;

import java.util.Iterator;

import javax.imageio.spi.ServiceRegistry;

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.Transaction;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

/**

* @author otaxa

*/

public class HibernateDemo1 {

/**

* @param args the command line arguments

*/

// TODO code application logic here

private static SessionFactory factory;

public static void main(String[] args) {

org.hibernate.service.ServiceRegistry ServiceRegistry = null;

try {

factory = new Configuration().configure().buildSessionFactory();

} catch (Exception ex) {

System.err.println("Failed to create sessionFactory object." + ex);

// throw new ExceptionInInitializerError(ex);

//try {

// factory = new Configuration().configure().buildSessionFactory();

//} catch (Throwable ex) {


// System.err.println("Failed to create sessionFactory object. " + ex.getMessage());

// throw new ExceptionInInitializerError(ex);

//}

HibernateDemo1 ME = new HibernateDemo1();

/* Add few employee records in database */

Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);

Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);

Integer empID3 = ME.addEmployee("John", "Paul", 10000);

/* List down all the employees */

ME.listEmployees();

/* Update employee's records */

ME.updateEmployee(empID1, 5000);

/* Delete an employee from the database */

ME.deleteEmployee(empID2);

/* List down new list of the employees */

ME.listEmployees();

/* Method to CREATE an employee in the database */

public Integer addEmployee(String fname, String lname, int salary){

Session userSession = factory.openSession();

Transaction tx = null;

Integer employeeID = null;

try {

tx = userSession.beginTransaction();

Employee1 employee = new Employee1(fname, lname, salary);


employeeID = (Integer) userSession.save(employee);

tx.commit();

} catch (HibernateException e) {

if (tx!=null) tx.rollback();

e.printStackTrace();

} finally {

userSession.close();

return employeeID;

/* Method to READ all the employees */

public void listEmployees( ){

Session session = factory.openSession();

Transaction tx = null;

try {

tx = session.beginTransaction();

List employees = session.createQuery("FROM Employee").list();

for (Iterator iterator = employees.iterator(); iterator.hasNext();){

Employee1 employee = (Employee1) iterator.next();

System.out.print("First Name: " + employee.getFirstName());

System.out.print(" Last Name: " + employee.getLastName());

System.out.println(" Salary: " + employee.getSalary());

tx.commit();

} catch (HibernateException e) {

if (tx!=null) tx.rollback();

e.printStackTrace();

} finally {

session.close();

}
/* Method to UPDATE salary for an employee */

public void updateEmployee(Integer EmployeeID, int salary ){

Session session = factory.openSession();

Transaction tx = null;

try {

tx = session.beginTransaction();

Employee1 employee = (Employee1)session.get(Employee1.class, EmployeeID);

employee.setSalary( salary );

session.update(employee);

tx.commit();

} catch (HibernateException e) {

if (tx!=null) tx.rollback();

e.printStackTrace();

} finally {

session.close();

/* Method to DELETE an employee from the records */

public void deleteEmployee(Integer EmployeeID){

Session session = factory.openSession();

Transaction tx = null;

try {

tx = session.beginTransaction();

Employee1 employee = (Employee1)session.get(Employee1.class, EmployeeID);

session.delete(employee);

tx.commit();

} catch (HibernateException e) {

if (tx!=null) tx.rollback();

e.printStackTrace();

} finally {

session.close();
}

Output

First Name : Zara Last Name :Ali Salary : 1000

First Name : Daisy Last Name : Das Salary : 5000

First Name : John Last Name : Paul Salary : 10000

10 . write a java program on structs

Fileupload.jsp

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

<!DOCTYPE html>

<html>

<head>

<title>File Upload</title>

</head>

<body>

<h1>Upload a File</h1>

<form enctype="multipart/form-data" action="uploadFile.do" method="post">

<input type="file" name="file" size="50"/><br/>

<input type="submit" value="Upload File"/>

</form>

</body>

</html>

Uploadsuccess.jsp

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

<!DOCTYPE html>

<html>

<head>

<title>Upload Success</title>

</head>
<body>

<h1>File Uploaded Successfully!</h1>

</body>

</html>

FileUploadAction.java

package java.io;

public void write(byte b[], int off, int len) throws IOException {

if (b == null) {

throw new NullPointerException();

} else if ((off < 0) || (off > b.length) || (len < 0) ||

((off + len) > b.length) || ((off + len) < 0)) {

throw new IndexOutOfBoundsException();

} else if (len == 0) {

return;

for (int i = 0 ; i < len ; i++) {

write(b[off + i]);

public void close() throws IOException {

FileUploadForm.java

package com.example.forms;

import org.apache.struts.action.ActionForm;

import org.apache.struts.upload.FormFile;

/**

* @author MCA
*/

public class FileUploadForm extends ActionForm{

private FormFile file;

public FormFile getFile()

return file;

public void setFile(FormFile file)

this.file = file;

Structs-config.xml

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

<!DOCTYPE struts-config PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"

"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

<form-beans>

<form-bean name="FileUploadForm" type="com.example.forms.FileUploadForm"/>

</form-beans>

<action-mappings>

<action path="/uploadFile" type="com.example.actions.FileUploadAction"

name="FileUploadForm" scope="request" validate="true"

input="/fileUploadForm.jsp">

<forward name="success" path="/uploadSucess.jsp"/>


</action>

</action-mappings>

</struts-config>

output

You might also like