Please comment if you have any question. I will try to answer when i have free time. Thanks!

Create a user details page

Create a user details page. The page should have First Name, Last Name, and Email address fields. On clicking the submit button, a new Web page should display the details entered by the user.
Hint: Use getAttribute to display the user details.

Solution:

The files used in this exercise are:

1. index.jsp
2. displayname.jsp
3. NameForm.java
4. NameAction.java

<%@ page language="java" %>
<%@ page language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<html>
<head>
<title>Sample Struts Application</title>
</head>
<body>
<h3> User Details</h3>
<html:form action="Name" name="nameForm" type="example.NameForm" >
<table width="80%" border="0">

<tr>
<td><b>First Name:</b>
<html:text property="name" />
</td>
</tr>

<tr>
<td><b>Last Name:</b>
<html:text property="last" />
</td>
</tr>

<tr>
<td>
<b>Email: </b>
<html:text property="email" />
</td>
</tr>

<tr>
<td><html:submit />
</td>
</tr>
</table>

</html:form>
</body>
</html>
Enter the code in Notepad and save the file as index.jsp in %TOMCAT_HOME%/webapps/ details.
<html>
<head>
<title>Sample Struts Display Name</title>
</head>
<body>
<h2> Confirm the Details You Entered</h2>
<table width="80%" border="0">

<tr>
<td>
<b>First Name:</b><%= request.getAttribute("NAME") %>
</td>
</tr>

<tr>
<td>
<b>Last Name:</b><%= request.getAttribute("LAST") %>
</td>
</tr>

<tr>
<td>
<b>Email:</b><%= request.getAttribute("EMAIL") %></td>
</tr>

</table>
</body>
</html>
Enter the code in Notepad and save the file as displayname.jsp in %TOMCAT_HOME%/ webapps/details.

package example;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

public class NameForm extends ActionForm
{
private String name = null;
private String last = null;
private String email = null;

public String getName()
{
return (name);
}
public String getLast()
{
return (last);
}
public String getEmail()
{
return (email);
}
public void setName(String name)
{
this.name = name;
}
public void setLast(String last)
{
this.last = last;
}
public void setEmail(String email)
{
this.email = email;
}
public void reset(ActionMapping mapping, HttpServletRequest request)
{
this.name = null;
this.last= null;
this.email=null;
}
}

Enter the Java code in Notepad and save the file as NameForm.java. Compile the file from the command prompt and copy the class file in %TOMCAT_HOME%/webapps/details/WEB-INF/classes/example.
package example;
import java.io.IOException;
import javax.servlet.ServletException;
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;

public class NameAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
String target = new String("success");
String name=null;
String last=null;
String email=null;

if ( form != null )
{
NameForm nameForm = (NameForm)form;
NameForm lastForm = (NameForm)form;
NameForm emailForm = (NameForm)form;

name = nameForm.getName();
last = lastForm.getLast();
email = emailForm.getEmail();
}

if ( name == null )
{
target = new String("failure");
}
else
{
request.setAttribute("NAME", name);
request.setAttribute("LAST", last);
request.setAttribute("EMAIL", email);
}
return (mapping.findForward(target));
}
}
Enter the Java code in Notepad and save the file as NameAction.java. Compile the file from the command prompt and copy the class file in %TOMCAT_HOME%/webapps/details/WEB-INF/classes/example.
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>

<!-- Form Bean Definitions -->

<form-beans>

<form-bean name="nameForm" type="example.NameForm"/>

</form-beans>

<!-- Action Mapping Definitions -->

<action-mappings>

<action path="/Name" type="example.NameAction" name="nameForm" input="/index.jsp">

<forward name="success" path="/displayname.jsp"/>

<forward name="failure" path="/index.jsp"/>

</action>

</action-mappings>
</struts-config>
Update the struts-config.xml file used in the Web application.

The output of the program is as shown in Figure 17.1.


Figure 17.1: Accepting User Details

The output of the program that displays user details is as shown in Figure 17.2.

Figure 17.2: Details Page

Read More ...

Create a Login form using struts

Create a Login form using struts. Create two text fields in the Web page, and name the fields as User and Password. The page includes a Submit button. After the user clicks the Submit button, a page should appear indicating that the user is a valid user.

The files used in this exercise are:

1. cust.jsp
2. valid.jsp
3. CustForm.java
4. CustAction.java

<%@ taglib uri = "/WEB-INF/struts-html.tld" prefix="html" %>
<html>
<head> <title>Testing struts</title> </head>
<body>
<html:form action = "cust.do" > <center>
<b>User:</b> <html:text property = "first" /> <br><br><br>
<b>Password:</b><html:password property = "pwd" /><br><br><br>
<html:submit /> </center>
</html:form>
</body>
</html>

Enter the code in Notepad and save the file as cust.jsp in %TOMCAT_HOME%/webapps/ struts-test.

<html>
<head><title>Valid User</title>
</head>
<body>
<center><h2><b>VALID USER</b></h2></center>
</body>
</html>

Valid Use
Enter the code in Notepad and save the file as valid.jsp in %TOMCAT_HOME%/webapps/ struts-test.

package common.test;
import javax.servlet.http.*;
import org.apache.struts.action.*;

public class CustForm extends ActionForm
{
private String mFirst = null;
private String mPwd = null;

public String getFirst() { return mFirst; }
public void setFirst(String aFirst) { mFirst = aFirst; }

public String getPwd() { return mPwd; }
public void setPwd(String aPwd) { mPwd = aPwd; }
public void reset(ActionMapping aMapping, HttpServletRequest aRequest)
{
mFirst = null;
mPwd = null;
}
}

Enter the Java code in Notepad and save the file as CustForm.java. Compile the file from the command prompt and copy the class file in %TOMCAT_HOME%/webapps/struts-test/WEB-INF/classes/common/test.

package common.test;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;

public class CustAction extends Action
{

public ActionForward perform(ActionMapping aMapping, ActionForm aForm,HttpServletRequest aRequest, HttpServletResponse aResponse)throws ServletException
{
CustForm f = (CustForm) aForm;
String first = f.getFirst();
String last = f.getPwd();
return aMapping.findForward("saved");
}
}
Enter the Java code in Notepad and save the file as CustAction.java. Compile the file from the command prompt and copy the class file in %TOMCAT_HOME%/webapps/struts-test/WEB-INF/classes/common/test.

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.0//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd">

<struts-config>

<!-- Form Bean Definitions -->

<form-beans>
<form-bean name = "custForm" type = "common.test.CustForm"/>
</form-beans>

<!-- Global Forward Definitions -->

<global-forwards>
<forward name = "start" path = "/index.jsp"/>
</global-forwards>

<!-- Action Mapping Definitions -->

<action-mappings>
<action path = "/cust" type = "common.test.CustAction" name = "custForm">
<forward name = "saved" path = "/valid.jsp"/>
</action>
</action-mappings>

</struts-config>

Update the struts-config.xml file used in the Web application

The output of the program is as shown in Figure 16.3.


Figure 16.3: Login page

After the user clicks the Submit button, the output of the program is as shown in Figure 16.2.

Figure 16.4: Valid user page

Read More ...

Create a struts-blank.war blank application

1. Create a struts-blank.war blank application. Use the blank application to create a Web page that displays the title and author of a book. The page includes a Submit button. After the user clicks the Submit button, a page should appear indicating that the request is being processed. The example requires two JSP pages and two JavaBeans. Update struts-config.xml file to associate the Web pages with the JavaBeans.

Solution:

The files used in this exercise are:

1. test.jsp
2. searching.jsp
3. BookForm.java
4. BookAction.java

<%@ taglib uri = "/WEB-INF/struts-html.tld" prefix="html" %>
<html>
<head> <title>Struts</title>
</head>
<body>
<html:form action="book.do" ><center>
<b>TITLE:<b> <html:text property ="title" /><p>
<b>AUTHOR:<b> <html:text property ="author" /><br> <p>
<html:submit /></center>
</html:form>
</body>
</html>

Enter the code in Notepad and save the file as test.jsp in %TOMCAT_HOME%/webapps/ struts-test.

<html>
<head><title>Searching</title>
</head>
<body>
<h3><b>Searching.....<b></h3>
</body>
</html>

Enter the code in Notepad and save the file as searching.jsp in %TOMCAT_HOME%/webapps/ struts-test.
package com;
import javax.servlet.http.*;
import org.apache.struts.action.*;

public class BookForm extends ActionForm
{
private String nTitle = null;
private String nAuthor = null;

public String getTitle() { return nTitle; }
public void setTitle(String aTitle) { nTitle = aTitle; }

public String getAuthor() { return nAuthor; }
public void setAuthor(String aAuthor) { nAuthor = aAuthor; }
public void reset(ActionMapping aMapping, HttpServletRequest aRequest)
{
nTitle = null;
nAuthor = null;
}
}

Enter the Java code in Notepad and save the file as BookForm.java. Compile the file from the command prompt and copy the class file in %TOMCAT_HOME%/webapps/struts-test/WEB-INF/classes/com.
package com;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;

public class BookAction extends Action
{
public ActionForward perform(ActionMapping aMapping, ActionForm aForm,HttpServletRequest aRequest, HttpServletResponse aResponse)throws ServletException
{
BookForm f = (BookForm) aForm;
String title = f.getTitle();
String author = f.getAuthor();
return aMapping.findForward("saved");
}
}

Enter the Java code in Notepad and save the file as BookForm.java. Compile the file from the command prompt and copy the class file in %TOMCAT_HOME%/webapps/struts-test/WEB-INF/classes/com.


Enter the Java code in Notepad and save the file as BookAction.java. Compile the file from the command prompt and copy the class file in %TOMCAT_HOME%/webapps/struts-test/WEB-INF/classes/com.

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.0//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd">

<struts-config>

<!-- Form Bean Definitions -->

<form-beans>
<form-bean name = "bookForm" type = "com.bookForm"/>
</form-beans>

<!-- Global Forward Definitions -->

<global-forwards>
<forward name = "start" path = "/index.jsp"/>
</global-forwards>

<!-- Action Mapping Definitions -->

<action-mappings>
<action path = "/book" type = "com.bookAction" name = "bookForm">
<forward name = "saved" path = "/greeting.jsp"/>
</action>
</action-mappings>

</struts-config>

Update the struts-config.xml file used in the Web application.

The output of the program is as shown in Figure 16.1.


Figure 16.1: Input page
After the user clicks the Submit button, the output of the program is as shown in Figure 16.2.

Read More ...

User Login in JSP

Every website and software in the world is having login facility. Login gives access rights to user and defines their role in website and application. Nobody can access website if they failure in proving their identity on website or application.
Registration is first step by login to website. We will keep focus on only user login in JSP.

User login contain two fields, first one important User ID. This is unique ID provided by site owner or software application itself or most of provide facility to choose user id themselves on their website of web application.

Second is password, it is secret field and user have to keep remember without sharing with anybody. This field gives authentication to user to login on the website. User ID and password keep isolate one user to other users.

We have three forms of JSP pages.

login.jsp take input from user, mainly user id and password then submitted to server for further processing. This process handles with database. Database has a SQL table name usermaster. Usermaster table is having number of fields which are not using in login process. We need user id, password, user type, user level, first name, last name.

User type field in database explain user type as e.g. admin role, power user role, moderator role, end user role. User levels field explain about permission defined to user. Read, write, update, view are permission on user can work accordingly to these permission. This certainly is not using in current login facility. This can be useful after user login successfully and work in application.


SQL usermaster Table

CREATE TABLE `usermaster` (
`sUserID` varchar(45) NOT NULL,
`sEmail` varchar(250) NOT NULL,
`sFirstName` varchar(45) NOT NULL,
`sLastName` varchar(45) NOT NULL,
`iDOB` datetime NOT NULL,
`cGender` varchar(45) NOT NULL,
`iCountryID` int(10) unsigned NOT NULL,
`iCityID` varchar(45) NOT NULL,
`iUserType` varchar(45) DEFAULT NULL,
`iUserLevel` varchar(45) DEFAULT NULL,
`sPassword` varchar(45) NOT NULL,
`sForgetPassword` varchar(45) DEFAULT NULL,
`sContact` bigint(20) unsigned NOT NULL,
`sCreatedBy` varchar(45) DEFAULT NULL,
`dCreatedDate` datetime DEFAULT NULL,
`sModifiedBy` varchar(45) DEFAULT NULL,
`sModifiedDate` datetime DEFAULT NULL,
`sStatus` varchar(45) NOT NULL,
PRIMARY KEY (`sUserID`),
UNIQUE KEY `sEmail` (`sEmail`)
);

login.jsp
<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<%
String error=request.getParameter("error");
if(error==null || error=="null"){
error="";
}
%>
<html>
<head>
<title>User Login JSP</title>
<script>
function trim(s)
{
return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
}

function validate()
{
if(trim(document.frmLogin.sUserName.value)=="")
{
alert("Login empty");
document.frmLogin.sUserName.focus();
return false;
}
else if(trim(document.frmLogin.sPwd.value)=="")
{
alert("password empty");
document.frmLogin.sPwd.focus();
return false;
}
}
</script>
</head>

<body>
<div><%=error%></div>
<form name="frmLogin" onSubmit="return validate();" action="doLogin.jsp" method="post">
User Name <input type="text" name="sUserName" /><br />
Password <input type="password" name="sPwd" /><br />
<input type="submit" name="sSubmit" value="Submit" />
</form>
</body>
</html>
doLogin.jsp mainly deals with database to check user id and password is matched with user trying to provide to get access from the server.

Our password field is encrypted with mysql password function. To decrypt password we have to use mysql password function again. If you are using Oracle or other database password function come with different name. Only user knows exact password and anybody can find out real password of the user. This increases the security of the system and reduces the hacking.

doLogin.jsp

<%@ page language="java" import="java.sql.*" errorPage="" %>
<%

Connection conn = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root", "");

ResultSet rsdoLogin = null;
PreparedStatement psdoLogin=null;

String sUserID=request.getParameter("sUserName");
String sPassword=request.getParameter("sPwd");
String message="User login successfully ";

try{
String sqlOption="SELECT * FROM usermaster where"
+" sUserID=? and sPassword=password(?) and sStatus=’A'";

psdoLogin=conn.prepareStatement(sqlOption);
psdoLogin.setString(1,sUserID);
psdoLogin.setString(2,sPassword);

rsdoLogin=psdoLogin.executeQuery();

if(rsdoLogin.next())
{
String sUserName=rsdoLogin.getString("sFirstName")+" "+rsdoLogin.getString("sLastName");

session.setAttribute("sUserID",rsdoLogin.getString("sUserID"));
session.setAttribute("iUserType",rsdoLogin.getString("iUserType"));
session.setAttribute("iUserLevel",rsdoLogin.getString("iUserLevel"));
session.setAttribute("sUserName",sUserName);

response.sendRedirect("success.jsp?error="+message);
}
else
{
message="No user or password matched" ;
response.sendRedirect("login.jsp?error="+message);
}
}
catch(Exception e)
{
e.printStackTrace();
}


/// close object and connection
try{
if(psdoLogin!=null){
psdoLogin.close();
}
if(rsdoLogin!=null){
rsdoLogin.close();
}

if(conn!=null){
conn.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}

%>

doLogin.jsp match user id and password with database record. If record is matched with user field and password. It will set user id, user type, user level, first name, last name in session. This can access from session in further in application. It will finish processing and return to success.jsp page.

success.jsp

<%@ page contentType="text/html; charset=iso-8859-1" language="java"%>

<html>
<head>
<title>Successfully Login by JSP</title>
</head>

<body>
Successfully login by JSP<br />
Session Value<br />
<%
out.print("UserName :"+session.getAttribute("sUserID")+"<br>");
out.print("First & Last Name :"+session.getAttribute("sUserName"));
%>
</body>
</html>
If user id and password is not matched, it will return back to login.jsp page and print error message to user, user id and password is not matched.

The example of login is given with source code, login.jsp, doLogin.jsp and success.jsp.

Read More ...

JSP CheckBox

<html>
<h2>Select Languages:</h2>

<form ACTION="jspCheckBox.jsp">
<input type="checkbox" name="id" value="Java"> Java<BR>
<input type="checkbox" name="id" value=".NET"> .NET<BR>
<input type="checkbox" name="id" value="PHP"> PHP<BR>
<input type="checkbox" name="id" value="C/C++"> C/C++<BR>
<input type="checkbox" name="id" value="PERL"> PERL <BR>
<input type="submit" value="Submit">
</form>
<%

String select[] = request.getParameterValues("id");
if (select != null && select.length != 0) {
out.println("You have selected: ");
for (int i = 0; i < select.length; i++) {
out.println(select[i]);
}
}
%>
</html>
Output will be displayed as:


After selecting the languages, when you submit the button, the message will be displayed with selected languages:

Read More ...

JSP Sessions Example

Sessions are started automatically in JSP pages.
You can access current session by prebuilt session object.

Create sessions.jsp file on your Tomcat's webapps/ROOT directory :


<%@page import="java.util.Date"%>
<%
out.print("Session Creation Time:" + new Date(session.getCreationTime()));
out.print("<BR>");
out.print("Last accessed Time:" + new Date(session.getLastAccessedTime()));
out.print("<BR>");
out.print("Session ID:"+session.getId());
%>
and launch it (for example http://localhost:8080/sessions.jsp)

it prints:

Session Creation Time:Sat Jun 14 19:28:06 EEST 2008
Last accessed Time:Sat Jun 14 19:33:34 EEST 2008
Session ID:365A3F239D1E54FD43EA0F7CBA1931EF

Now we are able to access the session. We can store objects in session objects.
This can help share objects between JSP pages.

Sessions are widely used for authentication purposes.

For example , let this be index.jsp as default page :
<%
String userName = request.getParameter("userName");
String password = request.getParameter("password");
if ("admin".equals(userName) && "adminpass".equals(password) ) { //Session start
session.setAttribute("userName",userName);
session.setAttribute("role","admin");
response.sendRedirect("/main.jsp");
}
else out.print("Logon failed");
%>
<form action="index.jsp" method="post">
Enter Username: <input name="userName"> <br>
Enter Password: <input name="password"> <br>
<input type="submit">
</form>
The sample code above get username and password from user. If username and password are ok , username and role objects are stored in session and redirects to main.jsp otherwise sends an http error.

And in main.jsp we authenticate user based on username and role :
<%
String userName = session.getAttribute("userName");
String role = session.getAttribute("role");
if ( userName == null || ! "admin".equals(role) ) {
response.sendError(403,"You are not authorized to view this page");
return;
}
%>

This authentication part can be a seperate jsp and included in every page that needs authentication. Ideally , username , password and role lookup should be from database or from a directory service like LDAP or Active Directory.

Read More ...

Simple JSP Tutorial

This jsp accepts a number from an html form and prints squareroot of that number on the same page. Paste this code to file "first.jsp" and move it to tomcat's webapps/ROOT directory. Start tomcat and browse to localhost:8080/first.jsp. We put java code in <% %> block , other parts are standart html. <%=variable %> prints variable into html code just like <%out.print(variable);%> does.

request , response and out objects are standart JSP objects that can be used to access http request and response.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sample JSP</title>
</head>
<body>
<%
String strNumber= request.getParameter("number");
double mySqrt = 0.0;
if ( strNumber == null )
strNumber = "";
else {
double dNumber = Double.parseDouble(strNumber);
mySqrt = Math.sqrt(dNumber);
}
%>
<form action="first.jsp" method="post">
Enter Number: <input type="text" name="number" value="<%=strNumber%>">
<input type="submit">
<br><br>
The Sqrt is <%out.print(mySqrt);%>
</body>
</html>

Read More ...