ADV. Java File - Shahid Khan
ADV. Java File - Shahid Khan
Advanced Java
Practical File
INDEX
S.NO Topics/Programs
1. Write Servlet application to print current date & time
Below program shows how to print the current date and time. We can use simple
Date object with toString() to print current date and time.
DateSrv.java
import java.io.*;
import javax.servlet.*;
Output:
4
HTML files generate static web pages, servlet components generate dynamic
webpages, so to make static webpages talking to dynamic webpages we need to go
for HTML to servlet communication.
HTML to servlet communication is possible in 3 ways,
1) Using hyperlinks:- The hyperlinks are used to send requests without having
end-user supplied data. Example:- getting current trending jobs, show trending
news, get all employees.
2) Using forms:- The forms are used to send requests to servlet components
having end-user-supplied inputs. Example:- login page/form, registration form
page, payment form/page
3) Using JavaScript:- To send requests to servlet component based on different
Java-script events that are raised from different components. Examples:-
• OnLoad event:- Pages where we need to choose our country. When the web
page is loaded, the request fetches all available countries given in the servlet
components and puts them in the select box.
• OnBlur event:- After choosing a new email id, the request goes
automatically to check whether it is already available or not. Here form
component losing the focus.
• OnChange event:- OnChange event raises when we select items from the
select box. When we select a country in a select box then it sends a request
and gets all list of states from the servlet component and puts them in
another select box.
“good night”. In all the cases, generated page (by servlet component) should also
contain a hyperlink to return back to the home (i.e. servlet component to an HTML
page).
To get the current hour of the day you can use the below code. The “hour” variable
will get the value in 24-hour format, not in the 12-hour format, therefore write your
code accordingly.
Form Validations
In the HTML to Servlet communication using Form, we were not validating
whether the entered data is valid or not. Before accepting the data entered by the
end-user, and performing business operations we must check the input values. If
the input values are valid then only perform the business operations, else don’t
perform.
There are different technique to perform form validations:
• Placing form validation logic only on the server-side.
• Placing form validation logic only on the client-side.
• Place form validation logic both on the server-side and client-side.
7
• Place form validation logic both in server-side and client-side, but execute
server-side form validation logic only when client-side form validation logic
is not executed.
8
When we need to refresh the web page automatically after some time, we use
JSP setIntHeader() method. This method sends back header "Refresh" to the
browser along with an integer value which indicates time interval in seconds. It is
used when we need to display live game score, share market status etc.
Below example shows how to use setIntHeader() method to set Refresh header to
simulate a digital clock.
auto-refresh.jsp
<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Auto Refresh</title>
</head>
<body>
<center>
<form>
<fieldset style="width:20%; background-color:#e6ffe6;">
<legend>Auto refresh</legend>
<h2>Auto Refresh Example</h2>
<%
// Set refresh, autoload time as 1 seconds
response.setIntHeader("Refresh", 1);
// Get current time
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
9
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
out.println("Crrent Time: " + CT + "\n");
%>
</fieldset>
</form>
</center>
</body>
</html>
web.xml
<web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<jsp-file>/auto-refresh.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
Output:
10
This example describes how to use the HttpSession object to find out the creation
time and the last-accessed time for a session. We would associate a new session
with the request if one does not already exist.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
12
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td>
</tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime + " </td>
</tr>\n" +
"<tr>\n" +
" <td>Time of Last Access</td>\n" +
13
"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID + " </td>
</tr>\n" +
"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td>
</tr>\n" +
"</table>\n" +
"</body>
</html>"
);
}
}
Compile the above servlet SessionTrack and create appropriate entry in web.xml
file. Now running http://localhost:8080/SessionTrack would display the following
result when you would run for the first time −
14
Now try to run the same servlet for second time, it would display following result.
15
16
Example on how to select/ fetch records from a table using JDBC application :
Before executing the following example, make sure you have the following in
place −
• To execute the following example, you can replace
the username and password with your actual username and password.
• Your MySQL or whatever database you are using is up and running.
Required Steps
The following steps are required to create a new Database using JDBC application:
• Import the packages − Requires that you include the packages containing
the JDBC classes needed for database programming. Most often,
using import java.sql.* will suffice.
• Open a connection − Requires using
the DriverManager.getConnection() method to create a Connection object,
which represents a physical connection with a database server.
• Execute a query − Requires using an object of type Statement for building
and submitting an SQL statement to select (i.e. fetch ) records from a table.
• Extract Data − Once SQL query is executed, you can fetch records from the
table.
• Clean up the environment − try with resources automatically closes the
resources.
Sample Code
17
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
19
Here, we are going to create the simple example to create the login form using
servlet. We have used oracle10g as the database. There are 5 files required for this
application.
• index.html
• FirstServlet.java
• LoginDao.java
• SecondServlet.java
• web.xml
You must need to create a table userreg with name and pass fields. Moreover, it
must have contained some data. The table should be as:
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="username"/><br/><br/>
Password:<input type="password" name="userpass"/><br/><br/>
<input type="submit" value="login"/>
</form>
FirstServlet.java
import java.io.IOException;
import java.io.PrintWriter;
20
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
String p=request.getParameter("userpass");
if(LoginDao.validate(n, p)){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request,response);
}
else{
out.print("Sorry username or password error");
RequestDispatcher rd=request.getRequestDispatcher("index.html");
21
rd.include(request,response);
}
out.close();
}
}
LoginDao.java
import java.sql.*;
public class LoginDao {
public static boolean validate(String name,String pass){
boolean status=false;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement(
"select * from userreg where name=? and pass=?");
ps.setString(1,name);
ps.setString(2,pass);
ResultSet rs=ps.executeQuery();
status=rs.next();
}catch(Exception e){System.out.println(e);}
return status;
}
22
}
WelcomeServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
out.print("Welcome "+n);
out.close();
}
}
23
• To execute the following example you can replace the username and
password with your actual user name and password.
Required Steps
The following steps are required to create new Database using JDBC application :
• Import the packages − Requires that you include the packages containing the
JDBC classes needed for database programming. Most often, using import
java.sql.* will suffice.
• Register the JDBC driver − Requires that you initialize a driver so you can
open a communications channel with the database.
Sample Code
Copy and paste the following example in JDBCExample.java, compile and run as
follows:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
When first time servlet runs then session is created and value of the counter will be
zero and after access of servlet again, the counter value will be increased by one.
CounterServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Output:
28
In below example we create teacher registration page in html which accepts id,
name and address. After clicking submit button, all data gets stored in the database.
register.html
<!doctype html>
<body>
<form action="servlet/Register" method="post">
<fieldset style="width:20%; background-color:#ccffeb">
<h2 align="center">Registration form</h2><hr>
<table>
<tr>
<td>TId</td>
<td><input type="text" name="TId" required /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="Name" required /></td>
</tr>
<tr>
<td>Address</td>
<td><textarea name="address" placeholder="Enter address
here..."></textarea></td>
</tr>
<tr>
<td><input type="reset" value="Reset"/></td>
<td><input type="submit" value="Register"/></td>
29
</tr>
</table>
</fieldset>
</form>
</body>
</html>
Register.java
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
ps.setInt(1, id);
30
ps.setString(2,name);
ps.setString(3,address);
int i = ps.executeUpdate();
if(i>0)
out.print("You are successfully registered...");
}
catch (Exception ex)
{
ex.printStackTrace();
}
out.close();
}
}
web.xml
<web-app>
<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/servlet/Register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>register.html</welcome-file>
</welcome-file-list>
</web-app>
Output:
31
32
In this example we will check if the user is eligible for voting or not. If the age is
greater than 17, then user is eligible to vote. There is one html page which takes
name and age from the user.
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>VoterApp</title>
</head>
<body>
<form action= "vturl" method="get">
<fieldset style="width:20%; background-color:#80ffcc">
<table>
<tr><td>Name</td><td><input type="text"
name="name"></td></tr>
<tr><td>Age</td><td><input type="text" name="age"></td></tr>
<tr><td></td><td><input type = "submit" value="check voting
eligibility"></td></tr>
</table>
</fieldset>
</form>
33
</body>
</html>
VoterSrv.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class VoterSrv extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res) throws
IOException,ServletException
{
//set response content type
res.setContentType("text/html");
//get printWrite obj
PrintWriter pw = res.getWriter();
//read form data from page as request parameter
String name = req.getParameter("name");
int age = Integer.parseInt(req.getParameter("age"));
if (age>=18)
{
pw.println("<font color='green' size='4'>"+name+" you are eligible to
vote</font>");
}
34
else
pw.println("<font color='red' size='4'>"+name+" you are not eligible to
vote</font>");
//add hyperlink to dynamic page
pw.println("<br><br><a href= 'index.html'>Home</a>");
//close the stream
pw.close();
}
}
web.xml
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>VoterSrv</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/vturl</url-pattern>
</servlet-mapping>
</web-app>
Output:
35
36
package com.vaannila.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.vaannila.form.HelloWorldForm;
@Override
42
Here we typecast the ActionForm to HelloWorldForm and set the message value.
Add the following entries in the struts-config.xml file.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<struts-config>
<form-beans>
<form-bean name="helloWorldForm"
type="com.vaannila.form.HelloWorldForm"/>
</form-beans>
<global-forwards>
<forward name="helloWorld" path="/helloWorld.do"/>
43
</global-forwards>
<action-mappings>
<action path="/helloWorld" type="com.vaannila.action.HelloWorldAction"
name="helloWorldForm">
<forward name="success" path="/helloWorld.jsp" />
</action>
</action-mappings>
</struts-config>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
44
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
When we run the application the index.jsp page will be executed first. In
the index.jsp page we redirect the request to the helloWorld.do URI, which inturn
invokes the HelloWorldAction.
After creating all the files the directory structure of the application looks like this.
46
On executing the application, the "Hello World" message gets displayed to the
user.
47
In this example, when we click on submit button after checking the value, the
cookies add selected value.
index.html
<!doctype html>
<head>
<title>CookiesExample</title>
</head>
<body>
<form method='post' action='servlet/cookies'>
<fieldset style="width:14%; background-color:#ccffcc">
<h2>Select Course</h2> <hr>
<input type='radio' name='course' value='Java'>Java<br>
<input type='radio' name='course' value='UNIX'>UNIX<br>
<input type='radio' name='course' value='MCA'>DBMS<br>
<input type='radio' name='course' value='OOSE '>OOSE<br><br>
<input type='submit'> <input type='reset'><br>
</fieldset>
</form>
</body>
</html>
AddCookie.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookie extends HttpServlet
48
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Cookie []c = req.getCookies();
int id=1;
if(c!=null) id = c.length+1;
String value = req.getParameter("course");
Cookie newCookie = new Cookie("course:"+id,value);
res.addCookie(newCookie);
pw.println("<h4>Cookie added with value "+value+"</h4>");
}
web.xml
<web-app>
<servlet>
<servlet-name>AddCookie</servlet-name>
<servlet-class>AddCookie</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddCookie</servlet-name>
<url-pattern>/servlet/cookies</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Output:
Select Java and click on submit. It adds the cookies with value Java.
49
50
Today's world is 'online world' where people are highly dependent on the internet
and web applications. Millions of web applications and thousands of technologies
are available in the market for enterprise application development. All of these web
technologies are categorized as Model1, Model2, MVC and much more. Struts is
MVC Model2 architecture-based framework.
MVC means Model-View-Controller where model is responsible for business
logic, view handles the user interaction with application and controller decides the
flow of application.
Figure 1.1 explains the working methodology behind MVC architecture which is
as follows:
1) User sends the request using view which reaches to the controller on the server.
2) Controller decides the respective model and delivers the control to particular
model.
3) As a result of business processing, model changes its state.
4) Depending on the state change of model, control redirects the flow to the view.
Model: Model is responsible to carry data and it is the low level of the pattern.
View: View is responsible to expose the carried data to an user.
Controller: Controller will provide interaction between the model and view.
Controller will have the code, requests and responses will be handled from here.
52
o mail.jar
o activation.jar
{download these jar files or go to the Oracle site to download the latest version.}
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
message.setSubject("Ping");
message.setText("Hello, this is example of sending email ");
// Send message
Transport.send(message);
System.out.println("message sent successfully....");
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp1000">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="firstName"></property>
<property name="lastName"></property>
</class>
58
</hibernate-mapping>
3. The configuration file contains information about the database and mapping file.
Conventionally, its name should be hibernate.cfg.xml .
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property
name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property
name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>