Search This Blog

Thursday, November 19, 2009

Servlet Question and Answer

When I will prepare for technical interview, I have used to think about hints and opt technical terms.

So I have started preparing question while reading books. I will ask question my self and redo the answer until I get opt technical words.

This post all are my own preparation if any one find its use full I really deserve for that.

Visitors of my blogspot kindly add your valuable comments to improve my post.

Note:

If u find any answer is wrong let me know. So I can redefine the same.

  1. What is Servlet?
    • Servlet is a java program, It will run inside the web container
    • Servlet extends request/respond –oriented servers such as java oriented web server.
  2. Different way to session tracking?
    • Cookies
    • URL re-writings
    • Http session tracking
    • Hidden form
    • Session
  3. What mechanism is used by servlet container to maintain the session?
    • Session
    • Cookies
    • URL re-writing
  4. Difference between GET and POST?

No.

Get

Post

1

Data are submitted part of URL

Data are submitted inside body of servlet request.

2

Query max length is 255 character

No Limitation

3

Its not secure

Its secure.

  1. Session
    • Session is a object is used to track the information about the user with web application across multiple HTTP Request (State less).
    • Session is stored on web server.
  2. Servlet Mapping
    • Mapping defines the association between the URL pattern and Servlet
    • Mapping will be define in web.xml
    • Mapping is used to map the particular request to Servlet.
  3. Servlet Context:
    • It’s a servlet Object that contains information about web application and container.
    • Each application has only one servlet Context Object.
    • Uses for set the attribute that other servlet in the same context can use.
  4. Can we use constructer instead of Init():
    • Yes we can use constructer in Servlet
    • But we wont get servlet specific feature
    • So we can’t use servletcontext and servletconfig object in constructer.
  5. Life cycle method of the servlet:
    • Javax.servlet.Servlet interface providing 3 life cycle methods are
    • Public void init (ServletConfig config)- will be called when instance is created.
    • Public void service(ServletRequest req,ServletResponse res)-Every request is handled by service method only.
    • Public void distory()-when object is de-allocated from JVM.
  6. Pre Initialization of a servlet:
    • Process of loading servlet before any request comes in is called pre loading/pre initialization.
    • We have to include the element priority for every servlet in web.xml
  7. Difference between HttpServlet and Generic Servlet:

No.

Http Servlet

Generic Servlet

1

Parrent Class for Http Servlet is Generic Servlet

Parent class of HttpServlet is Servlet

2

Http Servlet support doget(),dopost(),doHead methods

Service method will handle all the request.

  1. Difference between ServletContext and ServletConfig:

No.

Servlet Context

Servlet Config

1

Set of methods support to communicate with servlet container

Its specific to the single servlet.

2

Uses for set the attribute that other servlet in the same context can use.

Its used to initialize the servlet specific value.

3

It’s created when servlet container created.

It’s created when specific class is loaded by container.

  1. Advantages and selling point of Servlet?

    • Servlet handle the multiple requests and synchronize the request.
    • This allows servlet to support online real time conferencing.
    • Servlet forward the request to the other servlet.
    • So servlet can be used to balance the load among several servers that mirror the same content.
  1. what are the Information servletRequest object contain:
    • parameter passed by the client
    • name of the remote host
    • the protocol
  2. Type of constraints send on the client : by servlet Response interface

    • Content length
    • Content type
    • Servlet Writer, Servlet output stream and a writer through which the servlet can send the data.

  1. Context Initialization Parameter:
    • It’s specified in web.xml under the element.
    • This is a parameter for the whole application not specific for Servlet/JSP.
    • It will be only accessed by servlet context object.

  1. Servlet Chaining:

    • Two are more servlet co-operate in servicing a single request.

  1. Difference between Servlet Context and Page Context?
    • ServletContext –Gives information about Servlet container
    • PageContext-Gives information about request
  2. Difference:
    • Request.getRequestDispacher()-Need to give relative path.
    • Context.getRequestDispacher()-Need to give absolute path.
  3. Difference:
    • RequestDispacher()-Direct with request and Response object.
    • sendRequest()-direct with new request and Response object.

Tuesday, November 17, 2009

Important IQ

1.What are your goals?

I break down goals into short-term goals, with the long term in

mind. Right now I’m looking for a position in a company with a

solid track record. I want to contribute to a team, bringing my

extensive experience in this field to add to the team mix. Long term

goals will depend on the career path available at the company.

Ideally, I would like to move progressively within a

company.

2.What are your strengths?

My strengths are a combination of my technical skills and my

ability to work with a variety of customers. I consider myself a

data-mining expert, but what makes me stand out from the competition

is my ability to work directly with customers and get to

the root of the problem. I can break down complex issues into

simple, understandable concepts and language so that the customers

can understand what I am saying. I have received customer

service awards in the technical area for the last two years.

Notes

A good way to prepare for the “strengths” question is to do an assessment

of what you have to offer. This means not only your knowledgebased

skills (experience and education) but also the skills that are used

in almost any job—transferable or portable skills (communication

skills, time management skills, problem-solving skills).


3.What is your greatest weakness?

Good:Weaknesses are not something that I dwell on. I know I could

improve on my patience when working with people who don’t

work at the same pace as I do. What I have found is that by helping

members of the team who are having problems, I can move

projects forward instead of being frustrated and doing nothing.

Avg:I am a person who likes to get the job done correctly the first

time. I become very frustrated when other people’s work affects

my ability to do my job correctly. I’ve been working on trying to

be more understanding and finding out what the problem is

before I pass judgment.

Wrong:

(C) My weakness is working too hard to get the job done. Because of

the workload, I have to work many evenings and weekends so

that projects meet deadlines. I’m trying to work smarter and not

harder.

Notes

The “weakness” question is the most dreaded question of all. In

answering this question it is best to avoid saying that you are weak

in any areas that would affect your job performance (as seen in the

job positing). For example, “My time management skills need some

improving” would be a poor thing to say because you are admitting

that you may not be able to do the job.

4.When have you been most motivated?

Last year I was involved in a project that was very exciting. I was

assigned to work with a team, and we had to brainstorm about a

product that was not being received well by the consumers. I

would wake up in the morning thinking of creative ways to overcome

our problem. The especially great part of this project was

the team I was working with. The team and the creative problem

solving are what make a difference in my motivation.

5.How would you describe your personality?

I am a high-energy person who is motivated by new challenges

and problems. I can hit the ground running and come up to

speed faster than anyone I know. I have a proven record of success

and a reputation for meeting deadlines on time. My attitude

about work is “whatever it takes to get the job done.” Anyone in

my department would tell you that I am someone who really

supports the team spirit.

Notes:

Describing your personality is like writing an ad for a product. What

makes you unique? Making a list of your specific personality traits

is a good exercise to prepare for an interview.

6.Have you ever been fired?

Good : One of the managers who reported to me made a big mistake that

caused the company to lose a great deal of money. Because I was

his boss, we were both fired. At first I did not think this was fair.

I now realize that the man was under my supervision and that it

was on my shift, and I take full responsibility for what happened.

I have put the incident behind me and am looking forward to

moving on to new opportunities.

Avg

I made a mistake in judgment that went against company policy

and was fired. I’m not proud of what I did and was hard on myself

about the mistake, but I also learned a lot from the incident. There

is no point holding on to the past. I will be more careful about my

actions in the future. I am ready for a second chance and know that

I will be a better employee because of this experience.

Note:


People get fired every day. They move on and get new jobs. No matter

what the circumstances, it is best to put it behind you. Deal with

your feelings about the firing before the interview, and as you prepare

your script, you will feel more confident and less emotional

about the situation.

Monday, November 16, 2009

Struts for Begineer


What are struts?

  1. Struts are an open source framework used for developing J2EE web applications using Model View Controller (MVC) design pattern.

  2. It uses and extends the Java Servlet API to encourage developers to adopt an MVC architecture.

Struts framework provides three key components:

  1. A request handler provided by the application developer that is used to map to a particular URI.

  2. A response handler which is used to transfer the control to another resource which will be responsible for completing the response.

  3. A tag library which helps developers to create the interactive form based applications with server pages.

MVC Architecture

Aim:

The main aim of the MVC architecture is to separate the business logic and application data from the presentation data to the user.

Here are the reasons why we should use the MVC design pattern.

  1. They are reusable: When the problem recurs, there is no need to invent a new solution; we just have to follow the pattern and adapt it as necessary.

  2. They are expressive: By using the MVC design pattern our application becomes more expressive.


Model:

  1. The model object knows about all the data that need to be displayed.

  2. It is model who is aware about all the operations that can be applied to transform that object. It only represents the data of an application.

  3. The model represents enterprise data and the business rules that manage, access and updates of this data.

  4. Model is not aware about the presentation data and how that data will be displayed to the browser.

View:

  1. The view represents the presentation of the application.

  2. The view object refers to the model. It uses the query methods of the model to obtain the contents and renders it.

  3. The view is not dependent on the application logic. It remains same if there is any modification in the business logic.

  4. In other words, we can say that it is the responsibility of the view's to maintain the consistency in its presentation when the model changes.

Controller:

  1. Whenever a user send request for something it always goes through the controller.

  2. The controller is responsible for intercepting the request from the view and send to the model for appropriate action.

  3. After the action can be taken in the data, after the appropriate data will be transfer to the view by controller.


Struts framework:


  1. Struts framework composed of approximately 300 class and interfaces which are organized 12 top level packages.

  2. Utility and helper class framework providing interacting with controller using class and interface.

  3. Even framework is providing predefine tag library for html GUI design.

The struts controller component:

  1. Whenever a user request for something, then the request is handled by the Struts Action Servlet.

  2. When the ActionServlet receives the request, it intercepts the URL and based on the Struts Configuration files, it gives the handling of the request to the Action class.

  3. Action class is a part of the controller and is responsible for communicating with the model layer.

The Struts View Components:

  1. The view components are responsible for presenting information to the users and accepting the input from them.

  2. They are responsible for displaying the information provided by the model components.

  3. Mostly we use the Java Server Pages (JSP) for the view presentation. To extend the capability of the view we can use the Custom tags, java script etc.

The Struts model component:

  1. The model components provide a model of the business logic behind a Struts program. It provides interfaces to databases or back- ends systems.

  2. Model components are generally a java class. There is not any such defined format for a Model component, so it is possible for us to reuse Java codes which are written for other projects. We should choose the model according to our client requirement.

Struts working

Struts Controller:

  1. The class org.apache.struts.action.ActionServlet is the heart of the Struts Framework. It is the Controller part of the Struts Framework.

  2. ActionServlet is configured as Servlet in the web.xml file as shown in the following code snippets.



action
org.apache.struts.action.ActionServlet

config
/WEB-INF/struts-config.xml


debug
2


detail
2

2

tag in the web.xml file specifies the url pattern to be handled by the servlet. By default it is *.do, but it can be changed to anything.



action
*.do


What is Action Class?

  1. An Action class in the struts application extends Struts 'org.apache.struts.action.Action" Class.

  2. Action class acts as wrapper around the business logic and provides an interface to the application's Model layer.

  3. It acts as glue between the View and Model layer. It also transfers the data from the view layer to the specific business process layer and finally returns the processed data from business layer to the view layer.



Action Class working procedure:

  1. An Action works as an adapter between the contents of an incoming HTTP request and the business logic that corresponds to it.

  2. Then the struts controller (ActionServlet) selects an appropriate Action and creates an instance if necessary, and finally calls execute method.

To use the Action, we need to Subclass and overwrite the execute () method.

  1. The ActionServlet (command) passes the parameterized class to Action Form using the execute() method.

  2. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

Understanding Action Class
Here is the signature of the Action Class.

public ActionForward execute(ActionMapping mapping,

ActionForm form,

javax.servlet.http.HttpServletRequest request,

javax.servlet.http.HttpServletResponse response)

throws java.lang.Exception

Action Class process the specified HTTP request, and create the corresponding HTTP response (or forward to another web component that will create it), with provision for handling exceptions thrown by the business logic. Return an ActionForward instance describing where and how control should be forward0ed, or null if the response has already been completed.

Parameters:

mapping - The ActionMapping used to select this instance

form - The optional ActionForm bean for this request (if any)

request - The HTTP request we are processing

response - The HTTP response we are creating

Throws:

Action class throws java.lang.Exception - if the application business logic throws an exception



What is ActionForm?

An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm.

  1. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.

  2. The validate() method is used to validate the inputs. If any or all of the fields on the form are blank, error messages are added to the ActionMapping object. Note that we are using ActionMessage class, ActionError is now deprecated and will be removed in next version.

  3. Validate methods has two parameters one is ActionMapping, HttpServletRequest.

public ActionErrors validate(
ActionMapping mapping, HttpServletRequest request ) {
ActionErrors errors = new ActionErrors();

if( getName() == null || getName().length() <>
errors.add("name",new ActionMessage("error.name.required"));
}
if( getAddress() == null || getAddress().length() <>
errors.add("address",new ActionMessage("error.address.required"));
}
if( getEmailAddress() == null || getEmailAddress().length() <>
errors.add("emailaddress",new ActionMessage("error.emailaddress.required"));
}

return errors;
}

Struts HTML Tag:

Struts provide HTML tags library for easy creation of user interface.

To use Struts HTML tags we have to include following line <%@ taglib uri=”” prefix =”html” %>




Submit

Reset




Submit

Reset







Struts Validator Framework


  1. Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side.

  2. Struts Framework emits the java scripts and it can be used to validate the form data on the client browser.

  3. The Validator framework was developed by David Winterfeldt as third-party add-on to Struts.

Using Validator Framework


  1. The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml.

  2. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations.

  3. The validation.xml defines the validations applied to a form bean

Structure of validator-rule.xml


  1. The validation-rules.xml is provided with the Validator Framework and it declares and assigns the logical names to the validation routines

  2. It also contains the client-side javascript code for each validation routine. The validation routines are java methods plugged into the system to perform specific validations.

Eg., Structure

classname="org.apache.struts.validator.FieldChecks"

method="validateMinLength"

methodParams="java.lang.Object,

org.apache.commons.validator.ValidatorAction,

org.apache.commons.validator.Field,

org.apache.struts.action.ActionMessages,

org.apache.commons.validator.Validator,

javax.servlet.http.HttpServletRequest"

depends=""

msg="errors.minlength"

jsFunction="org.apache.commons.validator.javascript.validateMinLength"/>

Structure of validation.xml

  1. This validation.xml configuration file defines which validation routines that are used to validate Form Beans.

  2. You can define validation logic for any number of Form Beans in this configuration file. Inside that definition, you specify the validations you want to apply to the Form Bean's fields.

  3. The definitions in this file use the logical names of Form Beans from the struts-config.xml file along with the logical names of validation routines from the validator-rules.xml file to tie the two together.




property="username"

depends="required">

property="password"

depends="required,mask">

mask

^[0-9a-zA-Z]*$



Client Side Address Validation in Struts

Validator Framework emits the JavaScript code which validates the user input on the browser. To accomplish this we have to follow the following steps:

  1. Enabling the Validator plug-in: This makes the Validator available to the system.

  2. Create Message Resources for the displaying the error message to the user.

  3. Developing the Validation rules we have to define the validation rules in the validation.xml for the address form. Struts Validator Framework uses this rule for generating the JavaScript for validation.

  4. Applying the rules: We are required to add the appropriate tag to the JSP for generation of JavaScript.

  5. Build and test: We are required to build the application once the above steps are done before testing.

Developing Simple Struts Tiles Application

what is Struts Tiles?

Tiles are a framework for the development user interface. Tiles is enables the developers to develop the web applications by assembling the reusable tiles (jsp, html, etc..). Tiles uses the concept of reuse and enables the developers to define a template for the web site and then use this layout to populate the content of the web site.