Archive

Posts Tagged ‘J2EE’

Struts 1 – how easier it is

March 12th, 2012 63 views No comments

I suppose I am increase redundancy over Internet by writing this article. You’ll find many of articles on Internet over struts. But only some of them has explained how easier strut is.

Prerequisites:

  1. JSP
  2. Servlets
Summary of JSP & Servlets:

JSP is nothing but a HTML page with java scriplets. They were designed to reduce Servlet work load & length. Imagine a well designed HTML page with 2 input box and 1 submit button. You fill HTML form & submit the request to a servlet. Servlet is not aware where the request is coming from. It might be some awt application or web page or web service etc. So it just respond with sum of values of both textbox. What happens next?……… content of your whole HTML page will be erased and you will see just a numeric value on that. That’s why JSP was discovered.

Now what is Servlet?
Servlet is nothing but a special java class running on server hidden from external people. A person can request/invoke it with its alias name written in web.xml. For each request to the webserver, container reads web.xml. Read aliases and calls actual java class who matches with that alias. For the convenience J2EE provides some classes for JSP & SERVLET;

  • Request : to read a request from a client
  • Response : To give response to client
  • Session : To remember client who requested last time
  • Cookie : To store some data at client’s computer.

Read more about it here

Lets start with Strut 1.

Strut is a framework over JSP & Servlet. It divides a Servlet class into 2 parts as per its working: Action & POJO class (or Controller & Model respectively). JSP is just for display/view purpose.

Controller just listen clients. Means it reads client requests and response them like a receptionist. It takes help from other java classes to fulfill the request. These java classes are caller Model. It is just like a restaurant where waiter listen your order and serve you meal. But chef inside kitchen actually cooks food.

This sort of architecture is called MVC(Model-view-controller) architecture.

Key Components

Action Servlet You need this one per application and its supplied by Struts itself. So you don’t write or modify it.
Form Beans For each HTML form one form bean is written. They are just Java beans. When a request to Struts Action Servlet arises. it calls setters on the form bean and populate its field member form request parameters.
Action Objects It has a call-back-like method called execute() which is a great place to get the validated form params and call model components.

its kind of a servlet lite

struts-config.xml This is the Struts-specific deployment descriptor, in it you will map

  • Request URLs to actions
  • Actions to Form beans
  • Actions to views
How struts work?

In short: A request come to web container (say Tomcat) who looks for alias in web.xml. It looks for URL pattern since eince exact URL alias is not present in web.xml. It sends request to ActionServlet. This servlet reads another configuration file (strut-config.xml) who actually has entries of all action classes. It calls setters of related form bean class and populate its fields with request parameters. Pass this form & request to relevant Action class.

how strut 1 works flow

See what actually happens:

  1. Action Servlet (provided into strut bundle, we don’t write  our own) needs to be mapped in web.xml same as other servlet are mapped.
  2. When a hit comes to Action Servlet, it reads strut-config.xml to know actual mapping (like which Action class or ActionForm is mapped and what are their initial values).
  3. Note: if it finds no action mapping, it set error in response header and return back.

  4. What ActionServlet does next with ActionForm
    1. It looks for form bean object into session. If it doesn’t present makes new one. (A form bean is simple java bean extends ActionForm)
    2. Calls reset() of ActionForm and populates it by calling all setters.
    3. If validate=true is set into action-mapping then it calls bean’s validate() of ActionForm.
  5. Note: it calls setter for all methods which are coming as request parameter. So there is no problem if form bean has an extra setter. But if there is an extra request parameter and form bean has no corresponding setter then it’ll generate run time error.

  6. If form bean returns a non-empty errors object then it pass error object to input page or error page as per its action-mapping.
  7. Note: If there is no page defined action-mapping as input page then it does nothing.

  8. If ActionError is empty then ActionServlet creates an object of relevant action class, pass the populated & validates form bean object, and calls action object’s execute().
  9. Note: if ActionForm’s setters or validate() modify actual values of form then they will not be reflected in session. But updated ActionForm will be passed to Action class.

  10. JSP: When a JSP with an html:form tag is rendered, the html:form tag uses its action path to look-up its action-mapping. Like the ActionServlet, it uses the form-bean to check for a ActionForm in session. If it doesn’t find one, it creates one. The new or pre-existing ActionForm is then used by the other html:tags to populate their elements. So the form fields get populated automatically if the form has been submitted once.
    Note:

    1. form-bean name specified in action-mapping is used as the default attribute name in session.
    2. If you are using same form for 2 or multiple actions with the same name in action-mapping, you will ever get the form with last submitted values. To avoid this, use the same ActionForm but with different name in action-mapping.
    3. Similarly, If you submit a form from a JSP page and forward to the same JSP page again from action class or ActionForm, you’ll get the form filled with submitted values even if the values are modified by setters or validate().
    4. html:tags uses form-bean name from session by default. You can change bean scope as per your need.

What else?
You’ll have to read strut tags similar to any other tag library like jsp, jakarta, apache, JSTL etc. Tags help in avoiding direct java code in JSP.

Simplest Shortest Sweetest Servlet tutorial – Part 2

February 8th, 2011 84 views No comments

You can request to a web server from html form using two methods GET & POST. So Our servlet class has two methods doPost() and doGet(). Our web servers automatically call appropriate method. So you need not to worry about internal mechanism this time.

< form method="get" action="/alias name of servlet">
:
< /form>

I hope the above discussion and the part1 has cleared you that a servlet is nothing but a java class accessorized with some extra classes to handle request, response etc. You can explore the servlet sea with your syntactical knowledge.

To increase you syntatically knowledge, here I am introducing you some commonly object, their use and their concept to handle not only J2EE but any web based application

Request

With Http request object

  1. You can read what is written in request header.
  2. Data submitted through the html form say form parameter
  3. Clients IP address, host address etc.

Refer sample servlet, web.xml and sample html page to know how to use request object.

Response

A servlet can response in either character form or in binary form. Giving response in binary format is similar to write data onto output stream. And responding in character format is similar to System.our.println() statement.

Character Data


response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("< html>");
:
out.close();

Binary Data


FileInputStream fis = new FileInputStream(new File("article-stack.pdf"));
response.setContentType("application/pdf");
ServletOutputStream servletOut = resp.getOutputStream();
byte[] read;
int bytes = 1024;
while((read=fis.read(bytes))!=-1)
	servletOut.write(bytes,0,read);
servletOut.close();

Example servlet
With the above small discussion and sample servlet, you should be able to design basic servlets like;

  • Submit a HTML Form to servlet. And display its data back.
  • Requesting a servlet to download a file.

Let me tell you one more point as a bonus

There is a very basic difference in attributes and parameters. When you pass something to a servlet then is called parameter. But when a servlet or JSP set some variables for their communication then it is called attribute.

Simplest Shortest Sweetest Servlet tutorial – Part 1

February 6th, 2011 125 views No comments

If you are a windows application developer then working with web application may fear you a bit. But if its concept, syntax, purpose of use etc. sets to your mind properly then you can soundly say that it is childish step to move ahead.

I am preparing a very funny video tutorial over servlets now days. And I hope to publish it soon. Till the period, this tutorial can help you to understand why & how we use servlet. And how we can develop J2EE applications easily.

Consider

A java based windows application which required id & pass in starting.

login screen

  1. Compare Input data against the id & pass stored into DB or written in a file. Or maybe you hard-coded it somewhere in your application.
  2. A class or function you use to check login id & pass say validUserCheck() or loginCheck(). You would have to pass both input values as parameter.

Points to be noticed

  1. When you call a function and pass some values to it, you call it as “parameter”.
  2. Hard coding values in your application, is not a good programming practice. It requires recompilation when that value is changed.

Migrate to J2EE

In web applications, whatever you want to display is written onto webpages say html or JSP. And the java classes containing functions and programming logic are called as SERVLET.

But

Actual name of servlet is kept hidden from outsiders. So a list is prepared which keeps entry of all servlets we designed along with their alias name. This file is called web.xml


java j2ee web.xml

About Servlet

Servlet is ordinary java class which handles all request and response so. There can be N number of java classes in our applications which are being used for different purpose but not to handle requests. These classes are called POJO. Besides handling request and response, servlet is just a java class.


Flow of J2ee servlet web application

Keep reading other parts
You may have refer sample servlet, web.xml and webpage till then.