Professional Documents
Culture Documents
Web Dev
Web Dev
C-4, JANAKPURI
DEPARTMENT OF COMPUTER
APPLICATIONS
SUBMITTED BY SUBMITTED TO
Yash MR. Manpreet Singh
(08021202021) (Assistant Professor)
INDEX
S.no Program Signature
1. Create a webpage that prints your name to the
screen, print your name in Tahoma font, print a
definition list with 5 items, Create links to five
different pages, etc.
2. Program to demonstrate swing components.
3. Configure Apache Tomcat and write a hello world
JSP page.
4. Write a java program that connects a database
using JDBC and does add, delete and retrieve
operations.
5. Create and develop a web application using JSF.
6. Write a program to implement a Java Beans to set
and get values.
7. Create a Java application to demonstrate Socket
Programming in Java.
8. Write a program to retrieve hostname—using
methods in Inetaddress class.
9. Write a client-server program which displays the
server machine’s date and time on the client
machine.
10. Create a table in the database containing the
columns to store book details like: book name,
authors, description, price and URL of the book’s
cover image. Using JSP and JDBC retrieve details
in the table and display them on the webpage.
11. Write a program to create a login page using Java
Beans. Also validate the username and password
from the database.
12. Create a form for inputting text and uploading image
using struts.
13. Create a Student Registration application using
Hibernate.
14. Write a program to implement MVC using Spring
Framework.
Q-1 Create a webpage that print your name to the screen, print your
name in ‘Tohoma’ font , print a definition list with 5 items, creates links to
five different pages.
CODE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Webpage</title>
<style>
body {
font-family: 'Tahoma', sans-serif;
}
</style>
</head>
<body>
<h1 style="font-family: 'Tahoma', sans-serif;">Ansh Shokeen</h1>
<h2>Definition List</h2>
<dl>
<dt>Item 1</dt>
<dd>Cake</dd>
<dt>Item 2</dt>
<dd>Donut</dd>
<dt>Item 3</dt>
<dd>Dosa</dd>
<dt>Item 4</dt>
<dd>Rice</dd>
<dt>Item 5</dt>
<dd>Apple</dd>
</dl>
<!-- Step 3: Links to Five Different Pages -->
<h2>Links to Five Different Pages</h2>
<ul>
<li><a href="page1.html">Page 1</a></li>
<li><a href="page2.html">Page 2</a></li>
<li><a href="page3.html">Page 3</a></li>
<li><a href="page4.html">Page 4</a></li>
<li><a href="page5.html">Page 5</a></li>
</ul>
</body>
</html>
OUTPUT:
Q-2 Program to Demonstrate Swing Component.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SwingDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGUI();
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Swing Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLayout(new FlowLayout());
JLabel label = new JLabel("Enter your name:");
JTextField textField = new JTextField(15);
JButton button = new JButton("Say Hello");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = textField.getText();
JOptionPane.showMessageDialog(frame, "Hello, " + name +
"!");
}
});
frame.add(label);
frame.add(textField);
frame.add(button);
// Display the frame
frame.setVisible(true);
}
}
OUTPUT:
Q-3 Configure Apache Tomcat and write, hello world servlet page.
Step-1 Install the Setup of Apache Tomcat.
OUTPUT:
<body>
#{helloWorld.getMessage()}
</body>
</html>
Step-6 Run the Application.
Q-6 Write a program to implement a Java Bean to set and get values.
Step-1 Create a file and save it as Person.java
public class person {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName (String firstname, String firstName)
{
this.firstName=firstName;
}
public String getlastName() {
return lastName;
}
public void setLastName String lastName1) {
this.lastName=lastName;
}
}
Step -2 Create another file and save it as Studentbean.java
public class CreateAJavaBean{
public static void main (String[] args) {
Person person=new Person();
person.SetFirstname("Stephon");
person.SerLastname("Withrow");
System.out.println("Java bean data:" + person.getFirstName() + "" +
person.getLastName);
}
}
Step – 3 Open a command prompt and navigate to the directory containing your
new Java programs. Then type in the command to compile the Java bean source
and hit Enter.
Step – 4 Type in the command to compile the Java application to instantiate the
Java bean and hit Enter.
Step – 5 You are ready to test your Java program. Type in the command to run the
Java runtime launcher and hit Enter. Observe the data from your Java bean.
Step-4 Next, the client will get connected and inputs the request in the form of a
string.
Step-5 When the client sends the request, the server will respond back.
Output
Q-11 Write a program to create a login page using Java Beans. Also
validate the username and password from the database.
Step:1 Create a web page "login.jsp" to login the user.
<html>
<head>
</head>
<body>
<form name="loginform" method="post" action="loginbean.jsp">
<br><br>
<table align="center"><tr><td><h2>Login Authentication</h2></td></tr></table>
<table width="300px" align="center" style="border:1px solid #000000;background-
color:#efefef;">
<tr><td colspan=2></td></tr>
<tr><td colspan=2> </td></tr>
<tr>
<td><b>Login Name</b></td>
<td><input type="text" name="userName" value=""></td>
</tr>
<tr>
<td><b>Password</b></td>
<td><input type="password" name="password" value=""></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Submit"></td>
</tr>
<tr><td colspan=2> </td></tr>
</table>
</form>
</body>
</html>
Step:2 To create a "loginbean.jsp" to set the parameter of the login.
<%@ page language="Java" import="java.sql.*" %>
<HTML>
<HEAD><TITLE>DataBase Search</TITLE></HEAD>
<BODY>
<jsp:useBean id="db" scope="request" class="logbean.LoginBean" >
<jsp:setProperty name="db" property="userName"
value="<%=request.getParameter("userName")%>"/>
<jsp:setProperty name="db" property="password"
value="<%=request.getParameter("password")%>"/>
</jsp:useBean>
<jsp:forward page="hello">
<jsp:param name="username" value="<%=db.getUserName()%>" />
<jsp:param name="password" value="<%=db.getPassword()%>" />
</jsp:forward>
</body>
</html>
Step:3 To create a "LoginBean.java" to mapping the parameter of "loginbean.jsp".
package logbean;
public class LoginBean {
String userName="";
String password="";
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Step:4 To create a Servlet "login.java" for validate the user login.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.*;
import java.sql.*;
public class login extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "user_register";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
String username="";
String userpass="";
String strQuery= "";
Statement st=null;
ResultSet rs=null;
HttpSession session = request.getSession(true);
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
if(request.getParameter("username")!=null &&
request.getParameter("username")!="" &&
request.getParameter("password")!=null &&
request.getParameter("password")!="")
{
username = request.getParameter("username").toString();
userpass = request.getParameter("password").toString();
strQuery="select * from userregister where
username='"+username+"' and password='"+userpass+"'";
System.out.println(strQuery);
st = conn.createStatement();
rs = st.executeQuery(strQuery);
int count=0;
while(rs.next())
{
session.setAttribute("username",rs.getString(2));
count++;
}
if(count>0)
{
response.sendRedirect("welcome.jsp");
}
else
{
response.sendRedirect("login.jsp");
}
}
else
{
response.sendRedirect("login.jsp");
}
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Step :5 To create the webpage "welcome.jsp" to display the message after
successful message.
<HTML>
<HEAD><TITLE>Welcome</TITLE></HEAD>
<BODY>
<br><br><br><br>
<table align="center" style="border:1px solid #000000;">
<%
if(session.getAttribute("username")!=null && session.getAttribute("username")!="")
{
String user = session.getAttribute("username").toString();
%>
<tr><td align="center"><h1>Welcome <b><%= user%></b></h1></td></tr>
<%
}
%>
</table>
</body>
<html>
OUTPUT:
Q-12 Create a form for inputting text and uploading image using struts.
Step-1 Create UserImage.jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Upload User Image</title>
</head>
<body>
<h2>
Struts2 File Upload & Save Example without Database
</h2>
<s:actionerror />
<s:form action="userImage" method="post" enctype="multipart/form-data">
<s:file name="userImage" label="Image" />
<s:submit value="Upload" align="center" />
</s:form>
</body>
</html>
Step – 2 Create Success User Image.jsp
<%@ page contentType="text/html; charset=UTF-8"%><%@ taglib prefix="s"
uri="/struts-tags"%>
<html>
<head>
<title>Success: Upload User Image</title>
</head>
<body>
<h2>
Struts2 File Upload Example
</h2>
User Image: <s:property value="userImage" /><br/>
Content Type:<s:property value="userImageContentType" /><br/>
File Name: <s:property value="userImageFileName" /><br/>
Uploaded Image: <img src="userimages/<s:property
value="userImageFileName"/>"
width="100" height="100" />
</body>
</html>
Step – 3 Create the action class
package com.javatpoint;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import com.opensymphony.xwork2.ActionSupport;
return SUCCESS;
}
public File getUserImage() {
return userImage;
}
public void setUserImage(File userImage) {
this.userImage = userImage;
}
public String getUserImageContentType() {
return userImageContentType;
}
<param name="allowedTypes">
image/png,image/gif,image/jpeg,image/pjpeg
</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success">SuccessUserImage.jsp</result>
<result name="input">UserImage.jsp</result>
</action>
</package>
</struts>
OUTPUT:
Q-13 Create a Student Registration application using Hibernate.
Step - 1 MySQL Database Setup
CREATE TABLE `users` (
`id` int(3) NOT NULL,
`first_name` varchar(20) DEFAULT NULL,
`last_name` varchar(20) DEFAULT NULL,
`username` varchar(250) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
COLLATE=utf8mb4_0900_ai_ci;
SELECT * FROM mysql_database.Student:
Step – 2 Create a JPA Entity - User.java
package net.javaguides.hibernate.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class User implements Serializable {
private static final long serialVersionUID = 1 L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "user_name")
private String username;
@Column(name = "password")
private String password;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Step – 3 Create UserDao to Save Registered User into Database
package net.javaguides.hibernate.dao;
import org.hibernate.Session;
import org.hibernate.Transaction;
import net.javaguides.hibernate.model.User;
import net.javaguides.hibernate.util.HibernateUtil;
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS,
"thread");
settings.put(Environment.HBM2DDL_AUTO, "create-drop");
configuration.setProperties(settings);
configuration.addAnnotatedClass(User.class);
ServiceRegistry serviceRegistry = new
StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Java Config serviceRegistry
created");
sessionFactory =
configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Exception e) {
e.printStackTrace();
}
}
return sessionFactory;
}
}
Step – 5 Create a UserController.java
package net.javaguides.hibernate.web;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.javaguides.hibernate.dao.UserDao;
import net.javaguides.hibernate.model.User;
/**
* @email Ramesh Fadatare
*/
@WebServlet("/register")
public class UserController extends HttpServlet {
private static final long serialVersionUID = 1 L;
private UserDao userDao;
userDao.saveUser(user);
RequestDispatcher dispatcher =
request.getRequestDispatcher("register-success.jsp");
dispatcher.forward(request, response);
}
}
Step – 6 Create a View - register.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.mi
n.css"
integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRx
T2MZw1T"
crossorigin="anonymous">
</head>
</head>
<body>
<div class="container">
<div class="row text-center" style="color: tomato;">
<h2>User Registration with JSP, Servlet and Hibernate</h2>
</div>
<hr>
<div class="row col-md-10 col-md-offset-3">
<form action="<%=request.getContextPath()%>/register"
method="post">
<div class="form-group">
<label for="uname">First Name:</label> <input type="text"
class="form-control" id="uname" placeholder="First Name"
name="firstName" required>
</div>
<div class="form-group">
<label for="uname">Last Name:</label> <input type="text"
class="form-control" id="uname" placeholder="last Name"
name="lastName" required>
</div>
<div class="form-group">
<label for="uname">User Name:</label> <input type="text"
class="form-control" id="username" placeholder="User Name"
name="username" required>
</div>
<div class="form-group">
<label for="uname">Password:</label> <input type="password"
class="form-control" id="password" placeholder="Password"
name="password" required>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Step – 7 Create a View - register-success.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.mi
n.css"
integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRx
T2MZw1T"
crossorigin="anonymous">
</head>
</head>
<body>
<div class="container">
<div class="row col-md-10 col-md-offset-3">
<div class="card card-body">
<h1>User successfully registered!</h1>
</div>
</div>
</div>
</body>
</html>
Step – 8 Run the Application and Demo
OUTPUT:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-
webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>SpringMVC</finalName>
</build>
</project>
Step – 2 Create the controller class
package com.javatpoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/")
public String display()
{
return "index";
}
}
Step – 3 Provide the entry of controller in the web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Step – 4 Define the bean in the xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
</beans>
Step- 5 Display the message in the JSP page
<html>
<body>
<p>Welcome to Spring MVC Tutorial</p>
</body>
</html>
OUTPUT: