Sunday, February 26, 2012

Sample StrutsPrepareAndExecuteFilter - struts2 framework


package org.apache.struts2.dispatcher.ng.filter;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.dispatcher.ng.*;

// Referenced classes of package org.apache.struts2.dispatcher.ng.filter:
//            FilterHostConfig

public class StrutsPrepareAndExecuteFilter
    implements StrutsStatics, Filter
{

    private PrepareOperations prepare;
    private ExecuteOperations execute;

    public StrutsPrepareAndExecuteFilter()
    {
    }

    public void init(FilterConfig filterConfig)
        throws ServletException
    {
        InitOperations init = new InitOperations();
        FilterHostConfig config = new FilterHostConfig(filterConfig);
        init.initLogging(config);
        org.apache.struts2.dispatcher.Dispatcher dispatcher = init.initDispatcher(config);
        init.initStaticContentLoader(config, dispatcher);
        prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher);
        execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher);
        init.cleanup();
        break MISSING_BLOCK_LABEL_91;
        Exception exception;
        exception;
        init.cleanup();
        throw exception;
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException
    {
        HttpServletRequest request;
        HttpServletResponse response;
        request = (HttpServletRequest)req;
        response = (HttpServletResponse)res;
        prepare.createActionContext(request, response);
        prepare.assignDispatcherToThread();
        prepare.setEncodingAndLocale(request, response);
        request = prepare.wrapRequest(request);
        org.apache.struts2.dispatcher.mapper.ActionMapping mapping = prepare.findActionMapping(request, response);
        if(mapping == null)
        {
            boolean handled = execute.executeStaticResourceRequest(request, response);
            if(!handled)
            {
                chain.doFilter(request, response);
            }
        } else
        {
            execute.executeAction(request, response, mapping);
        }
        prepare.cleanupRequest(request);
        break MISSING_BLOCK_LABEL_141;
        Exception exception;
        exception;
        prepare.cleanupRequest(request);
        throw exception;
    }

    public void destroy()
    {
        prepare.cleanupDispatcher();
    }
}

Sample error page.jsp for struts2 app


<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<SCRIPT type="text/javascript">
function disableBackButton()
{
window.history.forward();
}
setTimeout("disableBackButton()", 0);
</SCRIPT>
<title><s:text name="label.exceptionPage"/></title>
</head>
<body  style="background-color: #FAF8CC">
<h4><s:text name="label.heading"/></h4>
<p><s:text name="label.headingMsg"/></p>
----------------------------------------------------------------------------------------------------------------------------------------------------
<h4 style="color: red;"><s:text name="label.exceptionName"/>&nbsp;<s:property value="exceptionClassName" /> </h4>
<h4 style="color: red;"><s:text name="label.exceptionMsg"/>&nbsp;<s:property value="message"/> </h4>
<h4 style="color: red;"><s:text name="label.stacktrace"/>&nbsp;<s:property value="exception.stackTrace"/></h4>
<p><a href="<s:url action='homeAction.action'/>">Home</a></p>
   <p><a href="<s:url action='logOut.action'/>">Logout</a></p>
</body>
</html>

JSP WITH SESSION TIMEOUT LISTENER


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<%@ page language="java" session="true"
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<h2 style="color: red;">
<center>
<noscript>Your browser does not support JavaScript! Application will not work properly.</noscript>
</center>
</h2>
<head>
<meta http-equiv="PRAGMA" content="NO-CACHE"></meta>
<title><tiles:insertAttribute name="title" ignore="true" /></title>
<link rel="stylesheet" type="text/css" href="css/ddsmoothmenu.css" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" type="text/css" href="css/prompt.css" />
<style>
  #ajaxBackground {
display: none;
height: 100%;
width: 96%;
z-index: 9998;
position: absolute;
background-color:white;
top: 0;
-moz-opacity: 0;
-khtml-opacity: 0;
opacity: 0;
filter: alpha(opacity = 0);
}
#ajaxImage {
display: none;
z-index: 9999;
position: fixed;
top: 50%;
left: 50%;
margin-top: -24px;
margin-left: -24px;
}
</style>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/ddsmoothmenu.js"></script>
<script type="text/javascript" src="js/prompt.js"></script>
<script type="text/javascript" src="js/common.js"></script>
<script type="text/javascript">
var sessionTime=0;
//getting the location at which session is expired..START
var loc = (window.location+'');
var hashLoc = loc.indexOf('#');
var hashPart = '';
var urlPart = '';
if(hashLoc!=-1)
{
urlPart = loc.substring(0,hashLoc);
hashPart = loc.substring(hashLoc);
}
//getting the location at which session is expired..END

$(document).ready(function() {
sessionTime=$("#hdnSessionTime").val(); //hidden field value of session time out value
setInterval(timeOut,1000); //calling timeOut function after each second till session expires.
});

function resetTimeOut(){
'<%
  session.setMaxInactiveInterval(session.getMaxInactiveInterval());
%>'
sessionTime=$("#hdnSessionTime").val(); //reseting timeout value with hidden field value of sessionTime time out value
//console.log("timeout value reset to: "+sessionTime);
}

function timeOut(){
//console.log("sessionTime counter started..");
if(sessionTime!=0){
sessionTime=sessionTime-1;
if(sessionTime<=60){
$.prompt('<div id="heading" align="left"><b>Struts2-SpringDemo</div><br/><div style="background: #D8D8D8;padding-left:15px;">You have not been active for awhile.</div></b><br/><div style="padding-left:15px;">You will be logged out in <b>&nbsp;'+sessionTime+ '&nbsp;seconds</b> and <br/>will be returned to the login screen. If you wish <br/>to extend your sessionTime, click Ok.</div>',{
buttons:{Ok:true},
prefix:'jqismooth',
submit:function(v,m,f){
if(!v) return true;
else{
window.location.reload();
}
}
  }
);
}
}
if(sessionTime==0){
$.prompt.close();
window.location.href = "login.jsp?sess=expired";
}
}
</script>
</head>
<body style="background-color: #FAF8CC">
<img id="ajaxImage" src="imgs/ajaxloader.gif" style="display: none;"></img>
<div id="pagewrap">
<div id="ajaxBackground"></div>
<div id="maincontainer">
  <tiles:insertAttribute name="header" />
  <tiles:insertAttribute name="body" />
  <tiles:insertAttribute name="footer" />
</div>
</div>

</body>
<s:hidden id="hdnSessionTime" value='%{#session.sessionTimeOut}' />
</html>

JAVASCRIPT UTILITY FUNCTIONS WITH SAMPLE JQUERY AJAX



/*
 * Function is used to call ajaxRequest
 */
function ajaxRequest(actionName,dataUrl, callBack,options){
var optionsLocal = {"showSpinner":true};
resetTimeOut();
optionsLocal = $.extend(optionsLocal,options);
$.ajax({
url: actionName,
type: "POST",
cache: false,
data:dataUrl,
dataType:"html",
context: document.body,
success: function(data)
{
if(callBack){
if(data=="404"){
callBack("<b>No Data Found</b>",options);}
else
callBack(data,options);
}
},
beforeSend:function (){
if(optionsLocal.showSpinner==true){
$('#ajaxImage').show();
$('#ajaxBackground').show();
}
},
complete:function (){
if(optionsLocal.showSpinner==true){
$('#ajaxImage').hide();
$('#ajaxBackground').hide();
}
},
error: function(){
//Hide the spinner div
$('#ajaxImage').hide();
$('#ajaxBackground').hide();
}
});

}

function triggerOne(){
var valueAtWhichTriigered= $("#dropDownValueUserName").val();
$('#divDropdown option[value="'+valueAtWhichTriigered+'"]').attr("selected","selected"); //automatically select the value in dropdown
$('#divDropdown').trigger('change',valueAtWhichTriigered);//trigger next on basis of that dropdown value
}

function trim(fieldVal){
var field = fieldVal.replace(/^\s+|\s+$/g,"");
return field;
}

function eraseCookie(name) {
setCookie(name, "", -1);
}

function areCookiesEnabled(){
var r = false;
setCookie("test","hello",1);
if (getCookie("test") != null) {
r = true;
eraseCookie("test");
}
return r;
}

function setCheckVal(){
if(document.getElementById("rememberMe").checked){
document.getElementById("rememberMe").value="Y";
}
else{
document.getElementById("rememberMe").value="N";
}
}

function getCookie(c_name){
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++){
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name){
return unescape(y);
}
}
}

function setCookie(c_name,value,exdays){
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}


/**************************************GET USER PROFILE START***********************/

function getUserProfile(){
ajaxRequest("userProfile.action","",getUserProfileManp,{"showSpinner":true});
}

function getUserProfileManp(data,options){
var response=data.split("|");
$("#firstName").val(response[1]);
$("#lastName").val(response[2]);
$("#emailId").val(response[3]);
var role=response[4];
$('#updateMyProfile input[@type=radio][value="'+role+'"]').attr("checked","checked");
$("#updateMyProfile").show();
}

function showProfile(){
ajaxRequest("userProfile.action","",showProfileManp,{"showSpinner":true});
}

function showProfileManp(data,options){
var response=data.split("|");
$("#myFirstName").html(response[1]);
$("#myLastName").html(response[2]);
$('#myEmailId').html(response[3]);
$('#myRole').html(response[4]);
$("#myProfile").show();
}

/**************************************GET USER PROFILE END***********************/

/**************************************USER MANAGEMENT START***************************/

function showChangePassword(){
$("#changePassword").show();
}

function createUsers(){
$("#createNewUser").show();
}


$(function() {
$("#updateMyProfile input").keypress(function(e) {
if (e.keyCode == 13)
{
updateUserProfile();
}
});
});



function updateUserProfile(){
var validate=false;
var usernameField=$("#username");
var firstNameField=$("#firstName");
var lastNameField=$("#lastName");
var emailField=$("#emailId");
var username=usernameField.val();
var firstName=trim(firstNameField.val());
var lastName=trim(lastNameField.val());
var email=trim(emailField.val());
var role=$("input[@type=radio]:checked").val();
if(validateField(firstNameField,firstName,$("#frstNameReq"))==true){
validate=true;
}
if(validateField(lastNameField,lastName,$("#lstNameReq")) ==true){
validate=true;
}
if(validateEmail(emailField,email,$("#emailReq"))==true){
validate=true;
}
var dataUrl="authBean.userName="+username+"&authBean.firstName="+firstName+"&authBean.lastName="+lastName+"&authBean.emailId="+email+"&authBean.role="+role;
if(validate!=true){
ajaxRequest("updateProfile.action",dataUrl,updateUserProfileManp,{"showSpinner":true});
}
}

function updateUserProfileManp(data,options){
$("#updateMsg").html(data);
$("#updateMsg").show();
}


$(function() {
$('#changePassword input').keypress(function(e) {
if (e.keyCode == 13)
{
changePassword();
}
});
});

function changePassword(){
var validate=false;
var userNameField=$("#username");
var oldPassField=$("#oldPass");
var newPassField=$("#newPass");
var confPassField=$("#confirmPass");
var username=userNameField.val();
var oldPassword=trim(oldPassField.val());
var newPassword=trim(newPassField.val());
var confirmPassword=trim(confPassField.val());
var dataUrl="";
if(validateField(oldPassField,oldPassword,$("#oldPassReq"))==true){
validate=true;
}
if(validateField(newPassField,newPassword,$("#newPassReq"))==true){
validate=true;
}
if(validateField(confPassField,confirmPassword,$("#confPassReq"))==true){
validate=true;
}
if(confirmPassword==newPassword && validate!=true){
dataUrl="authBean.userName="+username+"&authBean.oldPassword="+oldPassword+"&authBean.newPassword="+newPassword;
ajaxRequest("changePassword.action",dataUrl,changePasswordManp,{"showSpinner":true});
}
else{
if(validate!=true){
newPassField.addClass("error");
confPassField.addClass("error");
$("#changePassMsg2").html("Confirmed password not matching with new password!!");
$("#changePassMsg2").show();
}
}
}

function changePasswordManp(data,options){
$('#changePassword input').removeClass('error');
$("#oldPass").val('');
$("#newPass").val('');
$("#confirmPass").val('');
$("#changePassMsg2").html('');
$("#changePassMsg2").hide();
if(data=="Old password is incorrect!"){
$("#oldPass").addClass("error");
$("#oldPassReq").html(data);
$("#oldPassReq").show();
}
else{
$("#changePassMsg").html(data);
$("#changePassMsg").show();
}
}

$(function() {
$('#createNewUser input').keypress(function(e) {
if (e.keyCode == 13)
{
createUser();
}
});
});


function createUser(){
var validate=false;
var dataUrl="";
var userName=$("#userNameCu");
var firstName=$("#frstNameCu");
var lastName=$("#lastNameCu");
var email=$("#emailCu");
var role=$("#roleCu");
var userNameVal=trim(userName.val());
var firstNameVal=trim(firstName.val());
var lastNameVal=trim(lastName.val());
var emailVal=trim(email.val());
var roleVal=role.val();

if(validateField(userName,userNameVal,$("#userNameReqCu"))==true){
validate=true;
}
if(validateField(firstName,firstNameVal,$("#frstNameReqCu")) ==true){
validate=true;
}
if(validateField(lastName,lastNameVal,$("#lstNameReqCu")) ==true){
validate=true;
}
if(validateEmail(email,emailVal,$("#emailReqCu"))==true){
validate=true;
}
if(validateDropdown(role,roleVal,$("#rolReqCu"))==true){
validate=true;
}

if(validate!=true){
dataUrl="authBean.userName="+userNameVal+"&authBean.firstName="+firstNameVal+"&authBean.lastName="+lastNameVal+"&authBean.emailId="+emailVal+"&authBean.role="+roleVal;
ajaxRequest("createUser.action",dataUrl,createUserManp,{"showSpinner":true});
}
}

function createUserManp(data,options){
$('#createNewUser input').removeClass('error');
$("#userNameCu").val('');
$("#frstNameCu").val('');
$("#lastNameCu").val('');
$("#emailCu").val('');
$("#roleCu").val('');
if(data.indexOf("Duplicate") != -1){
$("#createMsg2").html(data);
$("#createMsg2").show();
}
else{
$("#createMsg").html(data);
$("#createMsg").show();
}
}

/**************************************USER MANAGEMENT END***************************/

/************************************VALIDATION LOGIC START****************************************************/

function validateField(fld,fldVal,errorFld){
var validate =false;
if(trim(fldVal) == ""){
validate=true;
fld.addClass("error");
errorFld.html("This field is required.");
errorFld.show();
}
return validate;
}

function validateDropdown(Id,Val,errorFld){
var validate =false;
if(Val == "-1"){
validate=true;
Id.addClass("error");
errorFld.html("This field is required.");
errorFld.show();
}
else{
validate=false;
Id.removeClass("error");
errorFld.html("");
errorFld.hide();
}
return validate;
}

function validateEmail(emailFld,emailVal,errorFld){
var validate =false;
if(trim(emailVal) == ""){
validate=true;
emailFld.addClass("error");
errorFld.html("This field is required!");
errorFld.show();
}
else{
var filter = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
//Testing Email Regex
if(!filter.test(emailVal)){
emailFld.addClass("error");
errorFld.html("Not a valid email!");
errorFld.show();
validate= true;
}else if(emailVal.length > 50){
emailFld.addClass("error");
errorFld.html("Email must be less than 50 characters!");
errorFld.show();
validate= true;
}
}
return validate;
}

/******************** VALIDATION FOR UPDATE USER START*********************************/
function validateUserNameOnBlur(obj){
validateField($(obj),$(obj).val(),$("#userNameReqCu"));
}

function validateFirstNameOnBlur(obj){
validateField($(obj),$(obj).val(),$("#frstNameReq"));
}

function validateLastNameOnBlur(obj){
validateField($(obj),$(obj).val(),$("#lstNameReq"));
}

function validateEmailOnBlur(obj){
if(trim($(obj).val())=="" ){
validateField($(obj),$(obj).val(),$("#emailReq"));
}else{
validateEmail($(obj),$(obj).val(),$("#emailReq"));
}
}

/*****************************VALIDATION FOR UPDATE USER END*********************************/

/*****************************VALIDATION FOR CREATE USER START ******************************/
function validateNewUserNameOnBlur(obj){
validateField($(obj),$(obj).val(),$("#userNameReqCu"));
}

function validateNewUserFirstNameOnBlur(obj){
validateField($(obj),$(obj).val(),$("#frstNameReqCu"));
}

function validateNewUserLastNameOnBlur(obj){
validateField($(obj),$(obj).val(),$("#lstNameReqCu"));
}

function validateNewUserEmailOnBlur(obj){
if(trim($(obj).val())=="" ){
validateField($(obj),$(obj).val(),$("#emailReqCu"));
}else{
validateEmail($(obj),$(obj).val(),$("#emailReqCu"));
}
}

function validateDropDwnOnChange(obj){
validateDropdown($(obj), $(obj).val(), $("#rolReqCu"));
}

/******************************VALIDATION FOR CREATE USER END**********************************/

/********************************VALIDATION FOR CHANGE PASSWORD START *************************/
function validateOldPassOnBlur(obj){
validateField( $(obj),$(obj).val(),$("#oldPassReq"));
}

function validateNewPassOnBlur(obj){
validateField($(obj),$(obj).val(),$("#newPassReq"));
}

function validateConfPassOnBlur(obj){
validateField($(obj),$(obj).val(),$("#confPassReq"));
}
/***************VALIDATION FOR CHANGE PASSWORD END**********************************************/

/************************************VALIDATION LOGIC END******************************************************/

/************************************CANCEL AND CLAER ERRORS START*****************************/

function cancleFunct(arg){
var mode=$(arg).attr('name');
if(mode=="cancleChangePass"){
$("#oldPass").val('');
$("#newPass").val('');
$("#confirmPass").val('');
$("#changePassMsg").html("");
$("#changePassMsg").hide();
$("#changePassMsg2").html("");
$("#changePassMsg2").hide();
$("#changePassword").hide();
$("#oldPass").removeClass("error");
$("#newPass").removeClass("error");
$("#confirmPass").removeClass("error");
$("#oldPassReq").html("");
$("#oldPassReq").hide();
$("#newPassReq").html("");
$("#newPassReq").hide();
$("#confPassReq").html("");
$("#confPassReq").hide();
}
else if(mode=="closeProfile"){
$("#myProfile").hide();
}
else if(mode=='cancleCreateUser'){
$("#userNameCu").val('');
$("#frstNameCu").val('');
$("#lastNameCu").val('');
$("#emailCu").val("");
$("#roleCu").val("");
$("#userNameCu").removeClass("error");
$("#frstNameCu").removeClass('error');
$("#lastNameCu").removeClass('error');
$("#emailCu").removeClass("error");
$("#roleCu").removeClass("error");
$("#userNameReqCu").html("");
$("#userNameReqCu").hide();
$("#frstNameReqCu").html("");
$("#frstNameReqCu").hide();
$("#lstNameReqCu").html("");
$("#lstNameReqCu").hide();
$("#emailReqCu").html("");
$("#emailReqCu").hide();
$("#rolReqCu").html("");
$("#rolReqCu").hide();
$("#createMsg").html("");
$("#createMsg").hide();
$("#createMsg2").html("");
$("#createMsg2").hide();
$("#createNewUser").hide();
}
else{
$("#updateMyProfile").hide();
$("#updateMsg").html("");
$("#updateMsg").hide();
$("#errorMsgUpdate").html("");
$("#errorMsgUpdate").hide();
$("#frstNameReq").html("");
$("#frstNameReq").hide();
$("#lstNameReq").html("");
$("#lstNameReq").hide();
$("#emailReq").html("");
$("#emailReq").hide();
$("#firstName").removeClass("error");
$("#lastName").removeClass("error");
$("#emailId").removeClass("error");

}
}

function clearFieldErrors(obj){
var field=$(obj).attr('id');
if(field=="userNameCu"){
$("#userNameCu").removeClass('error');
$("#userNameReqCu").html("");
$("#userNameReqCu").hide();
}
else if(field=="firstName"){
$("#firstName").removeClass('error');
$("#frstNameReq").html("");
$("#frstNameReq").hide();
}
else if(field=="lastName"){
$("#lastName").removeClass('error');
$("#lstNameReq").html("");
$("#lstNameReq").hide();
}
else if(field=="emailId"){
$("#emailId").removeClass('error');
$("#emailReq").html("");
$("#emailReq").hide();
}
else if(field=="oldPass"){
$("#oldPass").removeClass('error');
$("#oldPassReq").html("");
$("#oldPassReq").hide();
}
else if(field=="newPass"){
$("#newPass").removeClass('error');
$("#newPassReq").html("");
$("#newPassReq").hide();
}
else if(field=="confirmPass"){
$("#confirmPass").removeClass('error');
$("#confPassReq").html("");
$("#confPassReq").hide();
}
else if(field=="userNameCu"){
$("#userNameCu").removeClass('error');
$("#userNameReqCu").html("");
$("#userNameReqCu").hide();
}
else if(field=="frstNameCu"){
$("#frstNameCu").removeClass('error');
$("#frstNameReqCu").html("");
$("#frstNameReqCu").hide();
}
else if(field=="lastNameCu"){
$("#lastNameCu").removeClass('error');
$("#lstNameReqCu").html("");
$("#lstNameReqCu").hide();
}
else if(field=="emailCu"){
$("#emailCu").removeClass('error');
$("#emailReqCu").html("");
$("#emailReqCu").hide();
}
else if(field=="roleCu"){
$("#roleCu").removeClass('error');
$("#rolReqCu").html("");
$("#rolReqCu").hide();
}
}

function clearErrors(){
$('.serverError').hide();
$("#sessExpID").html("");
$("#sessExpID").hide();
$(".errorMessage").html("");
$(".errorMessage").hide();
$(".serverActionError").html("");
$(".serverActionError").hide();
$("#updateMsg").html("");
$("#updateMsg").hide();
$("#errorMsgUpdate").html("");
$("#errorMsgUpdate").hide();
$("#changePassMsg").html("");
$("#changePassMsg").hide();
$("#changePassMsg2").html("");
$("#changePassMsg2").hide();
$("#createMsg").html("");
$("#createMsg").hide();
$("#createMsg2").html("");
$("#createMsg2").hide();
}
/************************************CANCEL AND CLAER ERRORS END*****************************/

Session and Context listener for web application


package com.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.utility.Utilities;

/**
 * **********************************************************************
 * @ServletContextListener-----------------------------------------------
 * The listener interface for receiving appContextAndSession events.
 * The class that is interested in processing a appContextAndSession
 * event implements this interface, and the object created
 * with that class is registered with a component using the
 * component's <code>addAppContextAndSessionListener<code> method. When
 * the appContextAndSession event occurs, that object's appropriate
 * method is invoked.
 * @see AppContextAndSessionEvent
 * ************************************************************************
 * @HttpSessionListener----------------------------------------------------
 * The listener interface for receiving session events.
 * The class that is interested in processing a session
 * event implements this interface, and the object created
 * with that class is registered with a component using the
 * component's <code>addSessionListener<code> method. When
 * the session event occurs, that object's appropriate
 * method is invoked.
 * @see SessionEvent
 */
public class AppContextAndSessionListener implements ServletContextListener,HttpSessionListener {

public AppContextAndSessionListener() {
super();
logger.info("AppContextAndSessionListener instantiated..");
}

/** The logger. */
protected final Log logger = LogFactory.getLog(getClass());

/* (non-Javadoc)
* @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
*/
@Override
public void contextDestroyed(ServletContextEvent arg0) {
logger.info("contextDestroyed destroyed..");
}

/* (non-Javadoc)
* @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
*/
@Override
public void contextInitialized(ServletContextEvent arg0) {
logger.info("contextDestroyed initialized..");
}


/* (non-Javadoc)
* @see javax.servlet.http.HttpSessionListener#sessionCreated(javax.servlet.http.HttpSessionEvent)
*/
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
logger.info("SessionListener creating a new session..");
HttpSession sess=httpSessionEvent.getSession();
sess.setAttribute("sessionTimeOut", sess.getMaxInactiveInterval());
}


/* (non-Javadoc)
* @see javax.servlet.http.HttpSessionListener#sessionDestroyed(javax.servlet.http.HttpSessionEvent)
*/
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
logger.info("SessionListener destroying the session..");
if(Utilities.getSessionCount()!=0){
Utilities.decrementCounter();
logger.info("Session counter decremented!");
}
}
}

Global exception class for struts2 app


package com.exception;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.ValueStack;
import com.propertyReader.PropertyReader;
import com.utility.Utilities;

/**
 * The Class GlobalException.
 */
public class GlobalException extends Utilities{

/**
* Instantiates a new global exception.
*/
public GlobalException() {
super();
}

/**
* Instantiates a new global exception.
*
* @param exception the exception
*/
public GlobalException(Exception exception) {
super();
this.exception = exception;
}

/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;

/** The exception. */
private Exception exception;

/** The message. */
private String message;

/** The exception class name. */
private String exceptionClassName;

/**
* Gets the exception class name.
*
* @return the exception class name
*/
public String getExceptionClassName() {
return exceptionClassName;
}

/**
* Sets the exception class name.
*
* @param exceptionClassName the new exception class name
*/
public void setExceptionClassName(String exceptionClassName) {
this.exceptionClassName = exceptionClassName;
}

/**
* Gets the message.
*
* @return the message
*/
public String getMessage() {
return message;
}

/**
* Sets the message.
*
* @param message the new message
*/
public void setMessage(String message) {
this.message = message;
}

/**
* Gets the exception.
*
* @return the exception
*/
public Exception getException() {
return exception;
}

/**
* Sets the exception.
*
* @param exception the new exception
*/
public void setException(Exception exception) {
this.exception = exception;
}

/* (non-Javadoc)
* @see com.action.AbstractAction#execute()
*/
public String execute(){
logger.info("GlobalException action invoked..");
setExceptionClassName(exception.getClass().getName());
logger.error("Error class: "+getExceptionClassName());
setMessage(findExceptionBase());
getResponse().setStatus(500);
exception.printStackTrace();
return PropertyReader.getStrutsConstantsProperty("globalException");
}


/**
* Find exception base.
*
* @return the string
*/
private String findExceptionBase() {      
ActionContext ac = ActionContext.getContext();
ValueStack vs = ac.getValueStack();
return "Exception arised in "+vs.getRoot().get(2).getClass().getSimpleName().toString();
}
}

#######################################


<!-- GLOBAL RESULTS AND MAPPINGS START-->
<global-results>
<result name="Exception" type="chain">demoExceptionHandler</result>
<result name="securityError">/jsp/securityError.jsp</result>
</global-results>
<!-- GLOBAL RESULTS AND MAPPINGS END-->

<!-- GLOBAL EXCEPTIONS AND MAPPINGS START-->
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception"
result="Exception" />
</global-exception-mappings>

<!-- GLOBAL EXCEPTIONS ACTION -->
<action name="demoExceptionHandler" class="com.exception.GlobalException">
<result name="demoException">/jsp/error.jsp</result>
</action>

<!-- GLOBAL EXCEPTIONS AND MAPPINGS START-->


Struts file upload example..


package com.action;

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;


import com.utility.Utilities;

/**
 * The Class FileUploaderAction.
 */
public class FileUploaderAction extends Utilities{

/**
* Instantiates a new file uploader action.
*/
public FileUploaderAction() {
super();
       logger.info("FileUploaderAction instantiated..");
}

/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;

/** The file. */
private File userImage;

/**
* @return the userImage
*/
public File getUserImage() {
return userImage;
}

/**
* @param userImage the userImage to set
*/
public void setUserImage(File userImage) {
this.userImage = userImage;
}

/** The user image content type. */
private String userImageContentType;

/** The user image file name. */
private String userImageFileName;


/**
* Gets the user image content type.
*
* @return the userImageContentType
*/
public String getUserImageContentType() {
return userImageContentType;
}

/**
* Sets the user image content type.
*
* @param userImageContentType the userImageContentType to set
*/
public void setUserImageContentType(String userImageContentType) {
this.userImageContentType = userImageContentType;
}

/**
* Gets the user image file name.
*
* @return the userImageFileName
*/
public String getUserImageFileName() {
return userImageFileName;
}

/**
* Sets the user image file name.
*
* @param userImageFileName the userImageFileName to set
*/
public void setUserImageFileName(String userImageFileName) {
this.userImageFileName = userImageFileName;
}




/**
* Upload file.
*
* @return the string
*/
public String uploadFile(){
logger.info("uploadFile invoked..");
return SUCCESS;
}

/**
* Upload file.
*
* @return the string
* @throws Exception the exception
*/
public String uploadImageFile() throws Exception{
logger.info("uploadImageFile invoked..");
try {

String filePath = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/");
logger.info("Server path:" + filePath);
if(userImageFileName!=null && userImage!=null){
File fileToCreate=new File(filePath, this.userImageFileName);
FileUtils.copyFile(this.userImage, fileToCreate);
}
else{
addActionMessage("An empty file can not be uploaded..");
return INPUT;
}

} catch (Exception e) {
e.printStackTrace();
addActionError("Exception occured while uploading the file..");
return INPUT;
}
return SUCCESS;
}

}
#######################################
<action name="uploadFile" class="com.action.FileUploaderAction"
method="uploadFile">
<result name="success" type="tiles">/fileUpload.tiles</result>
</action>
<action name="uploadImage" class="com.action.FileUploaderAction"
method="uploadImageFile">
<interceptor-ref name="sessionCheckStack"/>
<interceptor-ref name="fileUpload">
<param name="maximumSize">2097152</param>
<param name="allowedTypes">
image/png,image/gif,image/jpeg,image/bmp
                </param>
</interceptor-ref>
<result name="input" type="tiles">/fileUpload.tiles</result>
<result name="success" type="tiles">/fileUploadSuccess.tiles</result>
</action>

Struts custom controller example..


package com.customController;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;

import com.dbInitializer.DBInitializer;
import com.propertyReader.PropertyReader;
import com.utility.MailUtil;


/**
 * The Class StrutsSpringDemoController.
 */
public class CustomController extends StrutsPrepareAndExecuteFilter {

/** The logger. */
protected final Log logger = LogFactory.getLog(getClass());

/** The request. */
protected HttpServletRequest request;

/** Initial setup of database when application is deployeed first time on mechine */
static{
try {
DBInitializer.createDBAndTables();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* Instantiates a new struts spring demo controller.
*/
public CustomController(){
logger.info("Custom controller instantiated..");
}

/* (non-Javadoc)
* @see org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig)
throws ServletException
{
logger.info("Custom controller init..");
super. init(filterConfig) ;
if(DBInitializer.flag){
MailUtil sendMail=new MailUtil();
String mailContent="Hi "+DBInitializer.getFirstname()+" "+DBInitializer.getLastname()+PropertyReader.getProperty("mailContent")+"UserName: "+DBInitializer.getUsername()+"<br/>Password: "+DBInitializer.getPassword()
+PropertyReader.getProperty("mailContentLink")
+PropertyReader.getProperty("mailConetntLinkRef")
+PropertyReader.getProperty("mailContentThankStmt");

if(PropertyReader.getProperty("mailMode").equalsIgnoreCase("orgMail"))
{
sendMail.sendMail(DBInitializer.getEmailid(),PropertyReader.getProperty("mailSubject"),mailContent);
}else{
sendMail.sendMailViaGmail(DBInitializer.getEmailid(),PropertyReader.getProperty("mailSubject"),mailContent);
}
}
}

/* (non-Javadoc)
* @see org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException
{
logger.info("Custom controller doFilter..");
request =(HttpServletRequest)req;
String url = request.getRequestURL().toString();
String servletPath = request.getServletPath();
logger.info("Request data: url= "+url+" and servletPath= "+servletPath);
String currentUrl = request.getRequestURI();
String queryString = request.getQueryString();
String typeOfRequest = request.getHeader("X-Requested-With");
logger.info("Current URL :"+currentUrl+" Query String :"+queryString+" REQUEST TYPE: "+typeOfRequest);
super.doFilter(req, res, chain);
}

/* (non-Javadoc)
* @see org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter#destroy()
*/
public void destroy(){
logger.info("Custom controller destroy..");
super.destroy();
}
}

Struts session interceptor example with pre and post processing logic


package com.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.propertyReader.PropertyReader;

/**
 * The Class SessionInterceptor.
 */
public class SessionInterceptor implements Interceptor {

/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The logger. */
protected final Log logger = LogFactory.getLog(getClass());

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#init()
*/
public void init() {
logger.info("SessionInterceptor init..");
}

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
*/
public void destroy() {
logger.info("SessionInterceptor destroy...");
}

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
*/
public String intercept(ActionInvocation invocation) throws Exception {
logger.info("SessionInterceptor intercepting...");
final ActionContext context = invocation.getInvocationContext();
HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
HttpSession session = request.getSession(true);
String sessionValidate = (String) session.getAttribute("sessionValidate");
logger.info("Session validate: "+sessionValidate);
logger.info("Max inactive interval is: "+session.getAttribute("sessionTimeOut"));
String actionName = invocation.getInvocationContext().getName();
logger.info("Passing to action: "+actionName);
if(!actionName.equalsIgnoreCase("loginAction") && !(actionName.equalsIgnoreCase("demoExceptionHandler"))){
if ((sessionValidate == null || sessionValidate.equals("false"))) {
logger.info("User session expired..");
return PropertyReader.getStrutsConstantsProperty("sessionExpired");
}
}
String invocationString= invocation.invoke();
logger.info("Back to interceptor..");
logger.info("Back from action: "+actionName);
return invocationString;
}
}