You are on page 1of 58

1

Advanced Java
Practical File

Submitted To: Siddharth Singh


Submitted By: Shahid Khan
Course: B. Tech CSE -VI
College Roll No: 181064
2

INDEX
S.NO Topics/Programs
1. Write Servlet application to print current date & time

2. Html & Servlet Communication

3. Auto refresh a page

4. Demonstrate session tracking

5. Select record from database

6. Application for login page

7. Insert record into database

8. Count the visits on web page

9. Insert teacher record in Database

10. Check voter's eligibility

11. Apache Struts Hello World example

12. Adding cookie to selected value.

13. Write Down about MVC for Struts 2.

14. Write down a Program for Mail API.

15. Create Mapping Configuration File using Hibernate.


3

PRACTICAL:-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.*;

public class DateSrv extends GenericServlet


{
//implement service()
public void service(ServletRequest req, ServletResponse res) throws
IOException, ServletException
{
//set response content type
res.setContentType("text/html");
//get stream obj
PrintWriter pw = res.getWriter();
//write req processing logic
java.util.Date date = new java.util.Date();
pw.println("<h2>"+"Current Date & Time: " +date.toString()+"</h2>");
//close stream object
pw.close();
}
}

Output:
4

PRACTICAL:-2. Html & Servlet Communication

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.

HTML to Servlet Communication using Hyperlink


Example: In the browser, the HTML page should contain the link to the servlet
component to get the wish message based on the current hour of the day.
If the current hour of the day is between 5 AM to 12 PM then we should get “good
morning” as result, for 12 PM to 5 PM “good afternoon”, for 5 PM to 8 PM “good
evening”, and for the remaining time the servlet component should give result as
5

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

Communication Using Forms


Example1 : Take an HTML form to gather the input from the end-user. End-user
should pass name and age to check whether he/she is eligible for voting or not. In
the servlet, components develop logic to check the age and display an appropriate
message to the end-user. Assume 18 is the minimum age for voting.
6

Simple HTML Form Example


Example 2: Develop an HTML page that should take the name, age, gender,
address, marital status, qualification, and hobbies. Read those form data in the
servlet component and display them on the browser.

HTML to Servlet Communication Using JavaScript


Example: In the HTML form page one select box will be there containing a
different programming language name. Based on the selected language the creator
of that language should display it on the browser.

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

PRACTICAL:-3. Auto refresh a page

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

PRACTICAL:-4. Demonstrate session tracking

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.*;

// Extend HttpServlet class


public class SessionTrack extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Create a session object if it is already not created.


HttpSession session = request.getSession(true);

// Get session creation time.


Date createTime = new Date(session.getCreationTime());

// Get last access time of this web page.


Date lastAccessTime = new Date(session.getLastAccessedTime());
11

String title = "Welcome Back to my website";


Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");

// Check if this is new comer on your web page.


if (session.isNew()) {
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
} else {
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);

// Set response content type


response.setContentType("text/html");
PrintWriter out = response.getWriter();

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

"<body bgcolor = \"#f0f0f0\">\n" +


"<h1 align = \"center\">" + title + "</h1>\n" +
"<h2 align = \"center\">Session Infomation</h2>\n" +
"<table border = \"1\" align = \"center\">\n" +

"<tr bgcolor = \"#949494\">\n" +


" <th>Session info</th><th>value</th>
</tr>\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

" <td>" + lastAccessTime + " </td>


</tr>\n" +

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

PRACTICAL:-5. Select record from database

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

Use the following example in JDBCExample.java, compile and run as follows −


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCExample {


static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Registration";

public static void main(String[] args) {


// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER,
PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(QUERY);
){
while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
18

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

PRACTICAL:-6. Application for login page

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:

create table userreg(name varchar2(40),pass varchar2(40));

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;

public class FirstServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

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;

public class WelcomeServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("username");
out.print("Welcome "+n);

out.close();
}

}
23

PRACTICAL:-7. Insert record into database

An example on how to insert records in a table using JDBC application.


Before executing 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 user name and password.

• Your MySQL or whatever database you are using is up and running.

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.

• 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 insert records into a table.
24

• Clean up the environment try with resources automatically closes the


resources.

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;

public class JDBCExample {


static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";

public static void main(String[] args) {


// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER,
PASS);
Statement stmt = conn.createStatement();
){
// Execute a query
System.out.println("Inserting records into the table...");
String sql = "INSERT INTO Registration VALUES (100, 'Zara', 'Ali', 18)";
stmt.executeUpdate(sql);
25

sql = "INSERT INTO Registration VALUES (101, 'Mahnaz', 'Fatma', 25)";


stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES (102, 'Zaid', 'Khan', 30)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES(103, 'Sumit', 'Mittal', 28)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} 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
Inserting records into the table...
Inserted records into the table...
C:\>
26

PRACTICAL:-8. Count the visits on web page

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;

public class CounterServlet extends HttpServlet


{
//Instance variable used for counting hits on this servlet
private int iHitCounter;

//init method just initializes the hitCounter to zero


public void init() throws ServletException
{
iHitCounter = 0;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("<form><fieldset style='width:15%'>");
out.println("<h3>Welcome to my website !</h3><hr>");
out.println("You are visitor number: "+ (++iHitCounter));
out.println("</fieldset></form>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
27

throws ServletException, IOException


{
doGet(request, response);
}
}

Output:
28

PRACTICAL:-9. Insert teacher record in Database

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.

Create a table in a database to store the record.

Create table teacherdetails (tid number, name varchar2(20), address varchar2(40);

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.*;

public class Register extends HttpServlet


{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int id = Integer.parseInt(request.getParameter("TId"));
String name = request.getParameter("name");
String address = request.getParameter("address");
try
{
//load the driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//create connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","local","test");
// create the prepared statement object
PreparedStatement ps=con.prepareStatement("insert into TeacherDetails
values(?,?,?)");

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

PRACTICAL:-10. Check voter's eligibility

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

PRACTICAL:-11. Apache Struts Hello World example

First create a new project, go to File->New and select DynamicWebProject.

Enter the project name and click the Finish button.


37

Add the following jar files to the WEB-INF\lib directory.


38

Right click the src folder and select New->Package.

Enter the package name as com.vaannila.form and click Finish.


Now right click the newly created package and select New->Class.
39

Enter the class name as HelloWorldForm and the superclass name


as org.apache.struts.action.ActionForm and click Finish.
40

In the HelloWorldForm class add the following code.


package com.vaannila.form;
import org.apache.struts.action.ActionForm;
public class HelloWorldForm extends ActionForm {
private static final long serialVersionUID = -473562596852452021L;
private String message;
41

public String getMessage() {


return message;
}
public void setMessage(String message) {
this.message = message;
}
}
In the same way create a new package com.vaannila.action and create
a HelloWorldAction class extending org.apache.struts.action.Action. Add the
following code to the action class and save it.

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;

public class HelloWorldAction extends Action {

@Override
42

public ActionForward execute(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response) throws Exception {
HelloWorldForm hwForm = (HelloWorldForm) form;
hwForm.setMessage("Hello World");
return mapping.findForward("success");
}
}

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

<!DOCTYPE struts-config PUBLIC


"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">

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

Now configure the deployment descriptor. Add the following configuration


information 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"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID"
version="2.5">
<display-name>StrutsExample1</display-name>

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

<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>


<logic:redirect forward="helloWorld"/>
In the action class we return the ActionForward "success" which is mapped to
the helloWorld.jsp page. In the helloWorld.jsp page we display the "Hello World"
message.
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<html>
<head>
45

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">


<title>Hello World</title>
</head>
<body>
<bean:write name="helloWorldForm" property="message"/>
</body>
</html>

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

PRACTICAL:-12. Adding cookie to selected value.

Information which is stored on the client machine is called cookies. It has


parameters like name, value, path, host, expires and connection type.

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

PRACTICAL:-13. Write Down about MVC for Struts


2.

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.

Main advantage of this architecture is the separation of data layer, presentation


layer and pure business logic.
51

Struts 2 MVC Architecture, Struts2 framework is defined in most of the MVC


(Model View Controller) based applications, before that user should have an idea
about what MVC is. Model View Controller is the popular design pattern which is
utilized to build web applications and it consists of three parts where each one will
have its own functionality, where controller is the responsibility for carrying the
little code through which request will be sent to the server, when the server takes
the request model is the responsibility to check the data availability and view is
utilized to expose the data to an user. Following is the conceptual figure which
describes functioning of each module.

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

PRACTICAL:-14. Write down a Program for Mail


API.

➢ Steps to send email using JavaMail API


There are following three steps to send email using JavaMail. They are as follows:
➢ Get the session object that stores all the information of host like host name,
username, password etc.
➢ compose the message
➢ send the message

1) Get the session object


The javax.mail.Session class provides two methods to get the object of session,
Session.getDefaultInstance() method and Session.getInstance() method. You can
use any method to get the session object.
Example of getDefaultInstance() method
Properties properties=new Properties();
//fill all the information like host name etc.
Session session=Session.getDefaultInstance(properties,null);
Example of getInstance() method
Properties properties=new Properties();
//fill all the information like host name etc.
Session session=Session.getInstance(properties,null);
2) Compose the message
53

The javax.mail.Message class provides methods to compose the message. But it is


an abstract class so its subclass javax.mail.internet.MimeMessage class is mostly
used.
To create the message, you need to pass session object in MimeMessage class
constructor. For example:
MimeMessage message=new MimeMessage(session);
Now message object has been created but to store information in this object
MimeMessage class provides many methods.
Example to compose the message:
MimeMessage message=new MimeMessage(session);
message.setFrom(new InternetAddress("sonoojaiswal@sssit.org"));
message.addRecipient(Message.RecipientType.To,
new InternetAddress("sonoojaiswal@javatpoint.com"));
message.setHeader("Hi, everyone");
message.setText("Hi, This mail is to inform you...");

3) Send the message


The javax.mail.Transport class provides method to send the message.
Example to send the message:
Transport.send(message);

Simple example of sending email in Java


In this example, we are going to learn how to send email by SMTP server installed
on the machine e.g. Postcast server, Apache James server, Cmail server etc. If you
want to send email by using your SMTP server provided by the host provider, see
the example after this one.
For sending the email using JavaMail API, you need to load the two jar files:
54

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.*;

public class SendEmail


{
public static void main(String [] args){
String to = "sonoojaiswal1988@gmail.com";//change accordingly
String from = "sonoojaiswal1987@gmail.com";change accordingly
String host = "localhost";//or IP address

//Get the session object


Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);

//compose the message


try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
55

message.setSubject("Ping");
message.setText("Hello, this is example of sending email ");

// Send message
Transport.send(message);
System.out.println("message sent successfully....");

}catch (MessagingException mex) {mex.printStackTrace();}


}
}
56

PRACTICAL:-15. Create Mapping Configuration File


using Hibernate.

1. Let's create the simple Persistent class:


Employee.java
package com.javatpoint.mypackage;

public class Employee {


private int id;
private String firstName,lastName;

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
57

public String getLastName() {


return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
2. Let's see the mapping file for the Employee class:
employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">

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

You might also like