Skip to main content

Varargs:- Variable argument method in Java 5

· One min read

Varargs enables to write methods which can takes variable length of arguments.Varargs was added in Java 5 and the syntax includes three dots … provides the functionality to pass any number of arguments to a method.

Syntax

public void showDepartmentEmp(int deptCode, String... deptEmp){}
Example
public class Department {

public static void main(String args[]) {
showDepartmentEmp(100, "Sandeep", "Gaurav");
showDepartmentEmp(111, "Meenakshi", "Aditya", "Saurabh");
}

public static void showDepartmentEmp(int deptCode, String... deptEmp) {
System.out.print("\n"+deptCode);
for(String emp: deptEmp) {
System.out.print(", " + emp);
}
}
}

Create file type input using textbox and simple button

· One min read
Sandeep Bhardwaj

Some times we have requirement to create a file type input in HTML with using simple textbox and a simple button for browse functionality. I search a lot on Google to achieve this functionality but there is no option available in javascript or in jQuery to open file dialog using a simple button.

Then i used a simple trick to achieve this.

<input name="browse" style="display: none;" type="file">                                                   
<input name="fileInput" maxlength="255" type="text">
<input onclick="browse.click();fileInput.value=browse.value;" value="Browse.." type="button">

Trim method in JavaScript

· One min read
Sandeep Bhardwaj

We can use String.replace method to trim a string in javascript.

//method for trim a complete string like "  Hello World   "  
function trim(str) {
return str.replace(/^\s+|\s+$/g,"");
}

//method for left trim a string like " Hello World"
function leftTrim(str) {
return str.replace(/^\s+/,"");
}

//method for right trim a string like "Hello World "
function rightTrim(str) {
return str.replace(/\s+$/,"");
}

Renaming files using command prompt on windows

· One min read

Suppose we have lots of lots file in a directory and we need to rename of modify the extension of all the file, then renaming one by one is pain and not a good idea as well. In that case we can use ren or rename command on windows.

If we want to rename all the files in directory in one shot then we can use ren or rename command on command prompt.

Example:- If we want to rename all html files to jsp files of directory D:\pages\ then executes the command.

D:\pages>ren *.html *.jsp

Main method in java

· One min read
Sandeep Bhardwaj

public static void main(String arg[])

In Java we write public static void main (String args[]) instead of just main because:

public static void main(String arg[])   
{

}

public


The main method must be public because it is call from outside the class. It is called by jvm.

static


The main method must be static because without creating an instance jvm can call it.
If the main method is non static then it is must to create an instance of the class.

void


Main method doesn't return anything therefore it is void also.

Strings args[]


It is used for receiving any arbitrary number of arguments and save it in the array.

How Class.forName() method works ?

· 2 min read

Class.forName()

  1. Class.forName("XYZ") method dynamically loads the class XYZ (at runtime).
  2. Class.forName("XYZ") initialized class named XYZ (i.e., JVM executes all its static block after class loading).
  3. Class.forName("XYZ") returns the Class object associated with the XYZ class. The returned Class object is not an instance of the XYZ class itself.

Class.forName("XYZ")loads the class if it not already loaded. The JVM keeps track of all the classes that have been previously loaded. The XYZ is the fully qualified name of the desired class.

For example
package com.usebrain.util;

public class LoadClass {
static {
System.out.println("************LoadClass static block************");
}
}


package com.usebrain.action;

public class Test {

public static void main(String[] args) {
try {
Class c = Class.forName("com.usebrain.util.LoadClass");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

Example that use returned Class to create an instance of LoadClass:

package com.usebrain.util;

public class LoadClass {
static {
System.out.println("************LoadClass static block************");
}

public LoadClass() {
System.out.println("*************LoadClass Constructor************");
}
}


package com.usebrain.action;

import com.usebrain.util.LoadClass;

public class Test {

public static void main(String[] args) {

try {
System.out.println("first time calls forName method");

Class loadObj = Class.forName("com.usebrain.util.LoadClass");
LoadClass loadClass = (LoadClass) loadObj.newInstance();

System.out.println("\nsecond time calls forName method");
Class.forName("com.usebrain.util.LoadClass");

} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Output
first time calls forName method
************LoadClass static block************
*************LoadClass Constructor************

second time calls forName method

Class already loaded when Class.forName() execute first time so at second time when Class.forName() execute not loads the class again.

Hello World using Apache ANT

· 3 min read
Sandeep Bhardwaj

Old way of compile a project, making jar and running the jar

Project Structure


Make project structure using command prompt like

H:\>md DemoProject  
H:\>md DemoProject\src\hello
H:\>md DemoProject\build\classes

Make a java class


Now make a simple java class HelloWorld

package hello;  

public class HelloWorld {

public static void main(String[] args) {
System.out.println("Hello World");
}

}

Compile the code


Compile the java cod using the command below

H:\>javac -sourcepath DemoProject\src -d DemoProject\build\classes DemoProject\src\hello\HelloWorld.java  

Make the jar


To make the jar file we need to create manifest file containing the information of class with contain main method.

H:\>cd DemoProject  
H:\DemoProject>md build\jar
H:\DemoProject>jar cfm build\jar\HelloWorld.jar myManifest -C build\classes .

Run the code


Now we can run our HelloWorld jar file using the command below.

H:\DemoProject>java -jar build\jar\HelloWorld.jar Hello World  

Now doing with Smarter way using Ant

By using ant we just need to execute 4 steps.
Create only source (src) directory and place HelloWorld.java in to hello folder and manifest file parallel to src folder do not need to create build directory, it will created by ant.

H:\>md DemoProject  
H:\>md DemoProject\src\hello

Step 1:


Create a build.xml file (By default Ant uses build.xml) in to DemoProject directory (parallel to the src directory)

<project>
<target name="clean">
</target>

<target name="compile">
<mkdir dir="build/classes">
<javac srcdir="src" destdir="build/classes"></javac>
</mkdir>
</target>

<target name="jar">
<mkdir dir="build/jar">
<jar destfile="build/jar/HelloWorld.jar" basedir="build/classes">
<manifest>
<attribute name="Main-Class" value="hello.HelloWorld"></attribute>
</manifest>
</jar>
</mkdir>
</target>

<target name="run">
<java jar="build/jar/HelloWorld.jar" fork="true"></java>
</target>
</project>

Step 2:


Compile the code (move to the DemoProject directory before running the commands)

H:\>cd DemoProject  

H:\DemoProject>ant compile
Buildfile: H:\DemoProject\build.xml

compile:
[mkdir] Created dir: H:\DemoProject\build\classes
[javac] H:\DemoProject\build.xml:9: warning: 'includeantruntime' was not set
, defaulting to build.sysclasspath=last; set to false for repeatable builds
[javac] Compiling 1 source file to H:\DemoProject\build\classes

BUILD SUCCESSFUL
Total time: 8 seconds

Step 3


Make the jar (pack the code)

H:\DemoProject>ant jar  
Buildfile: H:\DemoProject\build.xml

jar:
[mkdir] Created dir: H:\DemoProject\build\jar
[jar] Building jar: H:\DemoProject\build\jar\HelloWorld.jar

BUILD SUCCESSFUL
Total time: 4 seconds

Step 4:


Run the code

H:\DemoProject>ant run  
Buildfile: H:\DemoProject\build.xml

run:
[java] Hello World

BUILD SUCCESSFUL
Total time: 4 seconds

Now you can see that using ANT makes our work easy and simpler than old technique. We can also execute all these commands in one line like this

H:\DemoProject>ant compile jar run  
Buildfile: H:\DemoProject\build.xml

compile:
[mkdir] Created dir: H:\DemoProject\build\classes
[javac] H:\DemoProject\build.xml:9: warning: 'includeantruntime' was not set
, defaulting to build.sysclasspath=last; set to false for repeatable builds
[javac] Compiling 1 source file to H:\DemoProject\build\classes

jar:
[mkdir] Created dir: H:\DemoProject\build\jar
[jar] Building jar: H:\DemoProject\build\jar\HelloWorld.jar

run:
[java] Hello World

BUILD SUCCESSFUL
Total time: 11 seconds

Hope you like this post.
I used apache reference manual for this blog its good and simple. Use Apache manual for depth knowledge.

Installing Apache Ant

· One min read
Sandeep Bhardwaj

Apache Ant is a Java-based build tool.

Download Ant


Download Apache ANT from this URL. http://ant.apache.org/bindownload.cgi

Installing Ant

The binary distribution of Ant consists of the following directory layout:
ant

   +--- bin  // contains launcher scripts  
|
+--- lib // contains Ant jars plus necessary dependencies
|
+--- Extra directories

Only the bin and lib directories are required to run Ant.
To install Ant, choose a directory and copy the distribution files and extract there. This directory will be known as ANT_HOME.

Setup


The ant.bat script makes use of three environment variables –

  1. ANT_HOME,
  2. CLASSPATH (optional not required )and
  3. JAVA_HOME.

Assume Ant is installed in c:\ apache-ant-1.8.1. The following sets up the environment:

set ANT_HOME=c:\apache-ant-1.8.1  
set JAVA_HOME=C:\jdk1.6.0_20
set PATH=%PATH%;%ANT_HOME%\bin

Check Installation


You can check the basic installation with opening a command prompt and typing

C:\>ant -version  
Apache Ant version 1.8.1 compiled on April 30 2010

Struts2 with login interceptor

· 5 min read

Hi All,

This is my first blog and this blog is for those who are not beginners because I am not going to explain HelloWorld application here. So if you are a beginner of Struts2 then follow the link.

About application

It’s an application of Struts 2 with LoginInterceptor this will perform these tasks:-

  1. Check user exist in session or not.
  2. Runs before every action to check .If some one try to access direct url of welcome page and not present in session then it will redirect towards login page.
  3. If user already in session then call the action called by user.
  4. If session time out and user clicks on any link, then also redirect towards login page.

Package Structure

jar required

web.xml

web.xml with struts2 configuration and defining session time out 1 min.

<?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" 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>login-app</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>

struts.xml

Here we configure our custom interceptor named LoginInterceptor defining loginStack as default stack.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package extends="struts-default" name="default" namespace="/">

<interceptors>
<interceptor class="com.blog.struts.interceptor.LoginInterceptor"
name="loginInterceptor" />
<interceptor-stack name="loginStack">
<interceptor-ref name="loginInterceptor" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>

<default-interceptor-ref name="loginStack"/>

<global-results>
<result name="login">login.jsp</result>
</global-results>

<action class="com.blog.struts.action.LoginAction"
name="loginAuthenticaion">
<result name="login-success">/WEB-INF/pages/welcome.jsp</result>
<result name="input">login.jsp</result>
</action>

<action class="com.blog.struts.action.ProfileAction"
name="profile">
<result name="success">/WEB-INF/pages/profile.jsp</result>
</action>

<action class="com.blog.struts.action.LogoutAction"
name="logout">
<result name="logout">login.jsp</result>
</action>

</package>
</struts>

LoginInterceptor.java

LoginInterceptor class extends AbstractInterceptor and checking user present in session or not.

package com.blog.struts.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.StrutsStatics;

import com.blog.struts.action.LoginAction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoginInterceptor extends AbstractInterceptor implements
StrutsStatics {

private static final Log log = LogFactory.getLog(LoginInterceptor.class);
private static final String USER_HANDLE = "loggedInUser";

public void init() {
log.info("Intializing LoginInterceptor");
}

public void destroy() {
}

public String intercept(ActionInvocation invocation) throws Exception {

final ActionContext context = invocation.getInvocationContext();
HttpServletRequest request = (HttpServletRequest) context
.get(HTTP_REQUEST);
HttpSession session = request.getSession(true);

// Is there a "user" object stored in the user's HttpSession?
Object user = session.getAttribute(USER_HANDLE);
if (user == null) {
// The user has not logged in yet.

/* The user is attempting to log in. */
if (invocation.getAction().getClass().equals(LoginAction.class))
{
return invocation.invoke();
}
return "login";
} else {
return invocation.invoke();
}
}

}

LoginAction.java

LoginAction class with simple bussiness logic you can login with any username and password but cannot left blank the mandatory fields.

package com.blog.struts.action;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
private String userName;
private String password;

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

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

// all struts logic here
public String execute() {

ServletActionContext.getRequest().getSession().setAttribute("loggedInUser", userName);
return "login-success";

}

// simple validation
public void validate() {
if (StringUtils.isNotEmpty(userName)
|| StringUtils.isNotEmpty(password)) {
addActionMessage("You are valid user!");

} else {
addActionError("Username and Password can't be blanked");
}

}
}

LogoutAction.java

LogutAction class calls when user click on logout link.

package com.blog.struts.action;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class LogoutAction extends ActionSupport {

// all struts logic here
public String execute() {

ServletActionContext.getRequest().getSession().invalidate();
addActionMessage("You are successfully logout!");
return "logout";

}
}

ProfileAction.java

ProfileAction executes when we click on profile link on welcome page. If we tried to call the profile action without login then login interceptor redirect user to login page. This is the whole purpose of using the login interceptor.

package com.blog.struts.action;

import com.opensymphony.xwork2.ActionSupport;

public class ProfileAction extends ActionSupport {

// all struts logic here
public String execute() {

return "success";

}
}

Login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login page</title>

<link rel="stylesheet" type="text/css" href="css/style.css" />

</head>
<body>

<s:if test="hasActionErrors()">
<div class="errors">
<s:actionerror />
</div>
</s:if>
<s:if test="hasActionMessages()">
<div class="welcome">
<s:actionmessage />
</div>
</s:if>

<s:form action="loginAuthenticaion.action">
<s:hidden name="loginAttempt" value="%{'1'}" />
<s:textfield label="UserName" name="userName" />
<s:password label="Password" name="password" />

<s:submit label="Login" name="submit" />
</s:form>
</body>
</html>

welcome.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="java.util.Date"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome page</title>

<link rel="stylesheet" type="text/css" href="css/style.css" />

</head>

<body>
<div class="content">
<div style="float: right;">
<a href="profile">Profile</a> | <a href="logout">logout</a>
</div>

</br>
<h3>Struts 2 with Login Interceptor</h3>

<s:if test="hasActionMessages()">
<div class="welcome">
<s:actionmessage />
</div>
</s:if>

<h4>
Hello :
<%=session.getAttribute("loggedInUser")%>
Login time : <%=new Date()%></h4>
</div>

</body>
</html>

profile.jsp

<%@ 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>Profile page</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<div class="content">

<div style="float: right;">
<a href="logout">logout</a>
</div>

</br>
<h3>Struts 2 with Login Interceptor</h3>

<p>
This is profile page . This page can't be accessed by direct access <a
href="http://localhost:8080/login-app/profile.action">http://localhost:8080/login-app/profile.action</a>
if there is no valid used then it will redirect to login page.

</p>
</div>
</body>
</html>

style.css

.errors {
background-color: #FFCCCC;
border: 1px solid #CC0000;
width: 400px;
margin-bottom: 8px;
}

.errors li {
list-style: none;
}

.welcome {
background-color: #DDFFDD;
border: 1px solid #009900;
width: 300px;
}

.welcome li {
list-style: none;
}

.content{
padding: 5px;
height: 400px;

border: 2px solid #d0d1d0;
}

Now paste these files according to package structure and run it by typing http://localhost:8080/LoginApp.

If you tries to hit direct url without login like http://localhost:8080/LoginApp/loginAuthenticaion then it will redirect towards login page.

Next time, i will try to write some more interesting you can also give me some suggestion about new topics.

Thanks, Have a great day !!!