0% found this document useful (0 votes)
88 views70 pages

Java JDBC and Servlet Programming Guide

The document outlines assignments for BCA Semester V at MIT College of Management, focusing on various Java programming implementations including JDBC, Servlets, JSP, RMI, Socket Programming, and the Spring Framework. Each section contains specific tasks such as displaying employee information, creating a shopping mall application, and implementing user login validation. The document includes code examples and descriptions for each task to guide students in their assignments.

Uploaded by

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

Java JDBC and Servlet Programming Guide

The document outlines assignments for BCA Semester V at MIT College of Management, focusing on various Java programming implementations including JDBC, Servlets, JSP, RMI, Socket Programming, and the Spring Framework. Each section contains specific tasks such as displaying employee information, creating a shopping mall application, and implementing user login validation. The document includes code examples and descriptions for each task to guide students in their assignments.

Uploaded by

Adarsh Jadhav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MIT COLLEGE OF MANAGEMENT

BCA SEM-V

Index
SR. Assignment Name Mar Sign
No ks
1: Implementation of JDBC

Q1: Write java program for display Employee information


from data base (use JDBC and MySQL) Assume
suitable database and table
Q2: Write java program for insert student information in
database (use JDBC and MySQL) Assume suitable
database and table.

2: Implementation of Servlet with JDBC, session


and Cookies
Q3: Write a servlet program to display current date and
time of server.
Q4: Design a servlet to display “Welcome IP address of
client” to first time visitor. Display “Welcome-back IP
address of client” if the user is revisiting the page.
Q5: Design the table User (username, password) Design
HTML login screen. Accept the username and
password from the user. Write a servlet program to
accept the login name and password and validates it
from the database you have created. If itis correct then
display [Link] otherwise display [Link].
Q6: Write a servlet program to create a shopping mall.
User must be allowed to do purchase from two pages.
Each page should have a page total. The third page
should display a bill, which consists of a page total of
whatever the purchase has been done and print the
total. (Use Http Session)

1
3: Implementation of JSP with JDBC, session and
Cookies
Q7: Write a JSP program to display number of times user
has visited the page. (Use cookies)
Q8: Write a JSP program to display details of products
from database in tabular format. Design Product table
in database as (pid, pname, qty, price)
Q9: Write a program, using servlet and JDBC which takes
students roll number and provides student information,
which includes the name of the student.
Q10: Write Username and password validation from
database to jsp view page
4: Implementation of RMI
Q11: Creating a Simple RMI application involves following
steps Define a remote interface. Implementing remote
interface. create and start remote application create
and start client application
5: Socket Programming
Q12: Build a Simple Chat Application Using Sockets in
Java.
6: Java Spring Framework
Q13: Design spring example print hello world in screen.
Q14: Design Spring MVC CRUD Example.
Q15: Building web application with Spring Boot

2
Topic 1: Implementation of JDBC

Q1: Write java program for display Employee information from data base
(use JDBC and MySQL) Assume suitable database and table:

File: JDBC_example.java

import [Link].*;
public class JDBC_example {
public static void main(String args[]) {
try {
[Link]("[Link]");
Connection con =
[Link]("jdbc:mysql://localhost:3306/test", "root", "");
Statement stmt = [Link]();
ResultSet rs = [Link]("select * from emp");
while ([Link]())
[Link]([Link](1) + " " + [Link](2) + " " +
[Link](3));
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}

3
Output:
File: Java_codes/JDBC_example.java
C:\xampp\tomcat\webapps\Java_codes>java JDBC_example.java
1 Amit Gaikwad
2 Hemant Kumar
3 Vedant Rajankar
4 Prashant Mahto

4
Q2: Write java program for insert student information in database (use
JDBC and MySQL) Assume suitable database and table.

File: JDBC_example_2.java
import [Link].*;
public class JDBC_example_2 {
public static void main(String args[]) {
try {
[Link]("[Link]");
Connection con =
[Link]("jdbc:mysql://localhost:3306/test", "root", "");
Statement stmt = [Link]();
[Link]("Inserting records into the table...");
String sql = "INSERT INTO student VALUES (100, 'Zara', 'Ali', 18)";
[Link](sql);
sql = "INSERT INTO student VALUES (101, 'Mahnaz', 'Fatma', 25)";
[Link](sql);
sql = "INSERT INTO student VALUES (102, 'Zaid', 'Khan', 30)";
[Link](sql);
sql = "INSERT INTO student VALUES(103, 'Sumit', 'Mittal', 28)";
[Link](sql);
[Link]("Inserted records into the table...");
[Link]();
} catch (Exception e) {
[Link](e);
}

5
}
}
Output:
File: Java_codes/JDBC_example_2.java

6
Topic 2: Implementation of Servlet with JDBC, session
and Cookies:

Q3: Write a servlet program to display current date and time of server.

File: Curr_date.java

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class DateTimeServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
[Link]("text/html");

Date currentDate = new Date();

7
PrintWriter out = [Link]();

[Link]("<html>");
[Link]("<head><title>Current Date and Time</title></head>");
[Link]("<body>");
[Link]("<h1>Current Date and Time on Server</h1>");
[Link]("<p>" + [Link]() + "</p>");
[Link]("</body>");
[Link]("</html>");

[Link]();
}
}

File: [Link]
<servlet>
<servlet-name>DateTimeServlet</servlet-name>
<servlet-class>DateTimeServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>DateTimeServlet</servlet-name>
<url-pattern>/currentDateTime</url-pattern>
</servlet-mapping>

8
Output:
File: DEMO/WEB_INF/classes/[Link]

Q4: Design a servlet to display “Welcome IP address of client” to first time


visitor. Display “Welcome-back IP address of client” if the user is revisiting
the page.

9
File: Welcome_Servlet.java
import [Link].*;
import [Link].*;
import [Link].*;
public class Welcome_Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {

[Link]("text/html");
String clientIp = [Link]()
HttpSession session = [Link](true);

String message;
if ([Link]()) {
message = "Welcome " + clientIp;
} else {
message = "Welcome-back " + clientIp;
}
PrintWriter out = [Link]();
[Link]("<html>");
[Link]("<head><title>Welcome Page</title></head>");
[Link]("<body>");
[Link]("<h1>" + message + "</h1>");
[Link]("</body>");
[Link]("</html>");
}
10
}

File: [Link]
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
version="3.1"
metadata-complete="true">

<servlet>
<servlet-name>Welcome_Servlet</servlet-name>
<servlet-class>Welcome_Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Welcome_Servlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

Output:

11
Q5: Design the table User (username, password) Design HTML login
screen. Accept the username and password from the user. Write a servlet
program to accept the login name and password and validates it from the
database you have created. If itis correct then display [Link]
otherwise display [Link].

12
File: [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<h2>Login Page</h2>
<form action="LoginServlet" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password"
required><br><br>

<button type="submit">Login</button>
</form>
</body>
</html>
File: [Link]
import [Link];
import [Link];
import [Link];
import [Link];
13
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

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

private final String dbURL = "jdbc:mysql://localhost:3306/test";


private final String dbUser = "root";
private final String dbPassword = "";

protected void doPost(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {

String username = [Link]("username");


String password = [Link]("password");

boolean isValidUser = false;


String sql = "SELECT * FROM User WHERE username = ? AND
password = ?";

try {

14
[Link]("[Link]");
try (Connection conn = [Link](dbURL, dbUser,
dbPassword);
PreparedStatement statement = [Link](sql)) {

[Link](1, username);
[Link](2, password);

ResultSet resultSet = [Link]();

if ([Link]()) {
isValidUser = true;
}
}
} catch (Exception e) {
[Link]();
}

if (isValidUser) {
[Link]("[Link]");
} else {
[Link]("[Link]");
}
}
}

File: [Link]
15
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
</head>
<body>
<h2>Welcome to the System!</h2>
</body>
</html>

File: Database Structure

Output:

File: Login_Project\[Link]

16
File: Login_Project\[Link]

File: Login_Project\[Link]

17
Q6: Write a servlet program to create a shopping mall. User must be
allowed to do purchase from two pages. Each page should have a page

18
total. The third page should display a bill, which consists of a page total of
whatever the purchase has been done and print the total. (Use Http
Session)

File: [Link]

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/shoppingPage1")
public class ShoppingPage1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
HttpSession session = [Link]();
int page1Total = 0;
String[] items = [Link]("item1");
if (items != null) {
for (String item : items) {
page1Total += [Link](item);
}
}
[Link]("page1Total", page1Total);

19
[Link]("shoppingPage2");
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h2>Shopping Page 1</h2>");
[Link]("<form action='shoppingPage1' method='post'>");
[Link]("<input type='checkbox' name='item1' value='100'> Item A -
$100<br>");
[Link]("<input type='checkbox' name='item1' value='200'> Item B -
$200<br>");
[Link]("<input type='checkbox' name='item1' value='300'> Item C -
$300<br>");
[Link]("<input type='submit' value='Continue to Page 2'>");
[Link]("</form>");
}
}

File: [Link]

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
20
import [Link];
@WebServlet("/shoppingPage2")
public class ShoppingPage2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
HttpSession session = [Link]();
int page2Total = 0;
String[] items = [Link]("item2");
if (items != null) {
for (String item : items) {
page2Total += [Link](item);
}
}
[Link]("page2Total", page2Total);
[Link]("bill");
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h2>Shopping Page 2</h2>");
[Link]("<form action='shoppingPage2' method='post'>");
[Link]("<input type='checkbox' name='item2' value='150'> Item D -
$150<br>");
[Link]("<input type='checkbox' name='item2' value='250'> Item E -
$250<br>");

21
[Link]("<input type='checkbox' name='item2' value='350'> Item F -
$350<br>");
[Link]("<input type='submit' value='Generate Bill'>");
[Link]("</form>");
}
}

File: [Link]

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/bill")
public class Bill extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
HttpSession session = [Link]();
[Link]("text/html");
PrintWriter out = [Link]();
Integer page1Total = (Integer) [Link]("page1Total");
Integer page2Total = (Integer) [Link]("page2Total");

22
int finalTotal = (page1Total != null ? page1Total : 0) + (page2Total != null
? page2Total : 0);
[Link]("<h2>Final Bill</h2>");
[Link]("Page 1 Total: $" + (page1Total != null ? page1Total : 0) +
"<br>");
[Link]("Page 2 Total: $" + (page2Total != null ? page2Total : 0) +
"<br>");
[Link]("<strong>Total Amount: $" + finalTotal + "</strong>");
}
}

File: [Link]

<!DOCTYPE web-app PUBLIC


"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"[Link]
<web-app>
<servlet>
<servlet-name>ShoppingPage1</servlet-name>
<servlet-class>ShoppingPage1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShoppingPage1</servlet-name>
<url-pattern>/shoppingPage1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ShoppingPage2</servlet-name>
<servlet-class>ShoppingPage2</servlet-class>

23
</servlet>
<servlet-mapping>
<servlet-name>ShoppingPage2</servlet-name>
<url-pattern>/shoppingPage2</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Bill</servlet-name>
<servlet-class>Bill</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Bill</servlet-name>
<url-pattern>/bill</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>

Output:
File: Shopping_mall\[Link]

24
File: Shopping_mall\[Link]

File: [Link]

25
Topic: 3: Implementation of JSP with JDBC, session and
Cookies

Q7: Write a JSP program to display number of times user has visited the
page. (Use cookies)

File: Count_view.jsp
<%@ page import="[Link]" %>
<%@ page import="[Link].*" %>
<%
int visitCount = 0;
boolean isNewUser = true;
String visitCountCookieName = "visitCount";
Cookie[] cookies = [Link]();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ([Link]().equals(visitCountCookieName)) {
visitCount = [Link]([Link]());
isNewUser = false;
break;
}
}
}
visitCount++;
Cookie visitCookie = new Cookie(visitCountCookieName,
[Link](visitCount));
[Link](60 * 60 * 24 * 365); // Cookie expiration time: 1 year
[Link](visitCookie);

26
%>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page Visit Counter</title>
</head>
<body>
<h2>Welcome to the page!</h2>
<%
if (isNewUser) {
[Link]("<p>This is your first visit to this page!</p>");
} else {
[Link]("<p>You have visited this page " + visitCount + "
times.</p>");
}
%>
</body>
</html>
Output: JSP_Programs\Count_view.jsp

27
Q8: Write a JSP program to display details of products from database in
tabular format. Design Product table in database as (pid, pname, qty,
price)

File: Display_Program.jsp

<%@ page import="[Link].*" %>


<%@ page import="[Link].*" %>
<%
String jdbcURL = "jdbc:mysql://localhost:3306/test";
String jdbcUsername = "root";
String jdbcPassword = "";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
[Link]("[Link]");
conn = [Link](jdbcURL, jdbcUsername,
jdbcPassword);
String sql = "SELECT * FROM Product";
stmt = [Link]();
rs = [Link](sql);
%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Product List</title>

28
<style>
table {
width: 50%;
border-collapse: collapse;
margin: 20px auto;
}
table, th, td {
border: 1px solid black;
padding: 10px;
text-align: center;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h2 style="text-align: center;">Product Details</h2>
<table>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<%
while ([Link]()) {

29
%>
<tr>
<td><%= [Link]("pid") %></td>
<td><%= [Link]("pname") %></td>
<td><%= [Link]("qty") %></td>
<td><%= [Link]("price") %></td>
</tr>
<%
}
%>
</table>
<%
} catch (Exception e) {
[Link]("<p>Error: " + [Link]() + "</p>");
} finally {
if (rs != null) try { [Link](); } catch (SQLException ignore) {}
if (stmt != null) try { [Link](); } catch (SQLException ignore) {}
if (conn != null) try { [Link](); } catch (SQLException ignore) {}
}
%>
</body>
</html>
Database:

30
Output: JSP_Program/Display_Product.jsp

31
Q9: Write a program, using servlet and JDBC which takes students roll
number and provides student information, which includes the name of the
student
File: [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Information</title>
</head>
<body>
<h2>Enter Student Roll Number</h2>
<form method="post" action="StudentInfoServlet">
Roll Number: <input type="text" name="roll_no">
<input type="submit" value="Get Student Info">
</form>
</body>
</html>

File: [Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

32
import [Link];
import [Link];
import [Link];
@WebServlet("/StudentInfoServlet")
public class StudentInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/test";
private static final String JDBC_USER = "root";
private static final String JDBC_PASSWORD = "";
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String rollNo = [Link]("roll_no");
String studentName = null;
if (rollNo != null && ![Link]().isEmpty()) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
[Link]("[Link]");
conn = [Link](JDBC_URL, JDBC_USER,
JDBC_PASSWORD);
String sql = "SELECT name FROM Student WHERE roll_no = ?";
pstmt = [Link](sql);
[Link](1, [Link](rollNo));
rs = [Link]();
if ([Link]()) {
studentName = [Link]("name");
}

33
} catch (Exception e) {
[Link]();
} finally {
try { if (rs != null) [Link](); } catch (Exception e) {
[Link](); }
try { if (pstmt != null) [Link](); } catch (Exception e) {
[Link](); }
try { if (conn != null) [Link](); } catch (Exception e) {
[Link](); }
}
}
[Link]("rollNo", rollNo);
[Link]("studentName", studentName);
RequestDispatcher dispatcher =
[Link]("[Link]");
[Link](request, response);
}
}

File: [Link]
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Information</title>
</head>
<body>
<%
34
String rollNo = (String) [Link]("rollNo");
String studentName = (String) [Link]("studentName");
%>
<h2>Student Information</h2>
<%
if (rollNo != null && studentName != null) {
%>
<p><strong>Roll Number:</strong> <%= rollNo %></p>
<p><strong>Name:</strong> <%= studentName %></p>
<%
} else if (rollNo != null) {
%>
<p>No student found with Roll Number: <%= rollNo %></p>
<%
} else {
%>
<p>Please enter a roll number.</p>
<%
}
%>
</body>
</html>

35
File: [Link]
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"[Link]
<web-app>
<servlet>
<servlet-name>StudentInfoServlet</servlet-name>
<servlet-class>StudentInfoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentInfoServlet</servlet-name>
<url-pattern>/StudentInfoServlet</url-pattern>
</servlet-mapping>
</web-app>

Database:

36
Output:

JSP_Program\[Link] :

JSP_Program\StudentInfoServlet :

37
Q10: Write Username and password validation from database to jsp view
page

File: [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form method="post" action="LoginServlet">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" value="Login">
</form>
</body>
</html>

File: [Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
38
import [Link];
import [Link];
import [Link];
import [Link];

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

private static final String JDBC_URL = "jdbc:mysql://localhost:3306/test";


private static final String JDBC_USER = "root";
private static final String JDBC_PASSWORD = "";

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
String username = [Link]("username");
String password = [Link]("password");
boolean isValidUser = false;

if (username != null && password != null) {


Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;

try {
[Link]("[Link]");
conn = [Link](JDBC_URL, JDBC_USER,
JDBC_PASSWORD);

39
String sql = "SELECT * FROM user WHERE username = ? AND
password = ?";
pstmt = [Link](sql);
[Link](1, username);
[Link](2, password);
rs = [Link]();
if ([Link]()) {
isValidUser = true;
}
} catch (Exception e) {
[Link]();
} finally {
try { if (rs != null) [Link](); } catch (Exception e) {
[Link](); }
try { if (pstmt != null) [Link](); } catch (Exception e) {
[Link](); }
try { if (conn != null) [Link](); } catch (Exception e) {
[Link](); }
}
}
[Link]("isValidUser", isValidUser);
[Link]("username", username);
RequestDispatcher dispatcher =
[Link]("[Link]");
[Link](request, response);
}
}

40
File: [Link]
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Result</title>
</head>
<body>
<%
Boolean isValidUser = (Boolean) [Link]("isValidUser");
String username = (String) [Link]("username");
%>
<h2>Login Result</h2>
<%
if (isValidUser != null && isValidUser) {
%>
<p>Welcome, <strong><%= username %></strong>! You have
successfully logged in.</p>
<%
} else {
%>
<p>Invalid username or password. Please try again.</p>
<%
}
%>
</body>
</html>
41
File: [Link]
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"[Link]
<web-app>

<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>

Database:

42
Output:
JSP_Program\[Link] :

JSP_Program\[Link] :

43
4: Implementation of RMI

Q11: Creating a Simple RMI application involves following steps Define a


remote interface. Implementing remote interface. create and start remote
application create and start client application

File: server/[Link]
package server;
import [Link];
import [Link];

public class RMIServer {


public static void main(String[] args) {
try {
[Link](1100);

HelloImpl hello = new HelloImpl();

[Link]("rmi://localhost:1100/HelloService", hello);

[Link]("Server is ready.");
} catch (Exception e) {
[Link]("Server exception: " + [Link]());
[Link]();
}
}
}

44
File: server/[Link]
package server;

import [Link];
import [Link];

public interface Hello extends Remote {


String sayHello() throws RemoteException;
}

File: server/[Link]
package server;

import [Link];
import [Link];

public class HelloImpl extends UnicastRemoteObject implements Hello {


private static final long serialVersionUID = 1L;

public HelloImpl() throws RemoteException {


super();
}
@Override
public String sayHello() throws RemoteException {
return "Hello, world!";
}
}

45
File: client/[Link]
package client;

import [Link];

import [Link];

public class RMIClient {


public static void main(String[] args) {
try {

Hello hello = (Hello)


[Link]("rmi://localhost:1100/HelloService");

String response = [Link]();


[Link]("Response from server: " + response);
} catch (Exception e) {
[Link]();
}
}
}

Output:
C:\Program Files\Apache Software Foundation\Tomcat
9.0\webapps\RMI_Programs\build>java -cp . [Link]
Server is ready.

46
Output:
C:\Program Files\Apache Software Foundation\Tomcat
9.0\webapps\RMI_Programs\build>java -cp . [Link]
Response from server: Hello, world!

47
Topic 5: Socket Programming

Q12: Build a Simple Chat Application Using Sockets in Java

File: [Link]
import [Link].*;
import [Link].*;
class MyServer1{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=[Link]();
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
String str="",str2="";
while(![Link]("stop")){
str=[Link]();
[Link]("client says: "+str);
str2=[Link]();
[Link](str2);
[Link]();
}
[Link]();
[Link]();
[Link]();
}
}

48
File: [Link]
import [Link].*;
import [Link].*;
class MyClient1{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
String str="",str2="";
while(![Link]("stop")){
str=[Link]();
[Link](str);
[Link]();
str2=[Link]();
[Link]("Server says: "+str2);
}
[Link]();
[Link]();
}}

Output:
C:\Program Files\Apache Software Foundation\Tomcat
9.0\webapps\Socket_Programming>java [Link]
client says: hi
hello

49
Output:
C:\Program Files\Apache Software Foundation\Tomcat
9.0\webapps\Socket_Programming>java [Link]
hi
Server says: hello

50
Topic 6: Java Spring Framework

Q13: Design spring example print hello world in screen

File: HelloSpring/src/[Link]/[Link]
package [Link];
public class HelloWorld {
private String message;

public void setMessage(String message){


[Link] = message;
}
public void getMessage(){
[Link]("Your Message : " + message);
}
}

File: HelloSpring/src/[Link]/[Link]
package [Link];

import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("[Link]");

51
HelloWorld obj = (HelloWorld) [Link]("helloWorld");
[Link]();
}
}

File: HelloSpring/src/[Link]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns = "[Link]
xmlns:xsi = "[Link]
xsi:schemaLocation = "[Link]
[Link]

<bean id = "helloWorld" class = "[Link]">


<property name = "message" value = "Hello World!"/>
</bean>
</beans>

Output :

52
Q14: Design Spring MVC CRUD Example.

File Structure:

53
File: src/main/java/com/javatpoint/beans/[Link]
package [Link];

public class Emp {


private int id;
private String name;
private float salary;
private String designation;

public int getId() {


return id;
}
public void setId(int id) {
[Link] = id;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
[Link] = salary;
}

54
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
[Link] = designation;
}

File: src/main/java/com/javatpoint/controllers/[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Controller
public class EmpController {
@Autowired
EmpDao dao;//will inject dao from xml file
@RequestMapping("/empform")
public String showform(Model m){

55
[Link]("command", new Emp());
return "empform";
}
@RequestMapping(value="/save",method = [Link])
public String save(@ModelAttribute("emp") Emp emp){
[Link](emp);
return "redirect:/viewemp";//will redirect to viewemp request mapping
}
@RequestMapping("/viewemp")
public String viewemp(Model m){
List<Emp> list=[Link]();
[Link]("list",list);
return "viewemp";
}
@RequestMapping(value="/editemp/{id}")
public String edit(@PathVariable int id, Model m){
Emp emp=[Link](id);
[Link]("command",emp);
return "empeditform";
}
@RequestMapping(value="/editsave",method = [Link])
public String editsave(@ModelAttribute("emp") Emp emp){
[Link](emp);
return "redirect:/viewemp";
}
@RequestMapping(value="/deleteemp/{id}",method = [Link])
public String delete(@PathVariable int id){

56
[Link](id);
return "redirect:/viewemp";
}
}

File: src/main/java/com/javatpoint/dao/[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class EmpDao {


JdbcTemplate template;

public void setTemplate(JdbcTemplate template) {


[Link] = template;
}
public int save(Emp p){
String sql="insert into Emp99(name,salary,designation)
values('"+[Link]()+"',"+[Link]()+",'"+[Link]()+"')";
return [Link](sql);
}
public int update(Emp p){

57
String sql="update Emp99 set name='"+[Link]()+"',
salary="+[Link]()+",designation='"+[Link]()+"' where
id="+[Link]()+"";
return [Link](sql);
}
public int delete(int id){
String sql="delete from Emp99 where id="+id+"";
return [Link](sql);
}
public Emp getEmpById(int id){
String sql="select * from Emp99 where id=?";
return [Link](sql, new Object[]{id},new
BeanPropertyRowMapper<Emp>([Link]));
}
public List<Emp> getEmployees(){
return [Link]("select * from Emp99",new RowMapper<Emp>(){
public Emp mapRow(ResultSet rs, int row) throws SQLException {
Emp e=new Emp();
[Link]([Link](1));
[Link]([Link](2));
[Link]([Link](3));
[Link]([Link](4));
return e;
}
});
}
}

58
File: src/main/webapp/[Link]

<a href="empform">Add Employee</a>


<a href="viewemp">View Employees</a>

File: src/main/webapp/WEB-INF/jsp/[Link]
<%@ taglib uri="[Link]
prefix="form"%>
<%@ taglib uri="[Link] prefix="c"%>

<h1>Add New Employee</h1>


<form:form method="post" action="save">
<table >
<tr>
<td>Name : </td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Salary :</td>
<td><form:input path="salary" /></td>
</tr>
<tr>
<td>Designation :</td>
<td><form:input path="designation" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Save" /></td>
59
</tr>
</table>
</form:form>

File: src/main/webapp/WEB-INF/jsp/[Link]

<%@ taglib uri="[Link]


prefix="form"%>
<%@ taglib uri="[Link] prefix="c"%>

<h1>Edit Employee</h1>
<form:form method="POST"
action="/SpringMVCCRUDSimple/editsave">
<table >
<tr>
<td></td>
<td><form:hidden path="id" /></td>
</tr>
<tr>
<td>Name : </td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Salary :</td>
<td><form:input path="salary" /></td>
</tr>
<tr>
<td>Designation :</td>

60
<td><form:input path="designation" /></td>
</tr>

<tr>
<td> </td>
<td><input type="submit" value="Edit Save" /></td>
</tr>
</table>
</form:form>

File: src/main/webapp/WEB-INF/jsp/[Link]

<%@ taglib uri="[Link]


prefix="form"%>
<%@ taglib uri="[Link] prefix="c"%>

<h1>Employees List</h1>
<table border="2" width="70%" cellpadding="2">
<tr><th>Id</th><th>Name</th><th>Salary</th><th>Designation</th><t
h>Edit</th><th>Delete</th></tr>
<c:forEach var="emp" items="${list}">
<tr>
<td>${[Link]}</td>
<td>${[Link]}</td>
<td>${[Link]}</td>
<td>${[Link]}</td>
<td><a href="editemp/${[Link]}">Edit</a></td>
<td><a href="deleteemp/${[Link]}">Delete</a></td>

61
</tr>
</c:forEach>
</table>
<br/>
<a href="empform">Add New Employee</a>

File: src/main/webapp/WEB-INF/[Link]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xmlns:p="[Link]
xmlns:context="[Link]
xsi:schemaLocation="[Link]
[Link]
[Link]
[Link]

<context:component-scan base-
package="[Link]"></context:component-scan>

<bean
class="[Link]">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

<bean id="ds"
class="[Link]">

62
<property name="driverClassName"
value="[Link]"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
</bean>

<bean id="jt" class="[Link]">


<property name="dataSource" ref="ds"></property>
</bean>

<bean id="dao" class="[Link]">


<property name="template" ref="jt"></property>
</bean>
</beans>

File: src/main/webapp/WEV-INF/[Link]

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


<web-app xmlns:xsi="[Link]
xmlns="[Link]
xsi:schemaLocation="[Link]
[Link] id="WebApp_ID"
version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>[Link]</servlet-
class>

63
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

File: target/[Link]

<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>
<groupId>[Link]</groupId>
<artifactId>SpringMVCPagination</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringMVCPagination Maven Webapp</name>
<url>[Link]
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
64
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-beans</artifactId>
<version>[Link]</version>
</dependency>

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-webmvc</artifactId>
<version>[Link]</version>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.12</version>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>[Link]-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

65
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-jdbc</artifactId>
<version>[Link]</version>
</dependency>
</dependencies>
<build>
<finalName>SpringMVCPagination</finalName>
</build>
</project>

Database:

66
Output:

67
Q15: Building web application with Spring Boot

File:
src/main/java/com/example/hellospringboot/[Link]

package [Link];

import [Link];
import [Link];

@SpringBootApplication
public class HelloSpringBootApplication {

public static void main(String[] args) {


[Link]([Link], args);
}
}

File:
src/main/java/com/example/hellospringboot/controller/[Link]

package [Link];

import [Link];
import [Link];

@RestController
public class HelloController {

68
@GetMapping("/hello")
public String sayHello() {
return "Hello, Spring Boot!";
}
}
File Structure:

Output:

69
70

You might also like