0% found this document useful (0 votes)
26 views26 pages

JAVA SLIP SETUP-1

Uploaded by

Roshni Prajapati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views26 pages

JAVA SLIP SETUP-1

Uploaded by

Roshni Prajapati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

SERVLET SETUP:

FULL PREREQUISITES + SETUP FOR SERVLETS (from


scratch)

✅ What You Need:


Tool Purpose

Eclipse IDE for Enterprise Java Developers To write and run Java EE apps

Apache Tomcat (v9 or v10) Servlet container/server

JDK Java Development Kit for compilation

🔎 How to Check if Tomcat is Configured in Eclipse


1. Open Eclipse

2. Go to Window → Preferences

3. Expand Server → Runtime Environments

4. ✔️
If you see "Apache Tomcat v9.0" (or any version) listed = Already configured

🚫 If Tomcat is NOT Configured — Follow These Steps:

🔽 Step 1: Download Apache Tomcat


1. Go to: https://tomcat.apache.org/download-90.cgi

2. Download "Core" → zip version (Windows)

3. Extract it to a folder like C:\apache-tomcat-9.0.X

🧩 Step 2: Add Tomcat to Eclipse


1. In Eclipse:
Window → Preferences → Server → Runtime Environments

2. Click Add...

3. Select:

○ Apache → Apache Tomcat v9.0

○ Click Next

4. Browse and select the Tomcat folder you extracted (e.g., C:\apache-tomcat-9.0.X)

5. Click Finish

✔️Now Eclipse knows where Tomcat is.

🧪 Step 3: Add Server to Project


1. In Eclipse:
Go to Servers tab (usually at bottom). If you don’t see it:

○ Go to Window → Show View → Servers

2. Click "No servers are available. Click this link to create a new server..."

3. Select Tomcat v9.0 Server

4. Click Next, select your project

5. Click Finish

✅ Done! Now you can right-click → Run on Server to run servlet programs.

📌 How You Know It’s Working:


When you run your servlet:
arduino
CopyEdit
http://localhost:8080/YourProjectName/YourServletName

If you see output in browser, and Eclipse Console shows logs like:
arduino
CopyEdit
Starting Tomcat...
Server startup in XXXX ms

Then it’s working perfectly. 🎯

PROGRAM
SLIP 4B
B) Write a SERVLET program that provides information about a HTTP request from a
client, such as IP address and browser type. The servlet also provides information
about
the server on which the servlet is running, such as the operating system type, and the
names of currently loaded servlets.

🟩 Step-by-Step: Servlet Program in Eclipse


✅ Goal:
Write a servlet that shows:
● Client info: IP address, browser type (user agent)

● Server info: OS type, loaded servlet names

🧱 Step 1: Prerequisites
Tool Needed?

Eclipse IDE ✅ Installed

Apache Tomcat ✅ Installed & configured in


Eclipse

Java EE / Jakarta ✅ (Servlet API comes with


EE Tomcat)

Step 2: Create a Dynamic Web Project


1. Open Eclipse
2. Go to File → New → Dynamic Web Project

3. Give it a name like HttpInfoServletProject

4. Target Runtime: Apache Tomcat

5. Click Finish

📄 Step 3: Create Servlet


1. Right-click src → New → Servlet

2. Servlet name: HttpInfoServlet

3. Package: com.exam

4. Click Next, then Finish

✍️Step 4: Write Code


Replace the code in the generated servlet with this:
java
CopyEdit
package com.exam;

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

public class HttpInfoServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Client Info
String ip = request.getRemoteAddr();
String browser = request.getHeader("User-Agent");
// Server Info
String os = System.getProperty("os.name");

ServletContext context = getServletContext();


Enumeration<String> servlets = context.getServletNames();

out.println("<html><body>");
out.println("<h2>Client Info</h2>");
out.println("<p>IP Address: " + ip + "</p>");
out.println("<p>Browser Type: " + browser + "</p>");

out.println("<h2>Server Info</h2>");
out.println("<p>Operating System: " + os + "</p>");

out.println("<p><strong>Loaded Servlets:</strong></p><ul>");
while (servlets.hasMoreElements()) {
out.println("<li>" + servlets.nextElement() + "</li>");
}
out.println("</ul>");
out.println("</body></html>");
}
}

🧷 Step 5: Configure web.xml (Optional if using annotations)


If you prefer to use web.xml, go to:
● WebContent/WEB-INF/web.x

<servlet>
<servlet-name>HttpInfoServlet</servlet-name>
<servlet-class>com.exam.HttpInfoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HttpInfoServlet</servlet-name>
<url-pattern>/httpinfo</url-pattern>
</servlet-mapping>

▶️Step 6: Run the Servlet


1. Right-click project → Run As → Run on Server

2. Select Tomcat → Next → Finish

URL in browser:

bash
CopyEdit
http://localhost:8080/HttpInfoServletProject/httpinfo
3.
You’ll see IP, browser type, OS info, and loaded servlets. 🎉

✅ Libraries Required:
● No extra libraries needed — just Tomcat (comes with servlet-api.jar)

JSP SETUP:

🔧 Prerequisites (Before Coding)

✅ Eclipse & Tomcat Setup


Already done ✔️(as per your earlier servlet setup)
PROGRAM
SLIP 9B
B) Write a SERVLET program that provides information about a HTTP request from a
client, such as IP address and browser type. The servlet also provides information
about
the server on which the servlet is running, such as the operating system type, and the
names of currently loaded servlets.

✅ Project Setup
1. Create a Dynamic Web Project

○ Name: JSPShoppingMall

○ Target Runtime: Apache Tomcat

○ Dynamic Web Module: 3.1 (or similar)

Inside WebContent, create:

CopyEdit
shopping1.jsp
shopping2.jsp
bill.jsp
2.

🛒 JSP Shopping Mall – Page-by-Page

🔹 Page 1: shopping1.jsp
jsp
CopyEdit
<%@ page language="java" contentType="text/html" %>
<%
String item1 = request.getParameter("item1");
String qty1 = request.getParameter("qty1");

if(item1 != null && qty1 != null){


int price1 = 100;
int total1 = Integer.parseInt(qty1) * price1;
session.setAttribute("total1", total1);
}
%>

<h2>Shopping Page 1 - Electronics</h2>


<form action="shopping2.jsp" method="post">
Item: Mobile (Rs.100 each)<br>
Quantity: <input type="text" name="qty1" /><br><br>
<input type="submit" value="Next" />
</form>

🔹 Page 2: shopping2.jsp
jsp
CopyEdit
<%@ page language="java" contentType="text/html" %>
<%
String qty2 = request.getParameter("qty2");
if(qty2 != null){
int price2 = 50;
int total2 = Integer.parseInt(qty2) * price2;
session.setAttribute("total2", total2);
}
%>

<h2>Shopping Page 2 - Books</h2>


<form action="bill.jsp" method="post">
Item: Book (Rs.50 each)<br>
Quantity: <input type="text" name="qty2" /><br><br>
<input type="submit" value="Generate Bill" />
</form>

🔹 Page 3: bill.jsp
jsp
CopyEdit
<%@ page language="java" contentType="text/html" %>
<%
Integer total1 = (Integer) session.getAttribute("total1");
Integer total2 = (Integer) session.getAttribute("total2");
if(total1 == null) total1 = 0;
if(total2 == null) total2 = 0;

int grandTotal = total1 + total2;


%>

<h2>Shopping Bill</h2>
<table border="1">
<tr><th>Item</th><th>Price</th></tr>
<tr><td>Electronics</td><td><%= total1 %></td></tr>
<tr><td>Books</td><td><%= total2 %></td></tr>
<tr><td><b>Total</b></td><td><b><%= grandTotal %></b></td></tr>
</table>

🚀 Running the JSP App

Step-by-step:
1. Right-click on your project → Run As → Run on Server

Start with:

bash
CopyEdit
http://localhost:8080/JSPShoppingMall/shopping1.jsp
2.
3. Enter quantity, go next, continue

4. Final bill is shown on bill.jsp

JDBC SETUP:

✅ Step 1: Prerequisites (XAMPP Setup)

🔹 Start MySQL in XAMPP


1. Open XAMPP Control Panel

2. Click Start next to MySQL

3. Click Admin (this opens phpMyAdmin in your browser)


✅ Step 2: Create Database and Table (Using
phpMyAdmin)
1. In phpMyAdmin:

○ Click New on the left → Name your DB company → Click Create

2. Click on company → Click SQL tab

3. Paste and run or choose already created table:

sql
CopyEdit
CREATE TABLE Emp (
ENo INT PRIMARY KEY,
EName VARCHAR(50),
Sal DOUBLE
);

✅ Step 3: Add MySQL JDBC Driver to Eclipse


1. Download from: MySQL Connector J

2. In Eclipse:

○ Right-click project → Build Path → Configure Build Path

○ Go to Libraries → Add External JARs

○ Add the mysql-connector-j-8.0.xx.jar file

PROGRAM
SLIP 9A
Write a Java Program to create a Emp (ENo, EName, Sal) table and insert
record into it. (Use PreparedStatement Interface)
✅ Step-by-Step: How to Create a Java File in Eclipse and
Run It

🔹 Step 1: Open Eclipse IDE


1. Launch Eclipse

2. Go to: File → New → Java Project

○ Name it: JDBCExample

○ Click Finish

🔹 Step 2: Create a Java Class (File)


1. Right-click on the src folder inside your new project → New → Class

2. Class Name: InsertEmployee

3. Check ✅ the option: public static void main(String[] args)

4. Click Finish

You’ll now see a file like:


css
CopyEdit
JDBCExample
└── src
└── InsertEmployee.java

🔹 Step 3: Paste Your JDBC Code


Replace the content with this code (already updated for XAMPP):
java
CopyEdit
import java.sql.*;
import java.util.Scanner;

public class InsertEmployee {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
Class.forName("com.mysql.cj.jdbc.Driver");

Connection con = DriverManager.getConnection(


"jdbc:mysql://localhost:3306/company", "root", "");

String query = "INSERT INTO Emp (ENo, EName, Sal) VALUES (?, ?, ?)";
PreparedStatement ps = con.prepareStatement(query);

System.out.print("Enter Emp No: ");


int eno = sc.nextInt();

System.out.print("Enter Emp Name: ");


String ename = sc.next();

System.out.print("Enter Salary: ");


double sal = sc.nextDouble();

ps.setInt(1, eno);
ps.setString(2, ename);
ps.setDouble(3, sal);

int result = ps.executeUpdate();

if (result > 0)
System.out.println("Record inserted successfully!");
else
System.out.println("Insertion failed.");

con.close();
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

🔹 Step 4: Add MySQL JDBC JAR File


1. Download MySQL Connector: https://dev.mysql.com/downloads/connector/j/
2. Go to Eclipse:

○ Right-click your project → Build Path → Configure Build Path

○ Go to Libraries tab → Click Add External JARs

○ Select mysql-connector-j-8.x.x.jar

○ Click Apply and Close

✅ This adds the required library to your project.

🔹 Step 5: Run the Program


1. Right-click on InsertEmployee.java

2. Click: Run As → Java Application

3. Terminal appears below → Enter Emp No, Name, Salary

4. Output: ✅ Record inserted successfully!

Check in XAMPP → phpMyAdmin → Table → Data will be inserted.

SOCKET SETUP:

🔧 Prerequisites (Before Coding)


1. Use any IDE: Eclipse, IntelliJ, or VS Code

2. No special setup needed — no Tomcat, no MySQL

3. Just standard JDK (version 8 or later)



PROGRAM
SLIP 1B
B) Write a socket program in java for chatting application.(Use Swing)

✅ How to Create a Java File in Eclipse

🔹 Step 1: Open Eclipse


● Launch Eclipse IDE for Java Developers.

● Choose a workspace folder (just click OK if unsure).

🔹 Step 2: Create a Java Project


1. Click File > New > Java Project

2. Give it a name (e.g., ChatApp)

3. Click Finish

🔹 Step 3: Create a Package (optional but neat)


1. Right-click on src > New > Package

2. Name it (e.g., chat)

3. Click Finish

🔹 Step 4: Create a Java Class (Your File)


1. Right-click on the package (or directly on src if no package)

2. Select New > Class

3. In the dialog:
○ Name: ChatServer (or whatever your class is)

○ ✅ Check public static void main(String[] args) if it has a main


method

4. Click Finish

💡 A file will be created named ChatServer.java and opened in the editor.

🔹 Step 5: Paste Your Code


● Copy the server or client code

● Paste it inside the ChatServer or ChatClient file (replace auto-generated code)

🔹 Step 6: Run Your Program


1. Click on the file tab (e.g., ChatServer.java)

2. Click the green ▶️Run button on top

3. See output in the console below

Step 1: Server Side Code – ChatServer.java


java
CopyEdit
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ChatServer extends JFrame {


private JTextArea chatArea;
private JTextField inputField;
private PrintWriter out;

public ChatServer() {
setTitle("Server Chat");
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);

chatArea = new JTextArea();


chatArea.setEditable(false);

inputField = new JTextField();


inputField.addActionListener(e -> {
String message = inputField.getText();
chatArea.append("Me: " + message + "\n");
out.println(message);
inputField.setText("");
});

add(new JScrollPane(chatArea), BorderLayout.CENTER);


add(inputField, BorderLayout.SOUTH);

setVisible(true);

try {
ServerSocket serverSocket = new ServerSocket(1234);
Socket socket = serverSocket.accept();
chatArea.append("Client connected\n");

BufferedReader in = new BufferedReader(new


InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);

String line;
while ((line = in.readLine()) != null) {
chatArea.append("Client: " + line + "\n");
}

socket.close();
serverSocket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

public static void main(String[] args) {


new ChatServer();
}
}

💻 Step 2: Client Side Code – ChatClient.java


java
CopyEdit
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ChatClient extends JFrame {


private JTextArea chatArea;
private JTextField inputField;
private PrintWriter out;

public ChatClient() {
setTitle("Client Chat");
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);

chatArea = new JTextArea();


chatArea.setEditable(false);

inputField = new JTextField();


inputField.addActionListener(e -> {
String message = inputField.getText();
chatArea.append("Me: " + message + "\n");
out.println(message);
inputField.setText("");
});

add(new JScrollPane(chatArea), BorderLayout.CENTER);


add(inputField, BorderLayout.SOUTH);

setVisible(true);
try {
Socket socket = new Socket("localhost", 1234);
chatArea.append("Connected to server\n");

BufferedReader in = new BufferedReader(new


InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);

String line;
while ((line = in.readLine()) != null) {
chatArea.append("Server: " + line + "\n");
}

socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

public static void main(String[] args) {


new ChatClient();
}
}

SLIP-2B
B) Write a java program in multithreading using applet for drawing
flag.
🔧 BEFORE YOU START:

✅ Check your Java version:


Open Command Prompt:
bash
CopyEdit
java -version
If it shows Java 8 (like 1.8.0_xx), you're good ✅
If you're on a newer version (Java 11+), install Java 8 JDK separately to use
appletviewer.

📝 Step 1: Create Java Applet File


Save this as FlagApplet.java:
java
CopyEdit
import java.applet.*;
import java.awt.*;

/* <applet code="FlagApplet.class" width="400" height="300"></applet> */

public class FlagApplet extends Applet implements Runnable {


int y = 50;
Thread t;

public void init() {


setBackground(Color.white);
t = new Thread(this);
t.start();
}

public void paint(Graphics g) {


// Flag pole
g.setColor(Color.DARK_GRAY);
g.fillRect(100, 50, 10, 200);

// Top - Saffron
g.setColor(Color.ORANGE);
g.fillRect(110, y, 100, 20);

// Middle - White
g.setColor(Color.WHITE);
g.fillRect(110, y + 20, 100, 20);

// Bottom - Green
g.setColor(Color.GREEN);
g.fillRect(110, y + 40, 100, 20);
}

public void run() {


while (true) {
y += 1;
if (y > 200) y = 50;
repaint();
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
}

📝 Step 2: Create HTML File


Save this as FlagApplet.html in the same folder:
html
CopyEdit
<html>
<body>
<applet code="FlagApplet.class" width="400" height="300">
</applet>
</body>
</html>

Step 3: Compile Java File


In Command Prompt:
bash
CopyEdit
javac FlagApplet.java

This generates a file: FlagApplet.class

▶️Step 4: Run the Applet


Now run using:
bash
CopyEdit
appletviewer FlagApplet.html

It will open a separate window and show the animated flag 🎌


✅ Final Notes

Task Tool

Create code FlagApplet.java

Create HTML FlagApplet.html

Compile javac FlagApplet.java

Run appletviewer FlagApplet.html

Java Version Use Java 8

Want me to check if your system already has Java 8 or help switch if it doesn’t?
4o

You said:
in notepad i can create both files na

ChatGPT said:
Yes, absolutely! ✅
You can create both .java and .html files using Notepad. Here's how to do it step by
step:

✅ Step-by-Step: Create Applet & HTML Files in Notepad

🔹 Step 1: Create the Java File


1. Open Notepad.

Paste this code:

java
CopyEdit
import java.applet.*;
import java.awt.*;

public class FlagApplet extends Applet implements Runnable {


int y = 50;
Thread t;

public void init() {


setBackground(Color.white);
t = new Thread(this);
t.start();
}

public void paint(Graphics g) {


g.setColor(Color.DARK_GRAY);
g.fillRect(100, 50, 10, 200);

g.setColor(Color.ORANGE);
g.fillRect(110, y, 100, 20);

g.setColor(Color.WHITE);
g.fillRect(110, y + 20, 100, 20);

g.setColor(Color.GREEN);
g.fillRect(110, y + 40, 100, 20);
}

public void run() {


while (true) {
y += 1;
if (y > 200) y = 50;
repaint();
try {
Thread.sleep(100);
} catch (Exception e) {}
}
}
}
2.
Save the file as:

CopyEdit
FlagApplet.java
3. 🔸 Select "All Files" in the Save As Type dropdown
🔸 Add .java manually
🔸 Save it in a simple folder (e.g., C:\JavaApplet\)

🔹 Step 2: Create the HTML File


1. Open a new Notepad window.
Paste this:

html
CopyEdit
<html>
<body>
<applet code="FlagApplet.class" width="400" height="300"></applet>
</body>
</html>
2.
Save the file as:

CopyEdit
FlagApplet.html
3. 🔸 Again, choose "All Files"
🔸 Add .html manually
🔸 Save it in the same folder as your .java file (e.g., C:\JavaApplet\)

✅ Done! Now you can compile and run:


Open Command Prompt:

cd C:\JavaApplet
javac FlagApplet.java
appletviewer FlagApplet.html

It will open a window and show your flag waving animation 🚩

HIBERNATE SETUP
SLIP-10A
Write a java Program in Hibernate to display “Hello world” message.
✅ Step 1: Download Required Files

1.1 Download Hibernate JARs


● Go to: https://hibernate.org/orm/releases/

● Scroll to "Hibernate ORM" → Download the latest stable version (ZIP).

● Extract the ZIP file. Inside, you'll find:

○ lib/required → All necessary JARs (these are what we need)

○ Optional: lib/jpa, lib/bytecode (not needed now)

🔖 Copy JARs from lib/required — this includes core Hibernate dependencies.

✅ Step 2: Create Java Project in Eclipse


1. Open Eclipse IDE.

2. Go to File → New → Java Project.

3. Name the project: HibernateHello

4. Click Finish.

✅ Step 3: Add Hibernate JARs to Project


1. Right-click on your HibernateHello project → Build Path → Configure Build Path

2. Click on the Libraries tab → Click Add External JARs…

3. Navigate to the extracted Hibernate folder → Select all JARs inside


lib/required

4. Click Open, then Apply and Close.

✅ Step 4: Add Hibernate Configuration File (hibernate.cfg.xml)


1. Right-click on src folder → New → File
2. Name it: hibernate.cfg.xml

3. Paste this content:

xml
CopyEdit
<?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>
<!-- No real DB, just in-memory config -->
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
<property name="hibernate.connection.url">jdbc:h2:mem:test</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"></property>
</session-factory>
</hibernate-configuration>

✅ This is a dummy in-memory config for “Hello World” only — we don’t need a real
DB yet.

✅ Step 5: Create Java Class (Main File)


1. Right-click on src → New → Class

2. Name it: HelloWorld

3. Check "public static void main(String[] args)" → Finish

4. Paste this code:

java
CopyEdit
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HelloWorld {


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

// Create SessionFactory
SessionFactory factory = cfg.buildSessionFactory();

// Open Session
Session session = factory.openSession();

System.out.println("Hello World from Hibernate!");

// Close resources
session.close();
factory.close();
}
}

✅ Step 6: Run the Program


1. Right-click on HelloWorld.java

2. Click Run As → Java Application

3. ✅ You’ll see the output in the console:

csharp
CopyEdit
Hello World from Hibernate!

You might also like