Friday, May 21, 2010

Setting and Getting Attributes from session

//Setting Attribute in session.
String userID="Subin";
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false); session.setAttribute("userId", userID);

//Getting Attribute from the session.
HttpServletRequest hsr = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
String userName = (String) hsr.getSession().getAttribute("userId");

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

Get application's browser path

/**
* This method is defined to get application's browser path
*
* @return ipPath
*/
public static String getIpPath() {
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
String contextPath = request.getContextPath();
StringBuffer requestURL = request.getRequestURL();

String ipPath = requestURL.substring(0, requestURL.indexOf(contextPath)) + contextPath;
System.out.println("Debug ipPath :" + ipPath);
return ipPath;
}

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

Get Machine IPAddress

String machineIP = "";
HttpServletRequest hreq = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
machineIP = hreq.getRemoteHost();

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

Adding new message to Faces Context

/**
* Add a Message to the Faces Context
* @param msg
*/
public static void showMessage(String msg) {
msg = "" + msg;
FacesMessage fm = new FacesMessage(msg);
FacesContext.getCurrentInstance().addMessage(msg, fm);
}

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

Get CurrentDate in YYYY_MM_DD Format

/**
* Here get the current date in format 'YYYY-MM-DD'
*
* @return Current date in format 'YYYY-MM-DD'
*/
public static String getCurrentDate_YYYY_MM_DD() {
// get current date in Format YYYY-MM-DD
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
final String dateFormat = "yyyy-MM-dd";
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(dateFormat);
sdf.setTimeZone(TimeZone.getDefault());
System.out.println("debug "+sdf.format(cal.getTime()));
return sdf.format(cal.getTime());
}

convertDateToString

/**
* Convert Date to String
* @param date
* @return
*/
public static String convertDateToString(Date date) {
String rtnString = "";
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");
//java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DateUtils.DATE_FORMAT);
if (date != null) {
rtnString = sdf1.format(date);
}
return rtnString;
}

convertStringToDate

/**
* Convert String to Date
* @param dateString
* @return
*/
public static Date convertStringToDate(String dateString) {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd-MM-yyyy");
java.util.Date dt = null;
try {
dt = sdf.parse(dateString);
System.out.println("Debug dt :"+dt);
} catch (java.text.ParseException p) {
System.out.println(p.toString());
}
return dt;
}

convertDatePattern

/**
* Change the Date pattern from yyyy/MM/dd to dd-MM-yyyy
* @param dateToParse
* @return
* @throws java.text.ParseException
*/
public static String convertDatePattern(String dateToParse) throws ParseException {
System.out.println("Debug inside convertDatePattern");
if (dateToParse != null && !dateToParse.equals("")) {
if (dateToParse.contains("-")) {
return dateToParse;
} else {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd");
String dateStringToParse = dateToParse;
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf1.parse(dateStringToParse);
dateToParse = sdf2.format(date);
System.out.println("Debug dateToParse:"+dateToParse);
return dateToParse;
}
} else {
System.out.println("Please check the date");
}
return "";
}

Note:Input to this method should be yyyy/MM/dd format.

Thursday, May 20, 2010

Getting CurrentServerDate

/**
* Wrapper / convenience method for getting the current server date
*
* @return Current server Date - "null" if error occurs
*/
public static Date getCurrentServerDate() {
Date serverDate = null;
serverDate = new java.util.Date();
return serverDate;
}

AuthFilter in JSF

AuthFilter is a server side validation to check whether userId is null and if it is null redirects back to login page

1) Creating AuthFilter class in security package.

/*
* Checks userId is null or not
*/
package security;

import java.io.IOException;
import javax.servlet.Filter;
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 javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
*
* @author Subin
*/
public class AuthFilter implements Filter {

public void init(FilterConfig arg0) throws ServletException {
}

public void doFilter(ServletRequest req, ServletResponse res, FilterChain arg2) throws IOException, ServletException {
HttpServletRequest hreq = (HttpServletRequest) req;
HttpServletResponse hres = (HttpServletResponse) res;
HttpSession session = hreq.getSession();
String path = hreq.getPathTranslated();
System.out.println("Context Path: " + hreq.getContextPath() + " Servelet Path: " + hreq.getServletPath());
String domainPath = hreq.getContextPath() + hreq.getServletPath();
System.out.println("User Ip address: " + hreq.getRemoteHost());
//Redirects application to login.jsp if userId is null
if (session.getAttribute("userId") == null ) {
System.out.println("Parameter: " + hreq.getPathTranslated() + " ");
hres.sendRedirect(domainPath + "/login.jsp");
return;
}
arg2.doFilter(req, res);
}

public void destroy() {
}
}


2) Mapping Filter in web.xml

<filter>
<filter-name>AuthFilter</filter-name>
<filter-class>security.AuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

Errror handling in JSF

1) Create a folder called error under webpages folder and create a jsp say
(error500.jsp,error400.jsp).....

place the below code in that jsp

<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Technical Problem Try Again</h1>
<%session.invalidate();%>
<a href="<%=request.getContextPath()%>/home.jsp">Home</a>
</body>
</html>

Note:home.jsp is the redirecting page when the error has occured.


2)Place the below code in web.xml

<!-- ======== Handling Exceptions Start ======== -->
<error-page>
<error-code>400</error-code>
<location>/error/error400.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/error/error404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/error500.jsp</location>
</error-page>
<error-page>
<error-code>501</error-code>
<location>/error/error501.jsp</location>
</error-page>
<error-page>
<error-code>502</error-code>
<location>/error/error502.jsp</location>
</error-page>


<!-- ======== Handling Exceptions End ======== -->

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

Integrating Richfaces with JSF

In my last post i have written JCaptcha in JSF. Today i will be discussing Integrating Richfaces with JSF
1) Add the following jar files to your project
a) richfaces-api-3.2.2.GA.jar
b) richfaces-impl-3.2.2.GA.jar
c) richfaces-ui-3.2.2.GA.jar

  Download all three jars here..
2) Add the following tag libraries to jsp pages

<%@ taglib uri="http://richfaces.org/a4j" prefix="a4j"%>
<%@ taglib uri="http://richfaces.org/rich" prefix="rich"%>

3) Add the following code in web.xml

<filter>
<display-name>RichFaces Filter </display-name>
<filter-name>richfaces </filter-name>
<filter-class>org.ajax4jsf.Filter </filter-class>
</filter>
<filter-mapping>
<filter-name>richfaces </filter-name>
<servlet-name>Faces Servlet </servlet-name>
<dispatcher>REQUEST </dispatcher>
<dispatcher>FORWARD </dispatcher>
<dispatcher>INCLUDE </dispatcher>
</filter-mapping>

JSF Related topics: Errror handling in JSF, Customizing URL Pattern in JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

Wednesday, May 19, 2010

Session TimeOut

<session-config>
<session-timeout>
30
</session-timeout>
</session-config>

Using above code will automatically logout your session after 30min.

Customizing URL Pattern in JSF

To Customize URL Pattern you need to add below code to web.xml

<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/subin/*</url-pattern>
</servlet-mapping>

Once you write this code faces keyword will be replaced by subin.

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

JavaScript function to restrict SpecialCharacter

1) Creating javascript file(util.js) and create function NoSpecialCharacter()

//for NoSpecialCharacter
function NoSpecialCharacter(evt) {

evt = (evt) ? evt : window.event
var charCode = (evt.which) ? evt.which : evt.keyCode
//alert(charCode)
if((charCode > 30 & charCode < 48)|charCode==32 |(charCode > 57 & charCode < 65) |(charCode > 90 & charCode < 97)|(charCode > 122 & charCode < 127) ){
status = "This field accepts No Special Character."
return false
}
status = ""
return true
}

2) Include util.js file in jsp file

<script type='text/javascript' src="<%=request.getContextPath()%>/utils.js"></script>


3)Calling javascript function in jsp
<h:inputText id="tf_NAME" label="Name" autocomplete="off" onkeypress="return NoSpecialCharacter(event);" >

JavaScript function to restrict input to only characters and space

1) Creating javascript file(util.js) and create function onlyCharSpace()

//only characters and space
function onlyCharSpace(evt) {
evt = (evt) ? evt : window.event
var charCode = (evt.which) ? evt.which : evt.keyCode
//alert(charCode)
if((charCode > 31 & charCode < 49)|(charCode > 49 & charCode < 65)|(charCode > 90 & charCode < 97) |(charCode > 122 & charCode < 127)){
status = "This field accepts characters and space only."
return false
}
status = ""
return true
}

2) Include util.js file in jsp file

<script type='text/javascript' src="<%=request.getContextPath()%>/utils.js"></script>


3)Calling javascript function in jsp
<h:inputText id="tf_NAME" label="Name" autocomplete="off" onkeypress="return onlyCharSpace(event)" >

Tuesday, May 18, 2010

JavaScript function to restrict input to only characters

1) Creating javascript file(util.js) and create function onlyCharNoSpace()

//only characters
function onlyCharNoSpace(evt) {
evt = (evt) ? evt : window.event
var charCode = (evt.which) ? evt.which : evt.keyCode
//alert(charCode)
if((charCode > 31 & charCode < 65) |(charCode > 90 & charCode < 97) |(charCode > 122 & charCode < 127)){
status = "This field accepts characters only."
return false
}
status = ""
return true
}

2) Include util.js file in jsp file

<script type='text/javascript' src="<%=request.getContextPath()%>/utils.js"></script>


3)Calling javascript function in jsp
<h:inputText id="tf_NAME" label="Name" autocomplete="off" onkeypress="return onlyCharNoSpace(event)" >

JavaScript function to restrict input to numeric

1) Creating javascript file(util.js) and create function checkIt()
//only numbers
function onlyNum(evt) {
evt = (evt) ? evt : window.event
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
status = "This field accepts numbers only."
return false
}
status = ""
return true
}

2) Include util.js file in jsp file

<script type='text/javascript' src="<%=request.getContextPath()%>/utils.js"></script>

3)Calling javascript function in jsp
<h:inputText id="tf_NAME" label="Name" autocomplete="off" onkeyup="return onlyNum(event);" >

JavaScript function to make text caps

1) Creating javascript file(util.js) and create function makeCaps()

/**
This function get the data on every key press and it will change that data into caps
*/
function makeCaps(data){
var val = data.value;
data.value = val.toUpperCase();

}

2) Include util.js file in jsp file

<script type='text/javascript' src="<%=request.getContextPath()%>/utils.js"></script>

3)Calling javascript function in jsp
<h:inputText id="tf_NAME" label="Name" autocomplete="off" onkeyup="makeCaps(this)">

Clearing Browser Cache

<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"></meta>
<meta content="no-cache" http-equiv="Cache-control"></meta>
<meta content="no-store" http-equiv="Cache-control"></meta>
<meta content="no-cache" http-equiv="Pragma"></meta>
<meta content="0" http-equiv="expires"></meta>

<%
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store");
%>

JavaScript to disable F5 button

<script language="javascript" >
function checkKeyCode(evt)
{

var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if(event.keyCode==116)
{
alert("F5 has been Disabled");
evt.keyCode=0;
return false
}
}
document.onkeydown=checkKeyCode;
</script >

Java Script to Disabling Right Click in Web Browser

<script language="javascript" >
//Disable right mouse click Script
var message="Right Click is Disabled!";

///////////////////////////////////
function clickIE4(){
if (event.button==2){
alert(message);
return false;
}
}

function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
alert(message);
return false;
}
}
}

if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}

document.oncontextmenu=new Function("alert(message);return false")

</script>

Java Script to Disabling Back Button in WebBrowser

<script language="javascript" >
function noBack(){window.history.forward()}
noBack();
window.onload=noBack;
window.onpageshow=function(evt){if(evt.persisted)noBack()}
window.onunload=function(){void(0)}
</script>