Ajp Prac
Ajp Prac
CODES
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JavaExpYug{
public static void main(String[]args){
// Frame initialization
JFrame f = new JFrame("Example Form");
f.setSize(400,300);
f.setLayout(new GridLayout(5,2));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Components initialization
JLabel lblName = new JLabel("Enter the name : ");
JLabel lblAge = new JLabel("Enter age : ");
JLabel lblBranch = new JLabel("Enter the branch : ");
JTextField tfName = new JTextField();
JTextField tfAge = new JTextField();
JTextField tfBranch = new JTextField();
JButton btnSubmit = new JButton("SUBMIT");
JLabel lblResponse = new JLabel("");
//Adding the components in the frame
f.add(lblName);
f.add(tfName);
f.add(lblAge);
f.add(tfAge);
f.add(lblBranch);
f.add(tfBranch);
f.add(new Label());
f.add(btnSubmit);
f.add(lblResponse);
//making the listener on the button
btnSubmit.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
if(tfName.getText().equals("") ||
tfAge.getText().equals("") || tfBranch.getText().equals("") ){
lblResponse.setText("Please Fill the Empty
brackets");
}
else{
lblResponse.setText("Form submitted
successfully");
}
}
});
// //making the listener to the window close button
// f.addWindowListener(new WindowAdapter() {
// public void windowClosing(WindowEvent e) {
// System.exit(0);
// }
// });
f.setVisible(true);
}
}
2. Develop a program to select multiple language known to the user( marathi english
hindi sanskrit ) and also gender of the user
// agar sirf language waala aaye toh
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/* <applet code = "exp2C1" width=500 height=500></applet> */
list.add("English");
list.add("Marathi");
list.add("Hindi");
list.add("Sanskrit");
add(list);
list.addItemListener(this);
setLayout(new FlowLayout());
}
public void itemStateChanged(ItemEvent e) {
repaint();
}
public void paint(Graphics g) {
int idx[];
String msg = "Selected:";
idx = list.getSelectedIndexes();
OR
import java.awt.*;
import java.awt.event.*;
public class JavaExpYug{
public static void main(String[]args){
Frame f = new Frame("Select Language and Gender");
f.setSize(500,500);
f.setLayout(new GridLayout(2,2));
//initialize the components
List ltLang = new List(4,true);
Label lblSelectedLang = new Label("");
ltLang.add("HINDI");
ltLang.add("ENGLISH");
ltLang.add("MARATHI");
ltLang.add("SANSKRIT");
f.add(new Label("Select Language : "));
f.add(ltLang);
f.add(new Label("Selected Languages are : "));
f.add(lblSelectedLang);
}
}
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
list.add("English");
list.add("Marathi");
list.add("Hindi");
list.add("Sanskrit");
c.add("Male");
c.add("Female");
add(list);
add(c);
list.addItemListener(this);
c.addItemListener(this);
if (!selectedGender.isEmpty()) {
msg += "| Gender: " + selectedGender;
}
g.drawString(msg, 6, 200);
}
}
OR
import java.awt.*;
import java.awt.event.*;
public class JavaExpYug{
public static void main(String[]args){
Frame f = new Frame("Select Language and Gender");
f.setSize(500,500);
f.setLayout(new GridLayout(4,2));
//initialize the components
List ltLang = new List(4,true);
Choice chGender = new Choice();
Label lblSelectedLang = new Label("");
Label lblSelectedGender = new Label("");
ltLang.add("HINDI");
ltLang.add("ENGLISH");
ltLang.add("MARATHI");
ltLang.add("SANSKRIT");
chGender.add("Male");
chGender.add("Female");
f.add(new Label("Select Language : "));
f.add(ltLang);
f.add(new Label("Select Gender : "));
f.add(chGender);
f.add(new Label("Selected Languages are : "));
f.add(lblSelectedLang);
f.add(new Label("Selected Gender is : "));
f.add(lblSelectedGender);
ltLang.addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent e){
String data = "";
int arr[] = ltLang.getSelectedIndexes();
for(int i = 0 ; i < arr.length ; i++){
data = data + " " + ltLang.getItem(arr[i]);
}
lblSelectedLang.setText(data);
}
});
chGender.addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent e){
String data = chGender.getSelectedItem();
lblSelectedGender.setText(data);
}
});
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
//making the frame visible
f.setVisible(true);
}
}
3. Develop an applet application to select multiple newspaper name by using List
(same as 2)
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
// <applet code="JavaExpYug" height="500" width="500"></applet>
public class JavaExpYug extends Applet{
public void init(){
setLayout(new GridLayout(2,2));
List lsNews = new List(4,true);
lsNews.add("Times Of India");
lsNews.add("Navbharat Times");
lsNews.add("Bhaskar Dainik");
lsNews.add("Dainik Shiksha");
Label lblSelected = new Label();
add(new Label("Select News Paper : "));
add(lsNews);
add(new Label("Select Papers are : "));
add(lblSelected);
lsNews.addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent e){
String data = "";
int arr[] = lsNews.getSelectedIndexes();
for(int i = 0 ; i < arr.length ; i++){
data = data + " " + lsNews.getItem(arr[i]);
}
lblSelected.setText(data);
}
});
}
}
4. Develop a applet program using the List component to add the name of 10 cities
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
// <applet code="JavaExpYug" height="500" width="500"></applet>
public class JavaExpYug extends Applet{
public void init(){
setLayout(new GridLayout(2,2));
List lsCities = new List(10,true);
lsCities.add("Mumbai");
lsCities.add("Pune");
lsCities.add("Panjim");
lsCities.add("Chennai");
lsCities.add("Bengluru");
lsCities.add("Kochi");
lsCities.add("Delhi");
lsCities.add("Bhopal");
lsCities.add("Gandhinagar");
lsCities.add("Ahemdabad");
Label lblSelected = new Label();
add(new Label("Select Cities : "));
add(lsCities);
add(new Label("Select Cities are : "));
add(lblSelected);
lsCities.addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent e){
String data = "";
int arr[] = lsCities.getSelectedIndexes();
for(int i = 0 ; i < arr.length ; i++){
data = data + " " + lsCities.getItem(arr[i]);
}
lblSelected.setText(data);
}
});
}
}
5. Wap to demonstrate the use of border layout use the border Layout and use all
consntants(north south east west centr)
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
@Override
public Insets getInsets() {
// Override the getInsets() method to add custom padding around the applet
return new Insets(10, 10, 10, 10); // 10px padding on all sides (top,
left, bottom, right)
}
}
6. WAP to create a grid using the gridlayouot with rows and columns and add button
and label to the grids
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
// <applet code="JavaExpYug" height="500" width="500"></applet>
public class JavaExpYug extends Applet{
public void init(){
setLayout(new GridLayout(5,2));
for(int i=1;i<=5;i++){
for(int j=1;j<=2;j++){
if(j==2){
String str = "This is Button "+i;
add(new Button(str));
}
else{
String str = "This is Label "+i;
add(new Label(str));
}
}
}
}
}
7. WAP that create a menu of different color and disables the menuItem from black
color
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JavaExpYug {
public static void main(String[] args) {
JFrame frame = new JFrame("Color Menu Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
JMenu colorMenu = new JMenu("Colors");
JMenuItem redItem = new JMenuItem("Red");
JMenuItem greenItem = new JMenuItem("Green");
JMenuItem blueItem = new JMenuItem("Blue");
JMenuItem blackItem = new JMenuItem("Black");
blackItem.setEnabled(false);
redItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().setBackground(Color.RED);
}
});
greenItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().setBackground(Color.GREEN);
}
});
blueItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().setBackground(Color.BLUE);
}
});
blackItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.getContentPane().setBackground(Color.BLACK);
}
});
colorMenu.add(redItem);
colorMenu.add(greenItem);
colorMenu.add(blueItem);
colorMenu.add(blackItem);
menuBar.add(colorMenu);
frame.setJMenuBar(menuBar);
frame.setVisible(true);
}
}
btnSubmit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String input1 = jtfNum1.getText().trim();
String input2 = jtfNum2.getText().trim();
// Validate inputs
if (input1.isEmpty() || input2.isEmpty()) {
lblResult.setText("Error: Both fields must be filled.");
return;
}
try {
int a = Integer.parseInt(input1);
int b = Integer.parseInt(input2);
String ans = a + b + "";
lblResult.setText("Result: " + ans);
} catch (NumberFormatException ex) {
lblResult.setText("Error: Please enter valid numeric values.");
}
}
});
f.setVisible(true);
}
}
setLayout(new GridLayout(4,2));
String fruits[] = {"Select Fruit", "Apple", "Banana", "Orange", "Mango",
"Grapes"};
String vegetables[] = {"Select Vegetable", "Carrot", "Broccoli", "Spinach",
"Potato", "Tomato"};
fruitComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selectedFruit = (String)fruitComboBox.getSelectedItem();
selectedFruitLabel.setText("Selected Vegetable: " + selectedFruit);
}
});
vegetableComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selectedVegetable =
(String)vegetableComboBox.getSelectedItem();
selectedVegLabel.setText("Selected Vegetable: " +
selectedVegetable);
}
});
}
}
/*
<applet code="Nishi" width="400" height="250"></applet>
*/
11. Create a simple stopwatch application using JLabel to display time in seconds,
and JButton for start, stop, and reset. Use a Timer to update the time every second
and allow the user to start,stop, and reset the stopwatch with the corresponding
buttons.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
// Create Buttons
JButton startButton = new JButton("Start");
JButton stopButton = new JButton("Stop");
JButton resetButton = new JButton("Reset");
buttonPanel.add(startButton);
buttonPanel.add(stopButton);
buttonPanel.add(resetButton);
frame.add(buttonPanel, BorderLayout.SOUTH);
12. Write a Jtree program to show root directory and its subFolders of your System.
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.io.File;
13. Write a program to create a table of name of student, percentage and grade of
10 students using JTable.
import javax.swing.*;
import java.awt.*;
add(scrollPane, BorderLayout.CENTER);
setSize(500, 300);
setVisible(true);
}
14. Develop a Program to display the key pressed, key typed and key released event
on Applet Window.
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*
<applet code="Question_12" width="400" height="200"></applet>
*/
15. Develop a program to accept two numbers and display product of two numbers when
user presses “Multiply” button.16.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Create components
JLabel label1 = new JLabel("Enter First Number:");
JLabel label2 = new JLabel("Enter Second Number:");
JTextField textField1 = new JTextField();
JTextField textField2 = new JTextField();
JButton multiplyButton = new JButton("Multiply");
JLabel resultLabel = new JLabel("Result: ");
16. Write a program using JPasswordField and JTextField to demonstrate the use of
user authentication.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Create components
JLabel usernameLabel = new JLabel("Username:");
JTextField usernameField = new JTextField();
JLabel passwordLabel = new JLabel("Password:");
JPasswordField passwordField = new JPasswordField();
JButton loginButton = new JButton("Login");
JLabel statusLabel = new JLabel(" ", JLabel.CENTER);
// Perform authentication
if (enteredUsername.equals(correctUsername) &&
enteredPassword.equals(correctPassword)) {
statusLabel.setText("Login Successful!");
statusLabel.setForeground(Color.GREEN);
} else {
statusLabel.setText("Invalid Credentials!");
statusLabel.setForeground(Color.RED);
}
}
});
17. Write a program to count the number of clicks performed by the user in a frame.
import java.awt.*;
import java.awt.event.*;
frame.setLayout(new FlowLayout());
frame.add(button);
frame.add(label);
frame.setSize(200, 100);
frame.setVisible(true);
import java.net.*;
import java.util.Scanner;
try {
// Get the InetAddress object for the entered hostname
InetAddress inetAddress = InetAddress.getByName(hostname);
19. Write a program using URL class to retrieve the host, protocol, port and the
file of URL http:/www.msbte.org.in
import java.net.*;
} catch (MalformedURLException e) {
// Handle exception if URL is invalid
System.out.println("Invalid URL.");
}}}
20.
import java.sql.*;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/college";
String user = "root";
String password = "";
try (
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement()) {
String createTableSQL = "CREATE TABLE STUD ("
+ "id INT PRIMARY KEY, "
+ "name VARCHAR(100), "
+ "dept VARCHAR(100),"
+ "percentage FLOAT(4))";
stmt.execute(createTableSQL);
Scanner scan = new Scanner(System.in);
System.out.println("Enter Student ID: ");
int id = Integer.parseInt(scan.nextLine());
System.out.println("Enter Student Name: ");
String name = scan.next();
name = "'" + name + "'";
System.out.println("Enter Student Dept: ");
String dept = scan.next();
dept = "'" + dept + "'";
System.out.println("Enter Student Percentage: ");
float perc = scan.nextFloat();
String insertSQL = "INSERT INTO STUD VALUES (" + id + "," + name + ","
+ dept + "," +perc + ")";
stmt.executeUpdate(insertSQL);
System.out.println("Student table created and record inserted.");
scan.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/* TO RUN THIS:
javac -cp "C:\Program Files\Java\jdk1.8.0_202\jre\lib\mysql-connector-j-8.4.0.jar"
A.java
java A
*/
21. Write servlet program to send username and password using HTML forms and
authenticate the user.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
Login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<form action="LoginServlet" method="post">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>
/webapps/Manuals/
├── login.html
├── WEB-INF/
├── classes/
└── LoginServlet.class
├── lib/
└── mysql-connector-java.jar
└── web.xml
http://localhost:8080/Manuals/login.html
22. Write a program to demonstrate session tracking using cookies (Store username
and email where email will be value)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class CookieSessionServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("username")) {
username = cookie.getValue();
} else if (cookie.getName().equals("email")) {
email = cookie.getValue();
}
}
}
response.sendRedirect("CookieSessionServlet");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>
22/
├── WEB-INF/
│ ├── web.xml
│ └── classes/
│ └── CookieSessionServlet.class <-- The compiled servlet class
http://localhost:8080/22/CookieSessionServlet
23. Develop a program to display the name and roll_no of students from studenttable
having percentage > 70
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
// SQL queries to create the table, insert data, and select students with
percentage > 70
String createTableSQL = "CREATE TABLE IF NOT EXISTS studenttable (" +
"id INT(11) AUTO_INCREMENT PRIMARY KEY, " +
"name VARCHAR(100) NOT NULL, " +
"roll_no INT(11) NOT NULL, " +
"percentage FLOAT NOT NULL);";
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
while (rs.next()) {
// Retrieve the values from the result set
String name = rs.getString("name");
int rollNo = rs.getInt("roll_no");
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
// SQL queries
String createTableSQL = "CREATE TABLE IF NOT EXISTS students_info (" +
"id INT AUTO_INCREMENT PRIMARY KEY, " +
"name VARCHAR(100) NOT NULL, " +
"roll_no INT NOT NULL UNIQUE)";
try {
// Establish a connection
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
// Create table
stmt.executeUpdate(createTableSQL);
System.out.println("Table 'students_info' created successfully!");
// Insert records
stmt.executeUpdate(insertSQL1);
stmt.executeUpdate(insertSQL2);
System.out.println("Records inserted successfully!");
// Update the name "Jack" to "David"
int rowsUpdated = stmt.executeUpdate(updateSQL);
if (rowsUpdated > 0) {
System.out.println("Record updated successfully!");
} else {
System.out.println("No matching record found to update!");
}
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int rollNo = rs.getInt("roll_no");
} catch (SQLException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
while (rs.next()) {
// Retrieve values from the ResultSet
int id = rs.getInt("id");
String name = rs.getString("name");
String position = rs.getString("position");
float salary = rs.getFloat("salary");
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
// SQL queries
String createTableSQL = "CREATE TABLE IF NOT EXISTS product_info (" +
"id VARCHAR(10) NOT NULL, " +
"name VARCHAR(100) NOT NULL, " +
"price FLOAT NOT NULL)";
String deleteSQL = "DELETE FROM product_info WHERE price > 500 AND id =
'A003'";
String selectSQL = "SELECT id, name, price FROM product_info";
try {
// Establish a connection
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
// Create table
stmt.executeUpdate(createTableSQL);
System.out.println("Table 'product_info' created successfully!");
// Insert records
stmt.executeUpdate(insertSQL1);
stmt.executeUpdate(insertSQL2);
stmt.executeUpdate(insertSQL3);
stmt.executeUpdate(insertSQL4);
System.out.println("Records inserted successfully!");
while (rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
float price = rs.getFloat("price");
} catch (SQLException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
27. Develop a program to receive the parameter through HTML forms and send back
received parameter to Browser
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Example</title>
</head>
<body>
<h2>Enter your name</h2>
<form action="Exp27" method="POST">
<label for="username">Name:</label>
<input type="text" id="username" name="username" required>
<input type="submit" value="Submit">
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<servlet>
<servlet-name>Exp27</servlet-name>
<servlet-class>Exp27</servlet-class> <!-- Use the exact class name here -->
</servlet>
<servlet-mapping>
<servlet-name>Exp27</servlet-name>
<url-pattern>/Exp27</url-pattern>
</servlet-mapping>
</web-app>
webapps/
└───27/
├── index.html <-- Your HTML form file
├── WEB-INF/
│ ├── classes/ <-- Compiled servlet classes here
│ │ └── Exp27.class <-- Compiled servlet class
│ ├── web.xml <-- Your servlet configuration file
http://localhost:8080/27/index.html
28. Develop a program to send username to server and server will send length of
username to client.
Server Side
import java.io.*;
import java.net.*;
Client Side
import java.io.*;
import java.net.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Example</title>
</head>
<body>
<h2>Choose Your Preferences</h2>
<form action="Exp29" method="POST">
<!-- Dropdown List -->
<label for="option">Select an option:</label>
<select id="option" name="option">
<option value="Option1">Option 1</option>
<option value="Option2">Option 2</option>
<option value="Option3">Option 3</option>
</select>
<br><br>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<servlet>
<servlet-name>Exp29</servlet-name>
<servlet-class>Exp29</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Exp29</servlet-name>
<url-pattern>/Exp29</url-pattern>
</servlet-mapping>
</web-app>
http://localhost:8080/29/index.html
/path/to/tomcat/webapps/29/
├── index.html
├── WEB-INF/
│ ├── classes/
│ │ └── Exp29.class
│ ├── lib/
│ │ └── mysql-connector-java.jar (if DB is needed later)
│ └── web.xml
30. Develop a program to receive student subject marks through HTML forms TextField
and send the response as passed or failed in the examination.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Marks Form</title>
</head>
<body>
<h2>Enter Your Marks</h2>
<form action="Exp30" method="POST">
<label for="marks">Marks:</label>
<input type="text" id="marks" name="marks" required>
<input type="submit" value="Submit">
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<servlet>
<servlet-name>Exp30</servlet-name>
<servlet-class>Exp30</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Exp30</servlet-name>
<url-pattern>/Exp30</url-pattern>
</servlet-mapping>
</web-app>
http://localhost:8080/30/index.html
31. Write a program to check credentials of users (Client will send user ID and
password to server, and the server will authenticate the client using equals()).
Server Side
import java.io.*;
import java.net.*;
while (true) {
Socket socket = serverSocket.accept();
try (BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(),
true)) {
if (USER_ID.equals(receivedUserId) &&
PASSWORD.equals(receivedPassword)) {
out.println("Authentication Successful");
} else {
out.println("Authentication Failed");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client Side
import java.io.*;
import java.net.*;
out.println(userId);
out.println(password);
Client Side
import java.io.*;
import java.net.*;
public class Client32 {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader consoleReader = new BufferedReader(new
InputStreamReader(System.in))) {
33. Write a program to develop a prime number server (Client will send any number
to the server, and the server will respond whether the number is prime or not).
Server Side
import java.io.*;
import java.net.*;
String input;
while ((input = in.readLine()) != null) {
int number = Integer.parseInt(input);
boolean isPrime = isPrime(number);
out.println(isPrime ? "Prime" : "Not Prime");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
Client Side
import java.io.*;
import java.net.*;