Showing posts with label JavaEE. Show all posts
Showing posts with label JavaEE. Show all posts

Write a servlet which accepts product details from html form and stores the product details into database?



Product database:
create table Product
(
pid number (4),
pname varchar2 (15),
price number (6, 2)
);

web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>DatabaServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/getdata</url-pattern>
</servlet-mapping>
</web-app>

DarabaServ.java:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class DatabaServ extends HttpServlet {
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  res.setContentType("text/html");
  PrintWriter pw = res.getWriter();
  String pid1 = req.getParameter("prodata_pid");
  String pname = req.getParameter("prodata_pname");
  String price1 = req.getParameter("prodata_price");
  int pid = Integer.parseInt(pid1);
  float price = Float.parseFloat(price1);
  try {
   DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
   Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:
    Hanuman ","
    scott ","
    tiger ");
    PreparedStatement ps = con.prepareStatement("insert into Product values (?,?,?)"); ps.setInt(1, pid); ps.setString(2, pname); ps.setFloat(3, price); int i = ps.executeUpdate(); pw.println("<h4>" + i + " ROWS INSERTED..."); con.close();
   } catch (Exception e) {
    res.sendError(503, "PROBLEM IN DATABASE...");
   }
  }
  public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
   doGet(req, res);
  }
 }


Write a servlet which accepts client request and display the client requested data on the browser?



import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class DataServ extends HttpServlet {
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  res.setContentType("text/html");
  PrintWriter pw = res.getWriter();
  String name = req.getParameter("persdata_eurn");
  String cname = req.getParameter("persdata_eurc");
  pw.println("<center><h3>HELLO..! Mr/Mrs. " + name + "</h3></center>");
  pw.println("<center><h3>Your COURSE is " + cname + "</h3></center>");
 }
 public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  doGet(req, res);
 }

web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>DataServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/getdata</url-pattern>
</servlet-mapping>
</web-app>

NOTE:
1. Whenever we are not entering the data in html form that data will be treated as empty space.
2. Query string represents the data which is passed by client to the servlet through html form. URI stands for Uniform Resource Indicator which gives the location of servlet where it is available. URL stands for Uniform Resource Locator which gives at which port number, in which server a particular JSP or servlet is running. ht represents a context path which can be either a document root or a war file.


Write a servlet which illustrate the concept of ServletContext?



web.xml:

<web-app>
<context-param>
<param-name>v1</param-name>
<param-value>10</param-value>
</context-param>
<context-param>
<param-name>v2</param-name>
<param-value>20</param-value>
</context-param>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>Serv1</servlet-class>
<init-param>
<param-name>v3</param-name>
<param-value>30</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>pqr</servlet-name>
<servlet-class>Serv2</servlet-class>
<init-param>
<param-name>v4</param-name>
<param-value>40</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/firstserv</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>pqr</servlet-name>
<url-pattern>/secondserv</url-pattern>
</servlet-mapping>
</web-app>

Serv1.java:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Serv1 extends HttpServlet {
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  res.setContentType("text/html");
  PrintWriter pw = res.getWriter();
  ServletConfig config = getServletConfig();
  ServletContext ctx = config.getServletContext();
  String val1 = ctx.getInitParameter("v1");
  String val2 = ctx.getInitParameter("v2");
  String val3 = config.getInitParameter("v3");
  String val4 = config.getInitParameter("v4");
  int sum = Integer.parseInt(val1) + Integer.parseInt(val2);
  pw.println("<h3> Value of v1 is " + val1 + "</h3>");
  pw.println("<h3> Value of v2 is " + val2 + "</h3>");
  pw.println("<h3> Value of v3 is " + val3 + "</h3>");
  pw.println("<h3> Value of v4 is " + val4 + "</h3>");
  pw.println("<h2> Sum = " + sum + "</h2>");
 }
}


Serv2.java:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class Serv2 extends HttpServlet {
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  res.setContentType("text/html");
  PrintWriter pw = res.getWriter();
  ServletContext ctx = getServletContext();
  Enumeration en = ctx.getInitParameterNames();
  while (en.hasMoreElements()) {
   Object obj = en.nextElement();
   String cpname = (String) obj;
   String cpvalue = ctx.getInitParameter(cpname);
   pw.println("</h2>" + cpvalue + " is the value of " + cpname + "</h2>");
  }
 }
}




Develop a flexible servlet that should display the data of the database irrespective driver name, table name and dsn name?



import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
public class DbServ extends HttpServlet {
 ServletConfig sc = null;
 public void init(ServletConfig sc) throws ServletException {
  super.init(sc);
  this.sc = sc;
 }
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  res.setContentType("text/html");
  PrintWriter pw = res.getWriter();
  String dname = sc.getInitParameter("dname");
  String url = sc.getInitParameter("url");
  String tab = sc.getInitParameter("tab");
  try {
   Class.forName(dname);
   Connection con = DriverManager.getConnection(url, "scott", "tiger");
   Statement st = con.createStatement();
   ResultSet rs = st.executeQuery("select * from " + tab);
   while (rs.next()) {
    pw.println("<h2>" + rs.getString(1) + "" + rs.getString(2) + "" + rs.getString(3) + "</h2>");
   }
   con.close();
  } catch (Exception e) {
   res.sendError(503, "PROBLEM IN DATABASE...");
  }
 }
}



web.xml:


<web-app>

<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>DbServ</servlet-class>
<init-param>
<param-name>dname</param-name>
<param-value>oracle.jdbc.driver.OracleDriver ()</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:Hanuman</param-value>
</init-param>
<init-param>
<param-name>tab</param-name>
<param-value>emp</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/dbdata</url-pattern>
</servlet-mapping>
</web-app>


Struts interview questions (Part-2)



21.What is DispatchAction?
The DispatchAction class is used to group related actions into one class. Using this class, you can have a method for each logical action compared than a single execute method. The DispatchAction dispatches to one of the logical actions represented by the methods. It picks a method to invoke based on an incoming request parameter. The value of the incoming parameter is the name of the method that the DispatchAction will invoke.

22.How to use DispatchAction?
To use the DispatchAction, follow these steps
· Create a class that extends DispatchAction (instead of Action)
· In a new class, add a method for every function you need to perform on the service – The method has the same signature as the execute() method of an Action class.
· Do not override execute() method – Because DispatchAction class itself provides execute() method.
· Add an entry to struts-config.xml
DispatchAction Example »

23.What is the use of ForwardAction?
The ForwardAction class is useful when you’re trying to integrate Struts into an existing application that uses Servlets to perform
business logic functions. You can use this class to take advantage of the Struts controller and its functionality, without having to rewrite the existing Servlets. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page. By using this predefined action, you don’t have to write your own Action class. You just have to set up the struts-config file properly to use ForwardAction.

24.What is IncludeAction?
The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. Use the IncludeAction class to include another resource in the response to the request being processed.

25.What is the difference between ForwardAction and IncludeAction?
The difference is that you need to use the IncludeAction only if the action is going to be included by another action or jsp.
UseForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic
processing or even another JSP page.

26.What is LookupDispatchAction?
The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to get the key and then
gets the method whose name is associated with the key into the Resource Bundle.

27.What is the use of LookupDispatchAction?
LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end, but by the Locale independent key into the resource bundle. Since the key is always the same, the LookupDispatchAction shields your application from the side effects of I18N.

28.What is difference between LookupDispatchAction and DispatchAction?
The difference between LookupDispatchAction and DispatchAction is that the actual method that gets called in LookupDispatchAction is
based on a lookup of a key value instead of specifying the method name directly.

29.What is SwitchAction?
The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module. SwitchAction is useful only if you have multiple modules in your Struts application. The SwitchAction class can be used as is, without extending.

30.What if <action> element has <forward> declaration with same name as global forward?
In this case the global forward is not used. Instead the <action> element’s <forward>takes precendence.

31.What is DynaActionForm?
A specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties (configured in configuration file), without requiring the developer to create a Java class for each type of form bean.


32.What are the steps need to use DynaActionForm?
Using a DynaActionForm instead of a custom subclass of ActionForm is relatively straightforward. You need to make changes in two places:
· In struts-config.xml: change your <form-bean> to be an org.apache.struts.action.DynaActionForm instead of some subclass of ActionForm

33.How to display validation errors on jsp page?
<html:errors/> tag displays all the errors. <html:errors/> iterates over ActionErrors request attribute.

34.What are the various Struts tag libraries?
The various Struts tag libraries are:
· HTML Tags
· Bean Tags
· Logic Tags
· Template Tags
· Nested Tags
· Tiles Tags

35.What is the use of <logic:iterate>?
<logic:iterate> repeats the nested body content of this tag over a specified collection.
<table border=1>
<logic:iterate id="customer" name="customers">
<tr>
<td><bean:write name="customer"
property="firstName"/></td>
<td><bean:write name="customer" property="lastName"/></td>
<td><bean:write name="customer" property="address"/></td>
</tr>
</logic:iterate>
</table>

36.What are differences between <bean:message> and <bean:write>
<bean:message>: is used to retrive keyed values from resource bundle. It also supports the ability to include parameters that can be
substituted for defined placeholders in the retrieved string.

<bean:message key="prompt.customer.firstname"/>
<bean:write>: is used to retrieve and print the value of the bean property. <bean:write> has no body.
<bean:write name="customer" property="firstName"/>

37.How the exceptions are handled in struts?
Exceptions in Struts are handled in two ways:
· Programmatic exception handling :
Explicit try/catch blocks in any code that can throw exception. It works well when custom value (i.e., of variable) needed
when error occurs.
· Declarative exception handling :You can either define <global-exceptions> handling tags in your struts-config.xml or define the exception handling tags within <action></action> tag. It works well when custom page needed when error occurs. This approach applies only to exceptions thrown by Actions.
<global-exceptions>
<exception key="some.key"
type="java.lang.NullPointerException"
path="/WEB-INF/errors/null.jsp"/>
</global-exceptions>
or
<exception key="some.key"
type="package.SomeException"
path="/WEB-INF/somepage.jsp"/>

38.What is difference between ActionForm and DynaActionForm?
· An ActionForm represents an HTML form that the user interacts with over one or more pages. You will provide properties to hold the state of the form with getters and setters to access them. Whereas, using DynaActionForm there is no need of providing properties to hold the state. Instead these properties and their type are declared in the struts-config.xml
· The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file
grow larger.
· The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.
· ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.
· ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.getParameter.
· DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.

39.How can we make message resources definitions file available to the Struts framework environment?
We can make message resources definitions file (properties file) available to Struts framework environment by adding this file to strutsconfig.
xml.
<message-resources
parameter="com.login.struts.ApplicationResources"/>

40.What is the life cycle of ActionForm?
The lifecycle of ActionForm invoked by the RequestProcessor is as follows:
· Retrieve or Create Form Bean associated with Action
· "Store" FormBean in appropriate scope (request or session)
· Reset the properties of the FormBean
· Populate the properties of the FormBean
· Validate the properties of the FormBean
· Pass FormBean to Action


Struts interview questions (Part-1)



1.What is MVC?
Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from business logic and data.

Model: The model contains the core of the application's functionality. The model encapsulates the state of the application.
Sometimes the only functionality it contains is state. It knows nothing about the view or controller.

View: The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.

Controller: The controller reacts to the user input. It creates and sets the model.

2.What is a framework?
A framework is made up of the set of classes which allow us to use a library in a best possible way for a specific requirement.

3.What is Struts framework?
Struts framework is an open-source framework for developing the web applications in JavaEE, based on MVC-2 architecture. It uses and extends the Java Servlet API. Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.

4.What are the components of Struts?
Struts components can be categorize into Model, View and Controller:

Model: Components like business logic /business processes and data are the part of model.
View: HTML, JSP are the view components.

Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.

5.What are the core classes of the Struts Framework?
Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design. JavaBeans components for managing application state and behavior.

Event-driven development (via listeners as in traditional GUI development).

Pages that represent MVC-style views; pages reference view roots via the JSF component tree.

6.What is ActionServlet?
ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main Controller component that handles client requests and determines which Action will process each received request. It serves as an Action factory – creating specific Action classes based on user’s request.

7.What is role of ActionServlet?
ActionServlet performs the role of Controller:

· Process user requests
· Determine what the user is trying to achieve according to the request
· Pull data from the model (if necessary) to be given to the appropriate view,
· Select the proper view to respond to the user
· Delegates most of this grunt work to Action classes
· Is responsible for initialization and clean-up of resources

8.What is the ActionForm?
ActionForm is javabean which represents the form inputs containing the request parameters from the View referencing the Action bean.

9.What are the important methods of ActionForm?
The important methods of ActionForm are : validate() & reset().

10.Describe validate() and reset() methods ?
validate() : Used to validate properties after they have been populated; Called before FormBean is handed to Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate() method. public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)

reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set.
public void reset() {}

11.What is ActionMapping?
Action mapping contains all the deployment information for a particular Action bean. This class is to determine where the results of the Action will be sent once its processing is complete.

12.How is the Action Mapping specified ?
We can specify the action mapping in the configuration file called struts-config.xml. Struts framework creates ActionMappingobject
from <ActionMapping> configuration element of struts-config.xml file

<action-mappings>
<action path="/submit" 

type="submit.SubmitAction"
name="submitForm"
input="/submit.jsp"
scope="request"
validate="true">
<forward name="success" path="/success.jsp"/>
<forward name="failure" path="/error.jsp"/>
</action>
</action-mappings>

13.What is role of Action Class?
An Action Class performs a role of an adapter between the contents of an incoming HTTP request and the corresponding business logic
that should be executed to process this request.

14.In which method of Action class the 

business logic is executed ?
In the execute() method of Action class the business logic is executed.

public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception ;
execute() method of Action class:

· Perform the processing required to deal with this request
· Update the server-side objects (Scope variables) that will be used to create the next page of the user interface
· Return an appropriate ActionForward object


15.What design patterns are used in Struts?
Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the command design pattern and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern.

Struts also implement the following J2EE design patterns.

· Service to Worker
· Dispatcher View
· Composite View (Struts Tiles)
· Front Controller
· View Helper
· Synchronizer Token

16.Can we have more than one struts config.xml file for a single Struts application?
Yes, we can have more than one struts-config.xml for a single Struts application. They can be configured as follows:

<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>
/WEB-INF/struts-config.xml,
/WEB-INF/struts-admin.xml,
/WEB-INF/struts-config-forms.xml
</param-value>
</init-param>
.....
<servlet>

17.What is the directory structure of Struts application?
The directory structure of Struts application 



18.What is the difference between session scope and request scope when saving formbean ?
when the scope is request,the values of formbean would be available for the current request.

when the scope is session,the values of formbean would be available throughout the session.

19.What are the important tags of struts-config.xml ?
The five important sections are:



20.What are the different kinds of actions in Struts?
The different kinds of actions in Struts are:

· ForwardAction
· IncludeAction
· DispatchAction
· LookupDispatchAction
· SwitchAction


Java Features in Details



1. Simple:-
Java is a simple programming language because:
a- Java technology has eliminated all the difficult and confusion oriented concepts like pointers, multiple inheritance in the java language.
b- The c,cpp syntaxes easy to understand and easy to write. Java maintains C and CPP syntax mainly hence java is simple language.
c- Java tech takes less time to compile and execute the program.


2. Object Oriented:-
Java is object oriented technology because to represent total data in the form of object. By using object reference we are calling all the methods, variables which is present in that class. The total java language is dependent on object only hence we can say java is a object oriented technology.


3. Platform Independent :-
Compile the Java program on one OS (operating system) that compiled file can execute in any OS(operating system) is called Platform Independent Nature. The java is platform independent language. The java applications allows its applications compilation one operating system that compiled (.class) files can be executed in any operating system.





4. Architectural Neutral:-

Java tech applications compiled in one Architecture (hardware----RAM, Hard Disk) and that Compiled program runs on any hardware architecture(hardware) is called Architectural Neutral.

5. Portable:-
In Java tech the applications are compiled and executed in any OS(operating system) and any Architecture(hardware) hence we can say java is a portable language.

6. Robust:-
Any technology if it is good at two main areas it is said to be ROBUST

1 Exception Handling
2 Memory Allocation

JAVA is Robust because

a. JAVA is having very good predefined Exception Handling mechanism whenever we are getting exception we are having meaning full information.
b. JAVA is having very good memory management system that is Dynamic Memory (at runtime the memory is allocated) Allocation which allocates and deallocates memory for objects at runtime.

7. Secure:-
To provide implicit security Java provide one component inside JVM called Security Manager.

To provide explicit security for the Java applications we are having very good predefined library in the form of java.Security.package.

Web security for web applications we are having JAAS(Java Authentication and Authorization Services) for distributed applications.

8. Dynamic:-
Java is dynamic technology it follows dynamic memory allocation(at runtime the memory is allocated) and dynamic loading to perform the operations.

9. Distributed:-
By using JAVA technology we are preparing standalone applications and Distributed applications.

Standalone applications are java applications it doesn’t need client server architecture. web applications are java applications it need client server architecture.

Distributed applications are the applications the project code is distributed in multiple number of jvm’s.

10. Multithreaded: -
Thread is a light weight process and a small task in large program.

If any tech allows executing single thread at a time such type of technologies is called single threaded technology.

If any technology allows creating and executing more than one thread called as Multithreaded technology called JAVA.

11. Interpretive:-
JAVA tech is both Interpretive and Completive by using Interpretator we are converting source code into byte code and the interpretator is a part of JVM.

12. High Performance:-
If any technology having features like Robust, Security, Platform Independent, Dynamic and so on then that technology is high performance.


Difference between C, C++ and Java



C language

1- The program execution starts from main method and main method is called by Operating system.

2- In the c-language the predefined support is maintained in the form of header files

Ex:- stdio.h,conio.h

3- the header files contains predefined functions.

Ex:- printf,scanf…..

4- to make available predefined support into our program we have to use #include statement.

Ex:- #include<stdio.h>

5- memory allocation: malloc
Memory deallocation: free

6- size of the data types are varied from operating system to the operating system.

16-bit int -2bytes char- 1byte
32-bit int -4bytes char – 2 bytes

7- to print some statements into the console we have to use “printf” function.

8- C is dynamic language the memory is allocated at compilation time.

C++ language

1- The program execution starts from main method called by operating system.

2- In the cpp language the predefined is maintained in the form of header files.

Ex:- iostream.h

3- The header files contains predefined functions.

Ex:- cout,cin….

4- To make available predefined support into our program we have to use

#include statement.
Ex:- #include<iostream>

5-Allocation :constructor

6- Deallocation:destructors

7- Irrespective of any os

Int -4
Char-2

8- To print the statements we have to use “cout”
Cpp is static language the memory is allocated at compilation time.

Java language

1- The program execution starts from main method called by JVM(java virtual machile).

2- In the java language the predefined is maintained in the form of packages.

 Ex:- java.lang java.io java.net java.awt

3- The packages contains predefined classes.

Ex:- String,System

4- To make available predefined support into our program we have to use
import statement.

Ex:- import java.lang.*;

5- Allocation :constructor

6- Deallocation:Garbage collector(part of the jvm)8-Irrespective of any os

Int -4
Char-2

7- To print the statements we have to use “System.out.println”

8- Java is dynamic language the memory is allocated at runtime time



Java coding Standards



Coding standards for classes

Usually class name should be noun. Should starts with upper case letter and if it contain multiple
words every inner words also should start with capital letters.

Example:

String
StringBuffer
NumberFormat
CustomerInformation

Coding standards for Interfaces

Usually interface named should be adjective, starts with capital letters and if it contains multiple
words, every inner word also should starts with capital letter.

Example:

Runnable
Serializable
Clonable
Movable
Transferable
Workable

Coding standards with methods

Values should be either verbs or verb + noun combination.
Starts with lower case and every inner words starts with upper case(this convention is also called
camel case convention).

Example:

getName(), getMessage(), toString(), show(), display().

Coding standards for variables

Usually the variable starts with noun and every inner word should start with upper case i.e camel
case convention.

Example:

Name, rollno, bandwidth, totalNumber.

Coding standards for constants

It should be noun, it should contain only upper case letters and works are separated with underscores.

Example:

MAX_SIZE, MIN_PRIORITY, COLLEGE_NAME.

Java Been Coding Conventions

A java bean is a normal java class with private properties & public getter and setter methods.

Example:

public class StudentBeen 
{
    private String name;
    public String getName() 
    {
        return name;
    }
    public void setName(String name) 
    {
        this.name = name;
    }
}

Syntax for getterMethod

Compulsory it should be public & should not contain any arguments.
For the non boolean property xxx the following is syntax of getter method

public datatype getXxx()
{
return xxx;
}

For the boolean property xxx the following is the syntax

public boolean getXxx() or isXxx()
{
return xxx;
}

Syntax of setter Method

It should be public and return type should be void. For any propertyxxx

public void setXxx(datatype xxx)
{
This.xxx = xxx;
}

To register a listener

To register myActionListener x which of the following is valid coding convention.

public void addMyActionListener(myActionListener x);
public void addActionListener(myActionListener x);
public void registerMyActionListener(myActionListener x);

Similarly to un register myActionListener x which of the following are valid coding convention.

public void removeMyActionListener(myActionListener x);
public void removeActionListener(myActionListener x);
public void registerMyActionListener(myActionListener x);



Java Video Tutorial



Core Java Video Tutorial

1. JRE, JDK, JVM

2. Features of Java

3. OPP's Concept

4. String, StringBuffer, StringBuilder Class

5. Java Packages

6. java.util Package

7. Nested Classes

8. Interface and Abstract Class

9. Exception Handling

10. Multi Threading

11. Applets

12. AWT (abstarct window toolkit)

Advance Java Video Tutorial

1. JDBC

2. Servlet- Part 1

3. Servlet- Part 2

4. Servlet- Part 3

5. Servlet- Part 4

6. JSP- Part 1

7. JSP- Part 2

8. JSP- Part 3


Session Based Interview Questions



1. What is a Session?
A Session refers to all the request that a single client makes to a server. A session is specific to the user and for each user a new session is created to track all the requests from that particular user. Sessions are not shared among users and each user of the system will have a seperate session and a unique session Id. In most cases, the default value of time-out* is 20 minutes and it can be changed as per the website requirements.

*Time-Out - The Amount of time after which a session becomes invalidated/destroyed if the session has been inactive.


2. What is Session ID?
A session ID is an unique identification string usually a long, random and alpha-numeric string, that is transmitted between the client and the server. Session IDs are usually stored in the cookies, URLs (in case url rewriting) and hidden fields of Web pages.

3. What is Session Tracking?
HTTP is stateless protocol and it does not maintain the client state. But there exist a mechanism called "Session Tracking" which helps the servers to maintain the state to track the series of requests from the same user across some period of time.

4. What are different types of Session Tracking?
Mechanism for Session Tracking are:
a) Cookies
b) URL rewriting
c) Hidden form fields
d) SSL Sessions

5. What is HTTPSession Class?
HttpSession Class provides a way to identify a user across across multiple request. The servlet container uses HttpSession interface to create a session between an HTTP client and an HTTP server. The session lives only for a specified time period, across more than one connection or page request from the user.

6. Why do we need Session Tracking in a Servlet based Web Application?
In HttpServlet you can use Session Tracking to track the user state. Simply put, it is used to store information like users login credentials, his choices in previous pages (like in a shopping cart website) etc

7. What are the advantage of Cookies over URL rewriting?
Sessions tracking using Cookies are more secure and fast. It keeps the website URL clean and concise instead of a long string appended to the URL everytime you click on any link in the website. Also, when we use url rewriting, it requites large data transfer from and to the server. So, it may lead to significant network traffic and access to the websites may be become slow.

8. What is session hijacking?
If you application is not very secure then it is possible to get the access of system after acquiring or generating the authentication information. Session hijacking refers to the act of taking control of a user session after successfully obtaining or generating an authentication session ID. It involves an attacker using captured, brute forced or reverse-engineered session IDs to get a control of a legitimate user's Web application session while that session is still in progress.

9. What is Session Migration?
Session Migration is a mechanism of moving the session from one server to another in case of server failure. Session Migration can be implemented by:

a) Persisting the session into database
b) Storing the session in-memory on multiple servers.

10. How to track a user session in Servlets?
The interface HttpSession can be used to track the session in the Servlet. Following code can be used to create session object in the Servlet:

HttpSession session = req.getSession(true);

Using this session object, the servlet can gain access to the details of the session.

11. How can you destroy the session in Servlet?
You can call invalidate() method on the session object to destroy the session.

e.g. session.invalidate();