Web Dev Randeep
Web Dev Randeep
INDEX
4. Write a java program that connects a database using JDBC and does add, delete and
retrieve operations.
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.
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>
4
<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>
5
Output:
6
Output:
8
SOURCE CODE
10
11
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
class Mysql ,
public static void main(String*+ args) ,
String url="jdbc:mysql://localhost:3386/"jdbcdemo";
String username="root";
String password="";
try ,
Class.forName("com.mysql.cj,jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username,
passowrd);
statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuerry(sql:"select * from
student");
while (resultSet.next()) ,
system.out.println(resultSet.getInt(columnindex
1)+""+resultSet.getString(Columindex 2)+resultSet.getInt())
-
connection.close();
-
- catch( Exception e),
System.out.println(e);
12
-
-
Step – 1 Open Xampp and run the Server
Step – 2 Now make a table name “Student” and fill the entries.
OUTPUT:
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.7</version>
</dependency>
</dependencies>
<build>
<finalName>helloworld</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step-2 Prepare Eclipse Project
Step-3 Import Project in Eclipse
15
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-
startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>
Step-5 Create a jsf File.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
17
<title>JSF Tutorial!</title>
</head>
<body>
#,helloWorld.getMessage()-
</body>
</html>
Step-6 Run the Application.
18
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.
20
-
String line = "";
while (!line.equals("Over"))
,
try
,
line = input.readLine(); out.writeUTF(line);
-
catch(IOException i)
,
System.out.println(i);
-
-
try
,
input.close(); out.close();
socket.close();
-
catch(IOException i)
,
System.out.println(i);
-
-
public static void main(String args*+) , Client
client = new Client("127.0.0.1", 5000);
-
-
Step – 2 Write a program to implement socket connection at server side.
22
import java.net.*;
import java.io.*; public
class ServerSide
,
private Socket socket = null; private
ServerSocket server = null; private
DataInputStream in = null; public
Server(int port)
,
// starts server and waits for a connection try,
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ..."); socket =
server.accept();
System.out.println("Client accepted"); in =
new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = ""; while
(!line.equals("Over"))
,
try
,
line = in.readUTF(); System.out.println(line);
-
catch(IOException i)
,
System.out.println(i);
-
23
-
System.out.println("Closing connection");
socket.close(); in.close();
-
catch(IOException i), System.out.println(i);
-
-
public static void main(String args*+),
Server server = new Server(5000);
-
-
Step- 3 When you run the server side script, it will start and wait for the client to get started.
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.
24
OUTPUT:
25
//Data Client.Java
import java.io.*; import
java.net.*; class
DateClient
,
public static void main(String args*+) throws Exception
,
Socket soc=new Socket(InetAddress.getLocalHost(),5217);
BufferedReader in=new BufferedReader(new
InputStreamReader(soc.getInputStream() ));
System.out.println(in.readLine());
-
-
//DataServer.Java
import java.net.*;
import java.io.*; import
java.util.*; class
DateServer
,
public static void main(String args*+) throws Exception
,
ServerSocket s=new ServerSocket(5217);
while(true)
,
26
try ,
PrintWriter out = response.getWriter();
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/msi",
"root", "root");
String n = request.getParameter("txtName");
String p = request.getParameter("txtPwd");
PreparedStatement ps = con.prepareStatement("select uname from login
where uname=? and password=?"); ps.setString(1,n); ps.setString(2,p);
ResultSet rs = ps.executeQuery();
if(rs.next()) ,
RequestDispatcher
rd=request.getRequestDispatcher("welcome.jsp");
rd.forward(request,response);
-
else ,
out.println("<font color=red size=18>Login Failed!!<br>");
out.println("<a href=login.jsp>Try Again!!</a>");
-
- catch (ClassNotFoundException e) ,
e.printStackTrace();
- catch (SQLException e) ,
e.printStackTrace();
-
-
-
30
Output
32
33
</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;
35
-
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 ,
36
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");
37
-
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>
38
39
</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;
-
<struts>
<package name="fileUploadPackage" extends="struts-default">
<action name="userImage" class="com.javatpoint.FileUploadAction">
<interceptor-ref name="fileUpload">
<param name="maximumSize">2097152</param>
<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>
43
-
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;
org.hibernate.service.ServiceRegistry; import
net.javaguides.hibernate.model.User;
/**
* Java based configuration
* @author ramesh Fadatare
* */
public class HibernateUtil ,
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() ,
if (sessionFactory == null) , try ,
Configuration configuration = new Configuration();
// Hibernate settings equivalent to hibernate.cfg.xml's properties
Properties settings = new Properties();
settings.put(Environment.DRIVER, "com.mysql.jdbc.Driver");
settings.put(Environment.URL,
"jdbc:mysql://localhost:3306/demo?useSSL=false");
settings.put(Environment.USER, "root");
settings.put(Environment.PASS, "root");
settings.put(Environment.DIALECT,
"org.hibernate.dialect.MySQL5Dialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS,
"thread"); settings.put(Environment.HBM2DDL_AUTO,
"create-drop"); configuration.setProperties(settings);
configuration.addAnnotatedClass(User.class);
48
e.printStackTrace();
-
-
return sessionFactory;
-
-
Step – 5 Create a UserController.java package
net.javaguides.hibernate.web;
import java.io.IOException;
/**
* @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>
51
<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.
min.css"
integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZ
w1T" 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">
<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">
53
</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"
54
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.
min.css" integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZ
w1T" 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:
55
56
<!-- https://mvnrepository.com/artifact/org.springframework/springwebmvc -
->
<dependency>
57
<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()
,
58
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"
59
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>
60