Login Form

Login form in struts: Whenever you goes to access data from database, as a register user you are always asked for the login to accessing data.

Login Form

Login Form

     

Login form in struts: Whenever you goes to access data from database, as a register user you are always asked for the login to accessing data. E-mail's login are very  good example of this. In this section of struts tutorial we will explain how to do coding for a login form using struts.

UserLoginAction Class: When you download Login and User Registration Application from http://www.roseindia.net/struts/hibernate-spring/project.zip, you will get a jar file .After extracting this jar file you will get  UserLoginAction.java file in action directory. We use this  UserLoginAction.java to process  request and Login user. 

package roseindia.web.struts.action;

/**
* @Author roseindia team
* @Web http://www.roseindia.net
* @Copyright RoseIndia.net  
*/
/**
 * Action class for the Login User.
 *
*/

import roseindia.web.struts.form.UserLoginForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


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 org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import roseindia.services.ServiceFinder;

public class UserLoginAction extends Action{

public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest   request,HttpServletResponse response) throws Exception{


   //Retrieve the DAO Reference
   roseindia.dao.SpringHibernateDAO springHibernateDAO =  (roseindia.dao.SpringHibernateDAO) ServiceFinder.getContext(request)
.getBean("SpringHibernateDao");


// Create object of ActionMesssages
ActionMessages errors = new ActionMessages();

UserLoginForm objForm = (UserLoginForm) form;

String strUserid=objForm.getUserid();

String strPassword=objForm.getPassword();
boolean loginStatus = springHibernateDAO.checkUserLogin(strUserid,strPassword);
if(loginStatus==true){

HttpSession session = request.getSession();
session.setAttribute("userID", strUserid); 

//int id =springHibernateDAO.getUserId(strUserid);

String id=String.valueOf(springHibernateDAO.getUserId(strUserid));

//Integer idvalue=new Integer(id);

session.setAttribute("ID", id); 

System.out.println("Session value:"+session.getAttribute("userID"));

return mapping.findForward("success");
} else {
// not allowed

errors.add("login",new ActionMessage("error.login.invalid"));
saveErrors(request,errors);

return mapping.findForward("failure");
}
}
}

Here we explain the above code step by step--

 In order to create an action we must extends Action class. After that we use execute( ) method of Action class. This method  Processes the specified HTTP request and create the corresponding HTTP response or forward to another web component. 
The next lines of code is use to retrieve  the DAO Reference.

roseindia.dao.SpringHibernateDAO springHibernateDAO = (roseindia.dao.SpringHibernateDAO) ServiceFinder.getContext(request)
.getBean("SpringHibernateDao");

Now we create ActionMessages object to save errors and call them in jsp page.

// Create object of ActionMesssages
ActionMessages errors = new ActionMessages();

Now we create a action form object to access the value enter by user.
UserLoginForm objForm = (UserLoginForm) form;

Now we use a method checkUserLogin(strUserid,strPassword) .This will return the status of valid user. If user name and password is valid status will be true otherwise false. This method body is in SpringHibernateDAO class.

boolean loginStatus = springHibernateDAO.checkUserLogin(strUserid,strPassword);


// this code is from roseindia.dao.SpringHibernateDAOImpl.java
public boolean checkUserLogin(String strUserName, String strPassword) throws DataAccessException,java.sql.SQLException{
boolean valid = false;
Connection conn = this.getSession().connection();
//Write jdbc code to validate the user against database
Statement smt = conn.createStatement();
ResultSet rs;
//select query for checking password 
String query="select id from login where loginid='"+strUserName+"' and password='"+strPassword+"'";
rs=smt.executeQuery(query);

if(rs.next()== true){
valid=true;

}else{
valid=false;
}

smt.close();
rs.close();
conn.close();

return valid;


}

If the loginStatus  is true then we set the value of username and id in session and mapping.findForward("success") return success jsp page. Otherwise add  this error in ActionMessages object.  

errors.add("login",new ActionMessage("error.login.invalid"));
saveErrors(request,errors);
and mapping.findForward("failure") return failure. Now jsp page return with errors.

ActionForm:An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm.in this application ActionForm is UserLoginForm.java.ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side. It must have setters and getters for all the form fields.It must have setters and getters for all the form fields.

package roseindia.web.struts.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.*;

public class UserLoginForm extends ActionForm{

private String action="add";

private String userid = null;
private String password = null;

public void reset(ActionMapping mapping,HttpServletRequest request){


this.userid=null;
this.password=null;

this.action="add";

}


public ActionErrors validate( 

ActionMapping mapping, HttpServletRequest request ) {
ActionErrors errors = new ActionErrors();
/* 
if( getUserid() == null || getUserid().length() < 1 ) {
errors.add("username",new ActionMessage("error.username.required"));
}
if( getPassword() == null || getPassword().length() < 1 ) {
errors.add("password",new ActionMessage("error.password.required"));
}

*/
return errors;
}

public String getAction() {
return action;
}

public void setAction(String action) {
this.action = action;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getUserid() {
return userid;
}

public void setUserid(String userid) {
this.userid = userid;
}


Action mapping in struts-config.xml: Action mapping  associates a Struts action with a forward which is responsible for request processing. The following is  mapping for Action Form . 
 
 
<form-bean name="UserLoginForm" 
  type="roseindia.web.struts.form.UserLoginForm">
   </form-bean>

This is mapping for action class-

  <action
   path="/userlogin"
   name="UserLoginForm"
   scope="request"
   validate="true"
   input="/pages/user/userlogin.jsp"
   type="roseindia.web.struts.action.UserLoginAction">
  <forward name="success" path="/pages/user/loginsuccess.jsp"/>
  <forward name="failure" path="/pages/user/userlogin.jsp"/>
   </action>

View Part(jsp file): The View portion of this application is constructed using JavaServer Pages (JSP) technology.This JSP shows Login form user interface.

This line of code is responsible for errors generated by Action Class or Action Form.
Action Form returns  ActionErrors and Action Class returns errors saved in the form of ActionMessage.

<html:errors/>

<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html locale="true">
<head>
<title><bean:message key="welcome.title"/></title>
<LINK rel="stylesheet" type="text/css" name="anyname" href="<html:rewrite page='/css/style.css'/>">
</head>
<html:base/>
<body>

<%@ include file="../top.jsp"%> 
<center>

<table width="40%">

<tr>
<!--
<td colspan="5">

<table width="400" border="1" cellpadding="0" cellspacing="0" align="center" >
<tr>

--> <td>
<html:form action="/userlogin" method="post">
<table border="1" cellspacing="2" cellpadding="1" width="100%" class="signup">
<tr>
<td align="center" colspan="2" ><font size="5">User Login</font><br><font color="red"><html:errors/></td>
</tr> 

<tr align="center">
<td align="right" width="50%"><b>User ID:</b></td> 
<td width="50%"><html:text property="userid" size="30" maxlength="30"/></td>
</tr> 
<tr align="center">
<td align="right"><b>Password:</b></td> 
<td><html:password property="password" size="30" maxlength="30"/></td>
</tr> 

<tr>
<td align="center" colspan="2"><html:submit>Sign-In !</html:submit></td>
</tr> 



</table>
</html:form>
</td>

<!-- 
</tr>
</table>
</td> -->
</tr>
</table>

</center>
<body>
</html:html>