Annotation based configuration in Spring

Now It is possible to configure Spring’s dependency injection with annotations. This means that annotations can be used in Spring to mark fields, methods and classes that need dependency injection. Spring also supports auto-wiring of the bean dependencies, that is, resolving the collaborating beans by inspecting the contents of the BeanFactory.

Now there are annotations that can be used to indicate fields that are to be auto-wired. Furthermore, auto-detection of annotated components in the classpath is also supported now. When these capabilities are combined, the amount of configuration and dependency mapping in the Spring configuration files is reduced drastically.

According to the Spring development team, the core theme of Spring 2.5 that was released in October 2007 is to provide comprehensive support for configuration annotations in application components. Annotation support was first announced in Spring 2.0, and has been significantly enhanced in Spring 2.5. It introduces support for a complete set of configuration annotations.

I’ll briefly discuss the annotation-driven configuration and auto-detection support in Spring 2.5 with the help of a simple tutorial.


What you need before you start

You need the following software to try out the tutorial.

Java 5.0

Spring Framework 2.5

You also need the following jars in your classpath. These are available with the Spring distribution.

  • spring.jar
  • asm-2.2.3.jar
  • asm-commons-2.2.3.jar
  • aspectjweaver.jar
  • aspectjrt.jar
  • hsqldb.jar
  • commons-logging.jar
  • log4j-1.2.14.jar
  • junit-4.4.jar
  • spring-test.jar
  • common-annotations.jar(This is not required if Java 6.0 or later is used)

Adding the classes and interfaces for the example

The example is just a simple service that returns a different message when an employee is hired or fired.

Let me start with the EmployeeService interface.


package emptest;
public interface EmployeeService {
	String hire(String name);
        String fire(String name);
}

package emptest; public interface EmployeeService { String hire(String name); String fire(String name); }

Here is a simple class that implements this interface.

@Service
public class EmployeeServiceImpl implements EmployeeService {
	@Autowired
	private EmployeeDao employeeDao;

	public String hire(String name) {
		String message = employeeDao.getMessage("Hire");
		return name + ", " + message;
	}

	public String fire(String name) {
		String message = employeeDao.getMessage("Fire");
		return name + ", " + message;
	}

	public void setEmployeeDao(EmployeeDao employeeDao) {
		this.employeeDao = employeeDao;
	}
}

Stereotype Annotations

Classes marked with stereotype annotations are candidates for auto-detection by Spring when using annotation-based configuration and classpath scanning. The  Component annotation is the main stereotype that indicates that an annotated class is a “component”. The @Service stereotype annotation used to decorate the EmployeeServiceImpl class is a specialized form of the @Component annotation. It is appropriate to annotate the service-layer classes with @Service to facilitate processing by tools or anticipating any future service-specific capabilities that may be added to this annotation. The @Repository annotation is yet another stereotype that was introduced in Spring 2.0 itself.

This annotation is used to indicate that a class functions as a repository (the EmployeeDAOImpl below demonstrates the use) and needs to have exception translation applied transparently on it. The benefit of exception translation is that the service layer only has to deal with exceptions from Spring’s DataAccessException hierarchy, even when using plain JPA in the DAO classes.

@autowired

Another annotation used in EmployeeServiceImpl is @autowired . This is used to autowire the dependency of the EmployeeServiceImpl on the EmployeeDao . Here is the EmployeeDao interface.

public interface EmployeeDao {
    String getMessage(String messageKey);
}

The implementing class EmployeeDaoImpl uses the @Repository annotation.

@Repository
public class EmployeeDaoImpl implements EmployeeDao {

	private SimpleJdbcTemplate jdbcTemplate;

	public String getMessage(String messageKey) {
		return jdbcTemplate.queryForObject(
				"select message from messages where messagekey = ?",
				String.class, messageKey);
	}

	@Autowired
	public void createTemplate(DataSource dataSource) {
		this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
	}
}

Here again, the DataSource implementation is autowired to the argument taken by the method that creates the SimpleJdbcTemplate object.

Simplified Configuration

The components discovered by classpath scanning are turned into Spring bean definitions, not requiring explicit configuration for each such bean. So the Spring configuration xml file is very simple.

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/context
           
" title="http://www.springframework.org/schema/context/spring-context-2.5.xsd">
">http://www.springframework.org/schema/context/spring-context-2.5.xsd">
	<context:annotation-config />
	<context:component-scan base-package="emptest" />
	<aop:aspectj-autoproxy />

	<context:property-placeholder location="classpath:jdbc.properties" />

	<bean id="dmdataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>

</beans>

Now let me explain the new configurations in the above Spring context file. The element is used to automatically register all of Spring’s standard post-processors for annotation-based configuration. The annotation> element is used to enable autodetection of the stereotyped classes in the package emptest . Since the  AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor are both included implicitly when using the component-scan element, the

element can be omitted. The properties for the data source are taken from the jdbc.properties file in the classpath. The property placeholders are configured with the element.

The element is used to enable @AspectJ support in Spring.

@Aspect

The @Aspect annotation on a class marks it as an aspect along with @Pointcut definitions and

advice (@Before, @After, @Around) as demonstrated in the TraceLogger class defintion below. The

PointCut is applied for all methods in the EmployeeServiceImpl class. The @Before annotation

indicates that the log() method in the TraceLogger is to be invoked by Spring AOP prior to

calling any method in EmployeeServiceImpl.

@Component
@Aspect
public class TraceLogger {
	private static final Logger LOG = Logger.getLogger(TraceLogger.class);

	@Pointcut("execution(* emptest.EmployeeServiceImpl.*(..))")
	public void empTrace() {
	}

	@Before("empTrace()")
	public void log(JoinPoint joinPoint) {
		LOG.info("Before calling " + joinPoint.getSignature().getName()
				+ " with argument " + joinPoint.getArgs()[0]);
	}

}

Since there is no definition provided for TraceLogger in the Spring context file, it is marked for auto-detection from the classpath using the @Component annotation.


@Qualifier and @Resource

Suppose there is one more DataSource configuration in the spring context file as follows.

<bean id="jndidataSource"
	class="org.springframework.jndi.JndiObjectFactoryBean">
		<property name="jndiName" value="jdbc/test" />
</bean>

Since auto-detection is enabled, auto-wiring will fail since both data source beans are equally eligible candidates for wiring. It is possible to achieve by-name auto-wiring by providing a bean name within the @Qualifier annotation as follows. The below method injects the DataSource implementation by specifying the name “dmdataSource”.

@Autowired
public void createTemplate(@Qualifier("dmdataSource") DataSource dataSource) {
 	this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
}


JSR-250 Annotations

Spring also provides support for Java EE 5 Common Annotations (JSR-250). The supported annotations are @Resource, @PostConstruct and @PreDestroy. The @Resource annotation is also supported by Spring for autowiring as shown in the below code, the bean name to be autowired is passed.

@Resource(name = "dmdataSource")
public void createTemplate(DataSource dataSource) {
this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
}

The JSR-250 lifecycle annotations @PostConstruct and @PreDestroy can be used to specify initialization callbacks and destruction callbacks respectively. To demonstrate the use of these, I am adding the following code to the EmployeeDaoImpl class.

@PostConstruct
public void initialize() {
	jdbcTemplate.update("create table messages (messagekey varchar(20), message 

varchar(100))");
	jdbcTemplate.update("insert into messages (messagekey, message) values ('Hire', Congrats! 

You are hired')");
	jdbcTemplate.update("insert into messages (messagekey, message) values ('Fire', 'Sorry! 

You are fired')");
}

@PreDestroy
public void remove() {
	jdbcTemplate.update("drop table messages");
}


Unit Testing

Before testing the service implementation, I provided the database configuration details in the jdbc.properties file as follows.

jdbc.driver=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:mem:blog
jdbc.username=sa
jdbc.password=

Here is the class I wrote for unit testing.

public class EmployeeServiceImplTests extends
		AbstractDependencyInjectionSpringContextTests {
	@Autowired
	private EmployeeService employeeService;

	@Override
	protected String[] getConfigLocations() {
		return new String[] { "context.xml" };
	}

	public void testHire() {
		String name = "Tom";
		String message = employeeService.hire(name);
		assertEquals(name + ", " + "Congrats! You are hired", message);
	}

	public void testGermanWelcome() {
		String name = "Jim";
		String message = employeeService.fire(name);
		assertEquals(name + ", " + "Sorry! You are fired", message);
	}

	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}
}


Resources

You can download the source code for this tutorial

href=”http://weblogs.java.net/blog/seemarich/archive/springannotations/SpringAnnotationsTestApp.z

ip”>here.

The inputs from the following sources were very helpful in writing this tutorial.

Rod Johnson’s

article on Spring 2.5

Spring 2.5

Documentation


Summary

I hope this discussion has opened up the possibilities offered by the annotation-based configuration capabilities in Spring 2.5. The tutorial does not include the annotations such as @Transactional, @Required and @PersistenceContext / @PersistenceUnit. These were introduced as earlier as Spring 2.0 itself.

The @Transactional annotation can be used to configure transactional setting for the public methods of a class or interface. The transactional behavior of the class annotated with @Transactional can be easily enabled with the element in the xml configuration file.

The @Required annotation is used to specify that the value of a bean property is required to be dependency injected. That means, an error is caused if a value is not specified for that property.

JPA integration is supported by Spring with the @PersistenceContext and @PersistenceUnit annotations for injecting the EntityManager and EntityManagerFactory respectively.

‘Six’ best web frameworks in Java

web application framework is a software framework that is designed to support the development of dynamic websites, Web applications and Web services. The framework aims to alleviate the overhead associated with common activities used in Web development. Here is the list of SIX best web frameworks which we are using in Java. Each one has its own advantages.

1. Java Server Faces – JSF

  • From Sun Microsystems
  • Based on Component Centric approach
  • Best Feature : The most using web framework. Because of its component architecture, the developer doesn’t need to mess with writing HTML, JavaScript etc to get rich “AJAX” type of functionality. It also takes care of state and event management. It has very less configuration too.

JavaServer Faces (JSF) is a new standard Java framework for building Web applications. It simplifies development by providing a component-centric approach to developing Java Web user interfaces. JavaServer Faces also appeals to a diverse audience of Java/Web developers. “Corporate developers” and Web designers will find that JSF development can be as simple as dragging and dropping user interface (UI) components onto a page, while “systems developers” will find that the rich and robust JSF API offers them unsurpassed power and programming flexibility. JSF also ensures that applications are well designed with greater maintainability by integrating the well established Model-View-Controller (MVC) design pattern into it’s architecture. Finally, since JSF is a Java standard developed through Java Community Process (JCP), development tools vendors are fully empowered to provide easy to use, visual, and productive develop environments for JavaServer Faces.

2. GWT

  • From Google
  • Based on Widgets
  • Best Feature : Speed development. Easy to develop good, neat and “Browser independent” Ajax applications. Give more stress to pure browser independent ;) .

Google Web Toolkit (GWT) is an open source Java software development framework that makes writing AJAX applications like Google Maps and Gmail easy for developers who don’t speak browser quirks as a second language. Writing dynamic web applications today is a tedious and error-prone process; you spend 90% of your time working around subtle incompatibilities between web browsers and platforms, and JavaScript’s lack of modularity makes sharing, testing, and reusing AJAX components difficult and fragile.GWT lets you avoid many of these headaches while offering your users the same dynamic, standards-compliant experience. You write your front end in the Java programming language, and the GWT compiler converts your Java classes to browser-compliant JavaScript and HTML.Project Home and More features

3. Stripes

  • From Mc4j
  • Based on MVC architecture
  • Best Feature: No Configurations ) . Annotation based programming makes coding more interesting and easy.

Stripes is a presentation framework for building web applications using the latest Java technologies. The main driver behind Stripes is that web application development in Java is just too much work! It seems like every existing framework requires gobs of configuration.Project Home and more features

4. Spring MVC

  • From SpringSource
  • Based on MVC architecture
  • Best Feature : Speed development. Now so many Annotations are also included (v2.5). Its from SpringSource and have a good support too. Being a person who likes and works with Spring framework.. I really encouraged by their good and really fast support.

Spring Web MVC is the own web framework of Spring Framework.The Spring MVC Framework’s architecture and design are in such a way that every piece of logic and functionality is highly configurable. Also Spring can integrate effortlessly with other popular Web Frameworks like StrutsWebWorkJava Server Faces and Tapestry. It means that you can even instruct Spring to use any one of the Web Frameworks. More than that Spring is not tightly coupled with Servlets or Jsp to render the View to the Clients. Integration with other View technologies likeVelocityFreemarkerExcel or Pdf is also possible

5. Struts2

  • From Apache
  • Based on MVC architecture
  • Best Feature : No more ActionForms! Use any JavaBean to capture form input or put properties directly on an Action class. Use both binary and String properties! and its enhanced and rich tags

Apache Struts 2 is an elegant, extensible framework for creating enterprise-ready Java web applications. The framework is designed to streamline the full development cycle, from building, to deploying, to maintaining applications over time.Project Home and More Features

6. Wicket

  • From Apache
  • Based on Component Centric approach
  • Best Feature : Swing-like OO Component Model. This feature separates Wicket from all other frameworks

With proper mark-up/logic separation, a POJO data model, and a refreshing lack of XML, Apache Wicket makes developing web-apps simple and enjoyable again. Swap the boilerplate, complex debugging and brittle code for powerful, reusable components written with plain Java and HTML.Project Home and More Features here…

Please put your Suggestions and Ratings here and the frameworks which you are used and known as great ones. That will be more helpful to all of us to get the real idea. As we all know the selection is entirely related with the requirement, learning time and the using situation, this post is gives you an idea about the frameworks using nowadays. Its not at all easy to “rate” the Java frameworks and here I am putting this as per my knowledge and the current trends only. I expect your positive and negative suggestions through valuable comments. All the SIX frameworks noted here are excellent ones and do NOT consider the order as a RANK given to them.

Google unveils 1Gbps internet for US$70/mth

Ultra-Fast 1 Gigabit-Per-Second Google Fiber Internet

Tech giant Google Inc. seeks to diversify further from its original business of internet searching as it launched the ultra-fast 1 gigabit-per-second Google Fiber Internet and Fiber TV service in Kansas City Thursday, promising an access speed of more than 100 times faster than the average internet today. Google says it will cost US$70 a month or US$120 a month bundled with cable TV.

Image

High-speed 1Gbps internet finally available to general consumers?”Gigabit speeds will get rid of these pesky, archaic problems such as loading and waiting, and will open up new possibilities for the Web,” said Google’s Milo Medin, Vice President for Access Services. He added that one could imagine “instantaneous sharing, truly global education, medical appointments with 3D imaging, or even new industries that we haven’t even dreamed of” on Google’s fiber network.

Kansas City has long been a market testing hub for major tech companies prior to launching their services nationwide. The project to turn this Midwestern city of about 600,000 into a hub of hyper-fast Internet – called Google Fiber – is expected to yield tangible benefits for the local economy. “We will make Kansas City a place where bandwidth flows like water,” said Medin.

Google’s business would directly benefit from a faster Web, as it would encourage people to use more of Google’s products, such as YouTube and its videoconferencing service Google Hangouts. “The [tech] developers I’ve talked to, they’re ecstatic about this,” said Ryan Weber, president of KCnext, a nonprofit that advocates for the Kansas City region’s technology sector. “We’ve gone months waiting to see what this product was going to look like, so there’s been a lot of eagerness in the community.”

Image
Residents of Kansas city? You’re in luck

For US$70 a month, Google Fiber offers an Internet hookup 100 times faster than the average ISP today. It’s speedy enough to download an HD movie in a few seconds and it’s the type of network often called “future proof,” because it’s limited more by the computers sending information than by network speeds. The internet speed is there, but you will need a more powerful computer.

A free plan is also offered, but limits you to 5 Mbps download and 1 Mbps upload speeds, and requires the US$300 construction fee. The free service is guaranteed for at least seven years. That might be good news, just imagine in future we only need to pay the construction fee, and get to use free internet for 7 years.

According to Google, the connection uploads is just as fast as its downloads, which is both rare and essential for companies or individuals that work with large amounts of data. Telemedicine, the practice of doctors treating patients remotely over an Internet connection, is one such area, and the Google Fiber project could potentially turn Kansas City into a center for that industry. Telemedicine is considered one potential way to greatly reduce the cost of medical treatment.

Image

How soon will gigabit internet spread to the world?

Kansas City beat out more than 1,100 other cities to win the Google project. The company said the enthusiasm of residents won it over. Fast Internet speeds are potentially so important for the economic future that residents of another city, Leverett in Massachusetts, voted in June to finance a similar project, even though it will raise property taxes there by approximately 6 percent.

The Kansas City project will also highlight the fact that average Internet speeds in the U.S. lag far behind those in European and Asian cities. The U.S. ranks 13th in average network speed according to Akamai’s “State of the Internet” report, behind South Korea, Hong Kong, Latvia, Romania, Denmark, and others.

“Access is the next frontier that needs to be opened,” Google Chief Financial Officer Patrick Pichette said. “We’re going to do it profitably. That is our plan. We are at a crossroad,” he added, noting that Internet speeds had leveled out for broadband since around 2000. “We at Google we believe there is no need to wait.”

Image
New major breakthrough since broadband internet in 2000?

The currently market is dominated by Time Warner Cable Inc, which charges US$99.95 a month for its fastest Internet service. Even then, Google Fiber would be 20 times faster. Time Warner spokesman Justin Venech said the company had a “robust and adaptable network” and welcomed the competition.

Residents near Kansas city can sign up Google Fiber at http://fiber.google.com

SOURCE :  http://www.reuters.com/

Introduction to Session Management

Session tracking is the process of maintaining information, or state, about Web site visitors as they move from page to page. It requires some work on the part of the Web developer since there’s no built-in mechanism for it. The connection from a browser to a Web server occurs over the stateless Hypertext Transfer Protocol (HTTP).

There are a number of ways to handle session tracking, but our focus is on the easy-to-use yet powerful HttpSession interface provided by the Java Servlet specification. Before we get into the HttpSession interface, let’s look at some other ways of maintaining state.

Session-Tracking Techniques
At one time Web developers used Web site visitors’ IP addresses to track the sessions. This approach was inflexible and had many flaws. The main problem was that proxy servers eliminated the use of individual IP addresses. Users no longer had unique addresses, so this technique couldn’t work properly. Another way of handling session tracking is the use of the HTML hidden field:

<INPUT TYPE=”hidden” NAME=”user”VALUE=”Jennifer”>

This technique required server-side scripting that would dynamically generate the HTML code that contained the “user” field. Server-side code was also required to read the field and match it to information about this user on the server.

Another session-tracking technique is URL rewriting. In this approach, identification field(s) are appended to the end of each URL for a Web site. The following HTML code demonstrates this method:

<A HREF=”/orderform.htm?user=Jennifer”>Order Now!</A>

This approach is similar to hidden fields. The difference is that hidden fields can only be used in a form.

A common way of session tracking is the use of cookies. A cookie is information that’s stored as a name/value pair and transmitted from the server to the browser. Cookies containing unique user information can be used to tie specific visitors to information about them on the server. The Java Servlet specification provides a simple cookie API that allows you to write and retrieve cookies. The complete API can be found on Sun’s Java Web site, http://java.sun.com. The following code shows how to create a new cookie:

Cookie user = new Cookie(“user”,”Jennifer”);
user.setMaxAge(3600);
response.addCookie(user);

This code creates a cookie with a name of “user” and a value of “Jennifer”. The cookie’s expiration date is set with the setMaxAge() method to 3,600 seconds from the time the browser receives the cookie. The following code demonstrates how you would retrieve the value for a specific cookie:

String user = “”;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals(“user”)) user =
cookies[i].getValue();
}
}

In this code, an array of cookies is retrieved from the HttpServletRequest object using the getCookies() method. The array is walked through until a cookie with the name of “user” is returned by the getName() method. Once the cookie is found, the getValue() method is called to retrieve the value of the cookie.

The use of cookies provides a flexible and easy option for handling session tracking; however, it does present some problems. The information in the cookie is stored on the client’s browser in a text file that can be easily read and manipulated, and this information is transmitted unsecured across the Internet. But the main problem is that they can be disabled through a setting in the Web browser. Web sites that rely on cookies for session tracking will be unable to track users who have disabled cookies.

Sessions in Java
The session management techniques we have looked at so far all have a common security issue: they transmit data in plain text. A powerful session-tracking solution is needed that’s more secure and flexible. This is where the Java HttpSession API comes in. The HttpSession API provides a simple mechanism for storing information about individual users on the application server. The API provides access to a session object that can be used to store other objects. The ability to tie objects to a particular user is important when working in an object-oriented environment. It allows you to quickly and efficiently save and retrieve JavaBeans that you may be using to identify your site’s visitors, to hold product information for display on your online store, or to track products that potential customers have placed in their shopping carts.

A session object is created on the application server, usually in a Java servlet or a JavaServer Page. The object is stored on the application server and a unique identifier called a session ID is assigned to it. The session object and session ID are handled by a session manager on the application server. Figure 1 illustrates this relationship. Each session ID assigned by the application server has zero or more key/value pairs tied to it. The values are objects that you place in the session. Assign each of those objects a name, and each name must have an object with it because a null is not allowed.

For this session-tracking technique to work, the session ID must be sent to the client’s computer. A cookie is used to store the session ID on the Web site visitor’s computer. This is automatically handled by the application server. Simply create the session object and begin using it. The application server will, by default, create the session ID and store it in a cookie. The browser will send the cookie back to the server every time a page is requested. The application server, via the server’s session manager, will match the session ID from the cookie to a session object. The session object is then placed in the HttpServletRequest object and you retrieve it with the getSession() method.

CIO, CTO & Developer Resources

As we discussed earlier, some Web site visitors will have cookies disabled in their browsers. To get around this problem and continue using sessions, use URL rewriting in your code. URL rewriting appends the session ID to the URL for every page that’s requested. The only problem here is that you must rewrite every link in your HTML code as well as those from servlet to servlet, or servlet to JSP.

The procedure for URL rewriting is quite simple and requires only the use of two methods found in the HttpServletResponse interface. These two methods, encodeURL() and encodeRedirectURL(), are used to append the session ID to the URL. This allows the server to track users as they move through your Web pages, but it requires that every URL be rewritten. The string returned by the methods will have the session ID appended to it only if the server determines that it’s required. If the user’s browser supports cookies, the returned URL will not be altered. Also, the returned URL won’t be altered if the application server is configured to not use URL rewriting. The format of the altered URL will vary based on different application server implementations; however, the common format will be the addition of a parameter, such as “sessionID=uniqueIDnumber”. The parameter name (in this case “sessionID”) is usually controlled through a configuration setting on the server. The value of the parameter (“uniqueIDnumber” in this example) is the unique session ID assigned by the server’s session manager and is a long series of letters and numbers. The following line of HTML code from a JSP creates a link to another JSP:

<A HREF=”/products/product.jsp”>Product Listing</A>

Clicking on this link would send the user to the product.jsp page. Using URL rewriting, the same code would be written as follows:

<A HREF=”<%= response.encodeURL(“/products/product.jsp”)
%>”>Product Listing</A>

The returned string from the encodeURL() method would contain the session ID. On a Tomcat 3.2 application server, the result of this line of code would be:

<A HREF=”http://www.yourservername.com/products/
product.jsp;$sessionid$xxxx”>Product Listing</A>

The xxxx would actually be a unique session ID generated by the server. The other method you can use for rewriting URLs is the encodeRedirectURL(). It’s used only in a servlet or JSP that calls the sendRedirect() method of the HttpServlet-Response interface. The following code is a standard redirection statement:

response.sendRedirect(“http://www.yourservername.com/
products/sale.jsp”);

Using URL rewriting, the code would be:

response.sendRedirect(response.encodeRedirectURL(
http://www.yourservername.com/products/sale.jsp&#8221;));

The application server handles the encodeRedirectURL() method a little differently than the encodeURL() method; however, each method produces the same result.

You should now have a good understanding of how the session ID is tracked and matched to a session object on the server. The first step in using the session object is creating it. The method getSession() is used to create a new session object and to retrieve an already existing one. The getSession() method is passed a Boolean flag of true or false. A false parameter indicates that you want to retrieve a session object that already exists. A true parameter lets the session manager know that a session object needs to be created if one does not already exist. The following line of code demonstrates the use of getSession():

HttpSession session = request.getSession(true);

The getSession() method will return the session object. A new session object is created if one does not already exist. The server uses the session ID to find the session object. If a session ID is not found in a cookie or the URL, a new session object is created. You would probably use only the getSession() method with a true parameter at one point in your Web application. This would be the starting point of your site, possibly after the visitor has successfully logged in. Other servlets in your application should use the getSession(false) method. This will return a current session object or null. It does not generate a new session if one doesn’t already exist.

A number of methods are defined in the Java Servlet specification. (A complete API can be found on http://java.sun.com.) The methods you’ll use most often and the ones we’ll focus on are:

 

  • setAttribute(String name, Object value): Binds an object to this session using the name specified. Returns nothing (void).
  • getAttribute(String name): Returns the object bound with the specified name in this session, or null if no object is bound under this name.
  • removeAttribute(String name): Removes the object bound with the specified name from this session. Returns nothing (void).
  • invalidate(): Invalidates this session and unbinds any objects bound to it. Returns nothing (void).
  • isNew(): Returns a Boolean with a value of true if the client does not yet know about the session or if the client chooses not to join the session.For an example in using sessions, we’ll look at session management code that could be used for an online banking application that will allow customers to view their account information. The design of the application will follow the Model-View-Controller (MVC) architecture. The model, or data and business logic, will be represented by JavaBeans; the view will be through JavaServer Pages; and the control of the application will be handled by servlets. The ideas in these examples can easily be implemented in other types of Web applications.

    An online banking application should have an HTML login page where the customer can enter a login name and password in a form. The form will submit (or post) the name and password to a login servlet. The first thing the servlet needs to do is verify the username and password. To stick with the topic at hand (sessions), we’ll look only at the code needed to handle the session. After the customer has been verified, a Customer JavaBean can be created. The Customer bean will contain the basic information about this visitor and will be stored in the session. We want to create a new session object, but we also want to invalidate a session that may already exist. To do this, we need to retrieve the existing object (or create a new one) and check if it’s a new session using the isNew() method. If it’s not a new session object, we need to invalidate it using the invalidate() method. In the servlet, we can accomplish this with the following code:

    HttpSession session = request.getSession (true);
    if (session.isNew() == false) {
    session.invalidate();
    session = request.getSession(true);
    }

    The first line of code generates a new session object, or retrieves an existing one. The second line sees if the session is new by checking the value from isNew(). A true tells you the session was just created; a false means this user already had a session and you need to invalidate it. One possible reason the user would have an old session is that he or she has two accounts and logged in on one, then tried to log in on the other.

    You can now add the Customer JavaBean to the session for future use. The process of placing an object into the session object is known asbinding. The Customer object can be bound to the session using the setAttribute() method as follows:

    session.setAttribute(“CustomerBean”, Customer);

    Since we’re working on a bank’s Web site, security is a priority. To be secure, every JSP and servlet needs to verify that this user is an authorized customer before displaying any information. To accomplish this, each servlet should contain code that looks in the session for a Customer object and sends any customers who do not have this object to a login page. The following code handles this:

    Customer customerBean = (Customer)
    session.getAttribute(‘CustomerBean’);
    if (customerBean == null) {
    response.sendRedirect
    (“https://www.yourservername.com/login.htm&#8221;);
    return;
    }

    The customer will have a valid Customer JavaBean in the session if he or she logged in properly. A getAttribute() on a name that does not exist in the session will always return null. Visitors with a null value need to log in, so we redirect them to a login page. This code should be placed at the top of the JSPs to prevent unauthorized use of the site. The code should also be placed in the servlets. Remember that the JSP creates the session variable for you, and in a servlet you must create it yourself. Keep in mind that this is just one way of handling security for a Web site. Some Web application servers will handle authentication and authorization for you. This example is just a simple demonstration on session management. Your Web application may require more advanced security measures.

    You may have noticed that the object returned by the getAttribute() method is cast into a Customer object. This is necessary for any object bound to the session. The object is stored in the session as an Object type. To use the object in your code, you must convert it (or cast it) back to the type of object it is.

    As customers move through your site, they may wish to retrieve various pieces of information about their accounts. For example, they may be able to view their checking account balance by clicking on a menu option. Following the MVC architecture, the link would send them to a servlet that would verify who they are and then create a CheckingAccount JavaBean. This object would then be stored in the session using the setAttribute() method, then the servlet would send the customer to a JSP that uses the CheckingAccount JavaBean to display the information about the customer’s account.

    There may be times when you want to store something in the session other than a JavaBean, such as a text string or a number. You need to remember that you can only bind objects to the session. Text may be stored as a String object. You can put a number in the session as an Integer object. The following code demonstrates how to save a line of text and a number in the session:

    session.setAttribute(“text”,”A line of text.”);
    session.setAttribute(“number”, new Integer(10750));

    Remember to cast the objects when they are retrieved:

    String myText = (String) session.getAttribute(“text”);
    int myNumber = ((Integer) session.getAttribute
    (‘number’)).intValue();

    Because the session is so easy to use, you may overuse it. Simple messages from a servlet to a JSP can be placed in the session as String objects, but this is not the most efficient way. Soon you’ll find that your session is loaded with messages, and most of them are no longer needed. If you find that you’re passing simple strings back and forth in the session, perhaps you should consider wrapping up those messages in a special JavaBean. This would keep the session more organized. The session objects for each user of a Web site are stored in memory on the server. Throwing unnecessary information into the session reduces the server’s memory resources. Store only essential information in the session and use the removeAttribute() method to clean out objects after you’re finished with them.

    The use of the session will not only make it easier for you to program a site, but it should also help make the Web visit better for the user. The use of the beans and the session allows you to write JSPs that are customized for each user. For our bank scenario, we could use the information in the Customer bean to create personalized pages for each visitor. We can also use the bean to prepopulate forms for the customer. For example, you could use a JavaBean to store the results from a form that a visitor fills out to request information about services offered. If the user forgot to fill in a required field, you could use the JavaBean to store error messages from a servlet and then display them in the JSP. You could also populate the fields that the visitor just filled in instead of making the visitor fill out the form again.

    The session is not intended to be used as a persistent place to store information about a visitor. Each visitor will be assigned a new session every time he or she logs in. A back-end database will be needed if you want to store information about individual users. The session should just be used to track the user during one visit to your site. In cases where you have a large Web site and are running multiple, redundant application servers, you’ll need an application server that can handle sessions across servers. This is usually handled by placing session information into a database instead of local memory so each application server can access the information. And many of the commercial application servers will be able to do this for you.

    Conclusion
    The use of session tracking is an important design issue because of the complexity of today’s Web sites. As Java developers, we have access to a powerful and robust session manager through the use of the HttpSession API. The session examples that we went over in this article cover the main capabilities of the session API. Learning all of Java’s session management features will make your job as a Web developer easier and help you create a better experience for your Web site visitors.

Describing the Life Cycle of Servlet

Servlet Life Cycle

The lifecycle of a Servlet involves creating an instance of the Servlet, associating the Servlet with initialization information, dispatching request to the servlet instance and finally destroying the servlet instance. The lifecycle of a servlet begins when it is loaded into Application Server memory and ends when the servlet is terminated or reloaded.

Basically There are four stages in Servlet life Cycle

 

  1. Loading and Instantiation
  2. Initialization
  3. Servicing the Request
  4. Destroying the Servlet

 

Process Diagram of The Servlet Life-cycle

lyf.gif

Loading a Servlet: The first stage of the Servlet life-cycle involves loading and initializing the servlet by container. When ever the web container is started, it loads and initializes the Servlet. the web container may delay this untill the web container determines which servlet is needed to service a request. The Servlet Container loads the servlet during startup or when the first request made. The Loading of servlet depends on <load-on-startup> attribute in web.xml file. If the attribute <load-on-startup> has the positive values then the servlet is load with loading of the container otherwise it will load when the first request comes for service. After loading the servlet, the container creates the instance of the servlet.

Servlet Initializing: After creating the instances, the servlet container calls the init() method and pass the servlet initialization parameters to the init() method. The init() method must be called by the servlet container before the servlet can service any request. The initialization parameters persist until the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet. The Servlet will be available for service if its loaded successfully otherwise the servlet container unloads the servletServlet’s can be dynamically loaded and instantiated when their services are first requested, the Web server can be configured so that specific servlets are loaded and instantiated when the Web server initializes. In either case, the init method of the servlet performs any necessary servlet initialization, and is guaranteed to be called once for each servlet instance, before any requests to the servlet are handled. An example of a task which may be performed in the init method is the loading of default data parameters or database connections.

The most common form of the init method of the servlet accepts a ServletConfig object parameter. This interface object allows the servlet to access name/value pairs of initialization parameters that are specific to that servlet. The ServletConfig object also gives us access to the SevletContext object that describes information about our servlet environment. Each of these objects will be discussed in more detail in the servlet examples sections.

Request Handling: After completing the initialization process, the servlet will be available for service. Servlet creates separate thread for each request. The servlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost() for handling the request and sends response to the client using the method of the response object. Application Server – Express receives a client request. The servlet engine creates a request object and a response object. The servlet engine invokes the servlet service() method, passing the request and response objects.The service() method gets information about the request from the request object, processes the request, and uses methods of the response object to create the client response. The service method can invoke other methods to process the request, such as doGet(), doPost(), or methods you write.

request.gif

doPost: Invoked whenever an HTTP POST request is issued through an HTML form. The parameters associated with the POST request are communicated from the browser to the server as a separate HTTP request. The doPost method should be used whenever modifications on the server will take place.

doGet: Invoked whenever an HTTP GET method from a URL request is issued, or an HTML form. An HTTP GET method is the default when a URL is specified in a Web browser. In contrast to the doPost method, doGet should 
be used when no modifications will be made on the server, or when the parameters are not sensitive data. The parameters associated with a GET request are appended to the end of the URL, and are passed into the 
QueryString property of the HttpServletRequest

Destroying the Servlet: If the Servlet is no longer needed for servicing any request, the servlet container calls the destroy() method. like init() method it is also called only once throughout the life cycle of the servlet. The servlet engine stops a servlet by invoking the servlet’s destroy() method. Typically, a servlet’s destroy() method is invoked when the servlet engine is stopping a Web application which contains the servlet. The destroy() method runs only one time during the lifetime of the servlet and signals the end of the servlet.After a servlet’s destroy() method is invoked, the servlet engine unloads the servlet, and the Java virtual machine eventually performs garbage collection on the memory resources associated with the servlet.

Developing the Servlet application: Here we are going to develop a simple Servlet application Of servlet lifecycle. This application includes the following files:

Home.html: First we create a html file 

<html>
<head>
<title>Servlet Example</title>
</head>
<body bgcolor=“cyan”>
<form action=“LifeCycleServlet.java”><br/><br/>
<center>
<input type=“submit” value=“Invoke Life Cycle Servlet”/>
</center>
</form>
</body>
</html>

LifeCycleServlet.java: Then we create a servlet file.

package my;

import javax.servlet.*;
import javax.servlet.Servlet;

public class LifeCycleServlet implements Servlet 
{
  public void init(ServletConfig sc) 
  { config=sc;
   System.out.println(“In Init”);
  }
  public void service(ServletRequest req,ServletResponse res)throws ServletException,java.io.IOException
  {
   java.io.PrintWriter out=res.getWriter();
   out.println(“Hello from lifecycle servlet”);
   System.out.println(“in Service”);
  }
   public void destroy(){
   System.out.println(“In Destroy”);
  }
   public String getServletInfo(){return “LyfeCycleServlet”;
  }
   public ServletConfig getServletconfig(){
   return config;
  }
   private ServletConfig config;
}

web.xml: Then we create a web.xml file for mappimg the servlet file with html

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app version=“3.0″ xmlns=http://java.sun.com/xml/ns/javaee&#8221;xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd&#8221;>
<servlet>
<servlet-name>Ls</servlet-name>
<servlet-class>my.LifeCycleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Ls</servlet-name>
<url-pattern>/lifeCycleServlet</url-pattern>
</servlet-mapping>
</web-app>s

OUTPUT:

Home.html:

home.gif

Invoking Servlet:

lifecycleservlet.gif

Embed Videos In Your Web Pages Using HTML5

HTML5 video is taking the web by storm.

Not only has a very public (and contentious) debate unfolded on the web about the efficacy of presenting videos using HTML5 instead of Flash, but momentum is gathering behind the nascent web standard.

From giant video sites like YouTube to Wikipedia, everyone it seems wants to get their video out of Flash and into native web formats. With Microsoft recently announcing it will support the HTML5 video tag in the coming Internet Explorer 9, expect even more sites to abandon Flash for native video.

So, you want in on the fun? Do you want to use some HTML5 video tags on your site right now? No problem. Fasten your seat belts, as we’re about to take a tour of the wonderful world of HTML5 video.

Browser Support for HTML5

First, let’s deal with some very basic stuff, like where this will work and where it won’t. As you can see in the table below, only the latest versions of most browsers support native video playback using HTML5′s <video> tag.

 

HTML5 <video> support by browser:
Fx 3.0 Fx 3.5 IE7 IE8 IE9 Safari 3 Safari 4 Chrome 3+ Opera 10.5
· · ·

Since Firefox 3.0 and IE 7 & 8 lack any support for HTML5 video, you’ll have to come up with a fallback plan for serving video to those users. Depending on what you want to do you, could fallback first to Quicktime and then, failing that, to Flash. That’s the strategy used in Video for Everyone (note that as of v0.4, Video for everyone no longer falls back to QuickTime).

To keep things simple we’re just going to fall straight from HTML5 to Flash.

Formats, Codecs and Technicalities

The next thing you need to understand is what is actually happening when you load and play a video file in your web browser. You’re probably used to thinking of video as .mp4 or .mov files, but unfortunately it’s not that simple. The actual file formats are just containers. Think of them as a bit like a .zip file — they hold other stuff inside.

Each container holds at minimum one video track and, most likely, one audio track. When you watch a movie online, your video player (most likely Flash) decodes both the audio and video and sends the information to your screen and speakers.

Why does this matter? Well, because the process of decoding what’s inside the video container file varies. To know how to decode a movie, the player (which is your web browser in the case of HTML5 video) has to know which codec the movie was encoded with.

When it comes to web video there are two codecs to worry about: H.264 and Theora.

There’s a huge debate right now among web developersbrowser makers and just about everyone else as to which codec is right for the web. We believe that a free, open codec without patent and licensing restrictions is the best solution for the web. Sadly, neither codec exactly fulfills that dream, so for now, let’s just skip the whole argument and be practical — we’re going to use both codecs.

Why? Well, have a look at the table below, which shows which codecs work where and you’ll quickly see that there is no one-size-fits-all-browsers solution. Only Google Chrome can play both H.264 and Theora.

Codec support by browser/platform:
  Firefox Opera Chrome Safari IE 9 iPhone Android
Ogg Theora · · ·
H.264 · ·

So, you may be thinking … if HTML5 video doesn’t work in IE7 or IE8 and it means I’m going to have to encode my videos twice, then why bother at all? Well, the best answer is simple: mobile users. If you want iPhone and Android users to be able to see your video, HTML5 is the only way to do it — Flash support is coming to Android sooner or later but for now HTML5 is the only option, and we all know Flash doesn’t run on the iPhone or the iPad.

The HTML5 Code

Here’s how to actually embed your videos. First, we encode video in both .ogv and .mp4 containers. Encoding video is beyond the scope of this article, so instead we suggest you check out Mark Pilgrim’s online book Dive Into HTML5, which has a whole chapter devoted to understanding video encoding. Pilgrim’s encoding suggestions use free software to get the job done, and in the end you’ll have two files — one .mp4 and one .ogv.

Now it’s time to unleash those movies in pure HTML glory. Here’s the code:

1 <video width="560" height="340" controls>
2   <source src="path/to/myvideo.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
3 <source src="path/to/myvideo.ogv" type='video/ogg; codecs="theora, vorbis"'>
4 </video>

Yes, that’s it. What we’ve done here is use the <video> tag to specify the dimensions of our video, and to denote that we want to use the browser’s default controls. Then, within the video tag, we’ve added two<source> elements which link to our video files.

The “type” attribute of the <source> tag helps the browser understand which file it should load. It’s a bit of an ugly chunk of code that needs to specify the container format, the video codec and the audio codec.

In this case we’ve assumed standard .ogv and baseline encoded H.264 video as per Pilgrim’s tutorial. See the WHATWG wiki for more information on which video types you can specify.

And there you have it — native web video, no plugins required.

Dealing With Everyone Else

What about IE7, IE8 and older versions of just about any other browser? Well, for those users, we’ll fall back on Flash. To do that, we just use an  tag within our video tag:

1 <video width="560" height="340" controls>
2   <source src="path/to/myvideo.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'
3 <source src="path/to/myvideo.ogv" type='video/ogg; codecs="theora, vorbis"'>
4   
8 </video>

Now any browser that doesn’t understand the HTML5 video tag will just continue on its way until it hits the object tag, which it should understand (note that the order, mp4 before ogv, is important for iPad support — Apple requires that mp4 be the first video file).

Of course for this to work you need a Flash video container. JW Player is one popular example, or you can roll your own using Adobe’s tools. Also remember that we still haven’t handled the case of an older version of Firefox with no Flash plugin installed (maybe your users are surfing your tubes with an outdated Linux machine). You can always add good old text-based links to the video files as a catch-all fix for anyone who can’t, for whatever reason, see either the HTML5 or Flash versions.

Conclusion

Embedding HTML5 video isn’t significantly more difficult than using Flash, especially if you’ve been using H.264 video files in your Flash player — which is exactly what YouTube has done with its HTML5 beta.

While we’re concerned about the licensing and patent requirements of H.264, it isn’t hard to notice that if you skip Theora and make all non-H.264 fall back to Flash, you’ve still saved yourself a considerable encoding headache. In fact, that’s probably the best practical argument against Mozilla and Opera’s refusal to support H.264.

If you’d like to use some of the more advanced aspects of HTML5 video, be sure to check theSublimeVideo player, which offers very nice JavaScript-powered set of custom controls. Also be sure to have a look at Video for Everybody, which makes for more complex code but handles just about every use case you could imagine. And there’s a handy Video for Everybody WordPress plugin as well.

Desktop Phishing – Step by step tutorial

It is an advance form of phishing. Kindly read my previous post on normal phishing here before proceeding.Difference between phishing and desktop phishing is as follows.

In phishing :-

1. Attacker convinces the victim to click on the link of fake login page which resembles a genuine login page.

 

2.Victim enters his credentials in fake login page that goes to attacker.
3.Victim is then redirected to an error page or genuine website depending on attacker.
But main drawback in phishing is that victim can easily differentiate between fake and real login page by looking at the domain name. We can overcome this in desktop phishing by spoofing domain name.
In desktop phishing:-
1. Attacker sends an executable/batch file to victim and victim is supposed to double click on it. Attacker’s job is done.
2. Victim types  the domain name of orignal/genuine website and is taken to our fake login page. But the domain name remains the same as typed by victim and victim doesn’t come to know.
3. Rest of the things are same as in normal phishing.
What is Hosts File ?
The hosts file  is a text file containing domain names and IP address associated with them.
Location of hosts file in windows: C:\Windows\System32\drivers\etc\
Whenever we visit any website, say http://www.anything.com , an query is sent to  Domain Name Server(DNS) to  look up for the IP address associated with that website/domain. But before doing this the hosts file on our local computer is checked for the IP address associated to the domain name.
Suppose we make an entry in hosts file as shown. When we visit http://www.anywebsite.com , we would
be taken to this 115.125.124.50. No query for resolving IP address associated with http://www.anywebsite.com would be sent to DNS.

What is attack ?
I hope you have got an idea that how modification of this hosts file on victim’s computer can be misused. We  need to modify victim’s hosts file by adding the genuine domain name and IP address of our fake website /phishing page. Whenever victim would visit the genuine website , he would be directed to our fake login page and domain name in the URL box would remain genuine as typed by victim. Hence domain name is spoofed.
Two Steps to perform attack :-
1. Create and host phishing page on your computer.
2. Modify victim’s host file
Step 1 -:

Since the webshosting sites like 110mb.com,ripway.com etc where we usually upload our phishing page do not provide a IP that points to your website like http://www.anything.110mb.com. An IP address points to a webserver and not a website. So we need to host the phishing page on our computer using a webserver software like wamp or xampp.
Kindly read my simple  tutorial on setting up XAMPP webserver here  and this step would be clear to you.
Step 2. This  step can performed in two different ways. 

Method 1 – Send victim a zip file containing modified host file . When Zip file would be clicked, It would automatically replace victim’s orignal hosts file with modified hosts file.
Copy your hosts file and paste it anywhere . Modify it according to yourself..Edit it with any text editor and associate your public IP address with domain you wish as show.
Like in this case , when victim would visit gmail.com , he would be taken to website hosted on IP ‘xxx.xxx.xxx.xxx’.Replace it with your public IP.Compress hosts file such that when victim opens it, it automatically gets copied to default locationC:\Windows\system32\drivers\etc and victim’s hosts file get replaced by our modified hosts file.
Then you can bind this file with any exe ( using a binder or directly give it to victim. He is supposed to click it and you are done .
Method 2 – Create a batch file which would modify hosts file as per your need.
Open your notepad and type the following text
echo xxx.xxx.xxx.xxx. http://www.watever.com >> C:\windows\system32\drivers\etc\hosts
echo xxx.xxx.xxx.xxx watever.com >> C:\windows\system32\drivers\etc\hosts
Obviously replace it with your IP and website acc. to yourself.


Save file as ‘all files’ instead of txt files and name it anything.bat . Extension must be .bat 
When victim would run this file, a new entry will be made in hosts file.
You can test both the above methods to modify your own hosts file
Limitations of attack :-
1.Since our pubilc IP address is most probably dynamic that it gets changed everytime we disconnect and connect. To overcome this we need to purchase static IP from our ISP.
2. The browser may warn the victim that Digital Certificate of the website is not genuine.
Countermeasures:-
Never just blindly enter your credentials in a login page even if you yourself have typed a domain name in web browser. Check the protocol whether it is “http” or “https” . https is secure.