TestController.java

@RequestMapping(value="/Control2", method=RequestMethod.POST)
public String TestMe2(Model model)
{
  Person objPerson = new Person();
  objPerson.setName("Mugil");
  objPerson.setAddress("Sample Address");
  objPerson.setAge("27");

  model.addAttribute("objPerson", objPerson);
  return "display";
}

display.jsp

Person Name : ${objPerson.name}
Person Location : ${objPerson.location}
Person Age : ${objPerson.age}
Person Address : ${objPerson.address}
public class Person 
{
 private String Name;
 private String Location;
 private String Age;
 private String Address;

 public String getName() {
	return Name;
 }
 public void setName(String name) {
	Name = name;
 }
 public String getLocation() {
	return Location;
 }
 public void setLocation(String location) {
	Location = location;
 }

 .
 .
 .
}

How to Design Spring MVC for View Page

  1. Have a isSuccess attribute in the bean
  2. Use when and choose to decide whether to form element or form value based on the value set in the isSuccess
  3. When isSuccess is set to true the show the form Value or show the form element else display the form element
  4. When adding a new values in through the form the bean would be set to isSuccess true
  5. Next time when the page gets loaded the form values filled before the click of the submit will be displayed a s form values.

How to access the bean values where the bean has sub bean

class Student
{
 String Name;
 Address houseAddress;
 .
 .
}

For accessing values in Student bean the form elements should be

path=Name value="${student.Name}"

For accessing values in Student Address bean the form elements should be

path=Address.houseAddress value="${Student.Address.StreetName}" 

hello.java

<%@ 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>Insert title here</title>
</head>
<body>
<form name="frmTest" id="frmTest" method="post">		
	<select name="cboArea">
		<option value="Teynampet">Teynampet</option>
		<option value="TNagar">TNagar</option>
		<option value="Adyar">Adyar</option>
	</select>		
	<input type="checkbox" name="cboAgree" value="I Agree"/>I Agree		
	<input type="submit" name="btnSubmit" value="Submit"/>		
</form>
</body>
</html>

TestController.java

package com.mugil.controls;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/Control1")
public class TestController 
{	
	@RequestMapping("/Control2")		
	public String TestMe()
	{
		return "hello";
	}

	@RequestMapping(value="/Control2", method=RequestMethod.POST)
	public String TestMe2()
	{
		System.out.println("Hi there");
		return "hello";
	}

	@RequestMapping(value="/Control2", method=RequestMethod.POST, params={"cboArea=TNagar", "cboAgree"})
	public String TestMe3()
	{
		System.out.println("I am in TNagar");
		return "hello";
	}
}

Simple Controller Example
TestController.java

package com.mugil.controls;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/Control1")
public class TestController 
{	
  @RequestMapping("/Control2")	
  public String TestMe()
  {
    return "hello";
  }
}

hello.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>Insert title here</title>
</head>
<body>
   Hi Dear!
</body>
</html>

dispatcher-servlet.xml

 <mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>

HomeController.java

package com.mugil.controls;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HomeController {	
	@RequestMapping("/home")	
	public String testMethod()
	{
		return "home";
	}
}

style.css

h1
{
  color : red;
}

ServletConfig

  1. ServletConfig is one of the pre-defined interface.
  2. ServletConfig object is used for developing flexible servlets.
  3. ServletConfig objct exist one per servlet program.
  4. An object of ServletConfig created by the container during its initialization phase.
  5. An object of ServletConfig is available to the servlet during its execution, once the servlet execution is completed, automatically ServletConfig interface object will be removed by the container.
  6. An object of ServletConfig interface contains details at web.xml, of a particular servlet.
  7. The moment when we are using an object of ServletConfig, we need to configure the web.xml by writing tag under tag of web.xml.
  8. When ever compiler executes init() mehod then the ServletConfig will be created in general.
  9. An object of ServletConfig contain the data in the form of key,value pairs, here the keys represents init param names and values are its values, which are represented in the web.xml file

How to Get ServletConfig Object into Servelt
Method1

ServletConfig conf = getServletConfig();

Method2
ServletConfig object will be available in init() method of the servlet.

public void init(ServletConfig config)
{
// …………………
}

How to Retrieve Data from ServletConfig Interface Object

public String getInitParameter(“param name”);
public Enumeration getInitParameterNames();

web.xml

<web-app> 
  <servlet>
     <servlet-name>onServletConfig</servlet-name>
     <servlet-class>java4s.OnServletConfig</servlet-class> 
     <init-param>
        <param-name> n1 </param-name>
        <param-value> 100 </param-value>
     </init-param>
    .
    .
</web-app>

Test.java

ServletConfig conf=getServletConfig(); 
String s1=conf.getInitParameter("n1");
 

ServletContext
An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application.

Methods of ServletContext interface

  1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
  2. public Enumeration getInitParameterNames():Returns the names of the context’s initialization parameters.
  3. public void setAttribute(String name,Object object):sets the given object in the application scope.
  4. public Object getAttribute(String name):Returns the attribute for the specified name.
  5. public Enumeration getInitParameterNames():Returns the names of the context’s initialization parameters as an Enumeration of String objects.

web.xml

    <web-app>  
     ......  
          
      <context-param>  
        <param-name>parametername</param-name>  
        <param-value>parametervalue</param-value>  
      </context-param>  
     ......  
    </web-app>  

Test.java

  ServletContext context=getServletContext();    

  //Getting the value of the initialization parameter and printing it  
  String driverName=context.getInitParameter("parametername");  

Creating a Preconfigured MVC Project
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>
	
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>
  1. DispatcherServlet is the first servlet which gets called when you run Preconfigured MVC Project
  2. servlet-context.xml in init param of DispatcherServlet get run for other initialization of internal beans
  3. Apart from servlet-context.xml the other xml file that gets called is root-context.xml in a separate context

Test.java

package com.mugil.spring;

import java.util.Locale;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class Test
{	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String testMethod(Locale locale, Model model) 
	{	
		model.addAttribute("testMsg", "Hi There" );		
		return "home";
	}
}

home.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
	<title>Home</title>
</head>
<body>
<h1>
	${testMsg}  
</h1>
</body>
</html>

Output(http://localhost:8089/spring/)

Hi There

servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
	<annotation-driven />
	<resources mapping="/resources/**" location="/resources/" />
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

	<context:component-scan base-package="com.mugil.spring" />
</beans:beans>
  1. context:component-scan base-package defines the base location in which the controller to be found
  2. beans:property name=”prefix” defines the folder in which jsp should be found
  3. beans:property name=”suffix” defines the valid prefix
  4. Based on the return type of testMethod method the jsp page name is recognized. In our case it is home.jsp

Fibonacci(without using recursion)

public class Test
{
  public static void main(String[] args)
  {
     int a=0 , b=0 , c=1;
     System.out.println(a);
     System.out.println(b);

     for(int i=0;i<15;i++)
     {
        a=b;
        b=c;
        c=a+b;
        System.out.println(c);
     }
   }
}

Fibonacci(using recursion)

7

Reverse array without Temp Array

public static int[] reverseArrayWithoutTempArray(int[] array) 
{
    int i = 0, j = array.length - 1;
 
    for (i = 0; i < array.length / 2; i++, j--) 
    {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

Iterate random integer array and print the values greater than the current value

class Main 
{
 static void printNGE(int arr[]) 
 {
  int highestVal = 0, i, j;

  for (i = 0; i < arr.length; i++) 
  {
       if (arr[i] > highestVal) 
       {
        System.out.println(arr[i]);
        highestVal = arr[i];
       }
  }
 }

 public static void main(String args[]) 
 {
  int arr[]= {11, 13, 21, 3, 45};
  printNGE(arr);
 }
}

Inheritance program with Class and Interface.Find and print the Area and Perimeter for Rectangle,Square and Circle

  1. Interface Shape
  2. Rectangle class implements Shape
  3. Circle class extends Rectangle
interface Shape 
{
 void input();
 void area();
}

class Circle implements Shape 
{
 int r = 0;
 double pi = 3.14, ar = 0;
 
 @Override
 public void input() 
 {
  r = 5;
 }
 
 @Override
 public void area() 
 {
  ar = pi * r * r;
  System.out.println("Area of circle:" + ar);
 }
}

class Rectangle extends Circle 
{
 int l = 0, b = 0;
 double ar;

 public void input() 
 {
  super.input();
  l = 6;
  b = 4;
 }

 public void area() 
 {
  super.area();
  ar = l * b;
  System.out.println("Area of rectangle:" + ar);
 }
}

public class Demo 
{
 public static void main(String[] args) 
 {
  Rectangle obj = new Rectangle();
  obj.input();
  obj.area();
 }
}
Area of circle:78.5
Area of rectangle:24.0

Types (Hierarchy) of Java Class Loaders
Java class loaders can be broadly classified into below categories:

Bootstrap Class Loader
Bootstrap class loader loads java’s core classes like java.lang, java.util etc. These are classes that are part of java runtime environment. Bootstrap class loader is native implementation and so they may differ across different JVMs.

Extensions Class Loader
JAVA_HOME/jre/lib/ext contains jar packages that are extensions of standard core java classes. Extensions class loader loads classes from this ext folder. Using the system environment propery java.ext.dirs you can add ‘ext’ folders and jar files to be loaded using extensions class loader.

System Class Loader
Java classes that are available in the java classpath are loaded using System class loader.

Why you need class Loaders
Applications written in statically compiled programming languages, such as C and C++, are compiled into native, machine-specific instructions and saved as an executable file. The process of combining the code into an executable native code is called linking – the merging of separately compiled code with shared library code to create an executable application. This is different in dynamically compiled programming languages such as Java. In Java, the .class files generated by the Java compiler remain as-is until loaded into the Java Virtual Machine (JVM) — in other words, the linking process is performed by the JVM at runtime. Classes are loaded into the JVM on an ‘as needed’ basis. And when a loaded class depends on another class, then that class is loaded as well.

When a Java application is launched, the first class to run (or the entry point into the application) is the one with public static void method called main(). This class usually has references to other classes, and all attempts to load the referenced classes are carried out by the class loader.

java.lang.ClassLoader
The java.lang.ClassLoader is an abstract class that can be subclassed by applications that need to extend the manner in which the JVM dynamically loads classes. Constructors in java.lang.ClassLoader (and its subclasses) allow you to specify a parent when you instantiate a new class loader. If you don’t explicitly specify a parent, the virtual machine’s system class loader will be assigned as the default parent.

  1. Include directive includes the file at translation time (the phase of JSP life cycle where the JSP gets converted into the equivalent servlet) whereas the include action includes the file at runtime.
  2. If the included file is changed but not the JSP which is including it then the changes will reflect only when we use include action tag. The changes will not reflect if you are using include directive as the JSP is not changed so it will not be translated for request processing and hence the changes will not reflect.
  3. When using include action tag we can also pass the parameters to the included page by using param action tag but in case of include directive it’s not possible.
    <jsp:include page="file_name" />
     <jsp:param name="parameter_name" value="parameter_value" />
    </jsp:include>
    

JSP Include Action tag

<html>
<head>
<title>JSP include Action example</title>
</head>
<body>
<jsp:include page="display.jsp" />
</body>
</html>

JSP Include Directive

<html>
<head>
<title>JSP include Directive example</title>
</head>
<body>
<%@ include file="display.jsp" %>
</body>
</html>
Posted in JSP.

SessionId is used to keep track of request coming from the same client during a time duration.

URL rewriting
URL rewriting is a method of session tracking in which some extra data (session ID) is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session. This method is used with browsers that do not support cookies or where the user has disabled the cookies. If you need to track Session from JSP pages, then you can use tag for URL-rewriting. It automatically encodes session identifier in URL.

Cookies
A cookie is a small amount of information sent by a servlet to a Web browser. A cookie is saved by the browser and later sent back to the server in subsequent requests. A cookie has a name, a single value, expiration date and optional attributes. A cookie’s value can uniquely identify a client. Since a client can disable cookies, this is not the most secure and fool-proof way to manage the session. If Cookies are disabled then you can fallback to URL rewriting to encode Session id e.g. JSESSIOINID into the URL itself.

Hidden Form fields
Similar to URL rewriting. The server embeds new hidden fields in every dynamically generated form page for the client. When the client submits the form to the server the hidden fields identify the client.

HTTPS and SSL
Web browsers that support Secure Socket Layer communication can use SSL’s support via HTTPS for generating a unique session key as part of the encrypted conversation. Modern days online internet banking website, ticket booking websites, e-commerce retailers like Amazon and e-bay all use HTTPS to security transfer data and manage the session.