Friday, May 29, 2015

Try Catch combinations


Checked diff unchecked



load-on-startup

load-on-startup is an element which appears inside <servlet> tag in web.xml.4 years back load-on-startup was a very popular servlet interview question because not many Java J2EE developer was familiar with this element and how load-on-startup works inside servlet container like tomcat or webshere. In this J2EE Tutorial we will see what is load on start up, how to use load-on-startup element and what are different values we can configure for loadOnStartup inside web.xml.

What is load-on-startup
load on startup servlet tag exampleAs stated earlier load-on-startup is a tag element which appear inside <servlet> tag in web.xml. load-on-startup tells the web container about loading of a particular servlet. if you don't specify load-on-startup then container will load a particular servlet when it feels necessary most likely when first request for that servlet will come, this may lead to longer response time for that query if Servlet is making database connections or performing ldap authentication which contribute network latency or any other time consuming job, to avoid this, web container provides you a mean to specify certain servlet to be loaded during deployment time of application by using load-on-startup parameter.

If you specify load-on-startup parameter inside a servlet than based upon its value Container will load it.you can specify any value to this element but in case of load-on-startup>0 , servlet with less number will be loaded first. For example in below web.xml AuthenticationServlet will be loaded before AuthorizationServlet because load-on-startup value for AuthenticationServlet is less (2) while for AuthorizationServlet is 4.

load-on-startup Example in web.xml

here is an example of how to use load on startup tag inside servlet element in web.xml:

<servlet>
<servlet-name>AuthenticationServlet</servlet-name>
<display-name>AuthenticationServlet</display-name>
<servlet-class>com.trading.AuthenticationServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>

<servlet>
<servlet-name>AuthorizationServlet</servlet-name>
<display-name>AuthorizationServlet</display-name>
<servlet-class>com.trading.AuthorizationServlet</servlet-class>
<load-on-startup>4</load-on-startup>
</servlet>

Important points on load-on-startup element

1. If <load-on-startup> value is same for two servlet than they will be loaded in an order on which they are declared inside web.xml file.
2. if <load-on-startup> is 0 or negative integer than Servlet will be loaded when Container feels to load them.
3. <load-on-startup> guarantees loading, initialization and call to init() method of servlet by web container.
4. If there is no <load-on-startup> element for any servlet than they will be loaded when web container decides to load them.

When to use <load-on-startup> in web.xml
<load-on-startup> is suitable for those servlet which performs time consuming jobs e.g. Creating Database Connection pool, downloading files or data from network or prepare environment ready for servicing client in terms of initializing cache , clearing pipelines and loading important data in memory. If any of your servlet performs these jobs then declare them using <load-on-startup> element and specify order as per your business logic or what suites your applicationRemember lower the value of <load-on-startup>, servlet will be loaded first. You can also check your web container documentation on how exactly load on start-up is supported.


That’s all on load on start-up tag of servlet element in web.xml. Use it carefully and it can reduce response time for your web application. You can also check my Struts interview questions and spring interview questions for more on J2EE interview.


Read more: http://javarevisited.blogspot.com/2011/12/load-on-startup-servlet-webxml-example.html#ixzz3bX58yUbw

ClassNotFoundException v/s No ClassDefFoundError

Test t = new Test()
if classname is hardcoded then if at runtime the .class file is nt available then will get NoClassDefFoundError

NoClassDefFoundError -- is unchecked exception bocz it is Error


Object o= Class.forName(args[0]).newInstance()
Java Test Student

at runtime for dynamically  provided class name, if the corresponding .class file is nt avalible then will get  ClassNotFoundException

ClassNotFoundException --> is a checked exception

Wednesday, May 27, 2015

Struts Interview Questions

Struts Flow

Frame work semi implemented application which will provide very good environment to simplify and excellerate the application development.
two types of framework
web appliction framework--Struts and JSF
appln frame work--spring

web.xml
it provides mapping between URL pattern and ActionServlet class which is available in struts framework.
has welcome file


Whenever any web application is deployed an object will be created ie ServletContext Object for each web Application Ex: Login Application
At the time of recognizing our application Container identifies web.xml  performs loading and parsing of web.xml file








Difference between include action and forward action.
Difference in output.ex: if we forward from one.jsp to two.jsp the contents of only two.jsp will be generated .     
if we include two.jsp in one.jsp the contents of both the jsp's will be generated

Why servlet is used as controller ?not JSP? i want complete Explation?

In struts servlet control the application and we know that a jsp compiled into a servlet first. The only problem with the servlet is that it needs to write out.println call per HTML line. But as a controller in struts servlets do not force the programmers to write out.println, that is the part of JSP which acts as View.

So if the controller would be JSP the translation (JSP compiled to a servlet)step would be of no use and it only affets the performance of the system.

Most of the applications are created in MVC design pattern to seperate the functions of differnet components and handle the complexity of applications. JSP and Servlets are the server side components which can respond to the client request.
Servlets are the basic components for request handling in Web Server. They contains pure Java code. Everything that needs to be done to generate the proper user response (which is genarally HTML code) needs to be done through coding. As a single servlet cannot respond each and every request by itself as client request varies in type (e.g. enquiry, update request, add etc) the request and response object is passed onto different servlets with little task completed by each servlet. This controlling part is easier to write in java. So Servlet is used as controller.
JSP is again a servlet which has syntax more like to HTML with java support. Whatever user is going to see as result of his request is HTML. Programmer can easily write html tags inside JSP to render html. This is very economical to change also. So all this code is written JSP which is (generally) the final link in Servlet chaining





Servlets are meant to carry out the dynamic work. If we put Servlet to View rather than as controller, it holds so many server resources, unnecessary creation of Request and Response objects that makes the Server to have unnecessary burden.
To maintain the control flow huge amount of code is required.Writing huge code in jsp is against jsp technology.
So Jsp is not recommended to use as a controller
What is difference between Html tags and Struts specific HTML Tags





1. Html tags are static Struts tags are Dynamic( At the run-time struts tags are called)2. Another diff is U create ur own Struts tags 

Struts tags bind the property value with the Formbean property defined.
Well from end users perspective, not much of a difference.

From programmers perspective, it can be said that each struts html tag would be mapped to an attribute of a form bean.

Another thing we can state is that we can define our own custom tags which isn't possible in html.

HTML tags are static and Struts tags are dynamic.
Struts tags can be created by the page authors.
Binding of the property value with the Formbean property is done by the Struts tags.
HTML tags support the templates and themes.
Struts have HTML tag libraries and thus HTML tags are integral part of Struts

Is Action class is Servlet or Not ? if yes why ?

In Struts1, Action Servlet is a servelet (since it extends HTTPServle) but Action class extentsorg.apache.struts.action.Action which has nothing to do with Servlet.

In Struts2, Action class extends com.opensymphony.xwork2.ActionSupport which has nothing to do with Servlet.

So, to answer the question, Action class is not a Servlet by any logic.
No, Action Class is not a servlet, Because it is not a subclass of javax.servlet.GenericServlet. An ActionServlet calls the execute() method of an ActionClass().

Action class is not a Servlet .
Any Java object which extends the functionality of servlet interface or HttpServlet or GenericServlet or it is subclass can be called as a servlet but our action class does not extend any of these.
For clarification go to web.xml, there we have to define all the servlets. You will not find Action class bec it is not a servlet.

Actually the confusion is between two classeshttp://images.intellitxt.com/ast/adTypes/icon1.png Action and ActionServlet. Be clear that these two are different classes. ActionServlet is a servlet but Action is a normal java class.
  Was this answer useful?  Yes
Reply
No Action class is not a  servlet since it is not overriding init(),service,destory methods at the same time its super classes are also not implemented these three methods.One thing i want to say is any servlet in the world should implement Servlet interface either directly or indirectly .But action class is not implementing like that so it is not a servlet
  Was this answer useful?  Yes
Reply

No. the Struts action class neither extend any class nor implement any interface.

More over it has defined one method getServlet() .. discribes which servlet it associated with it. This will be Action Servlet, unless your write ur own Action Servlet.

public class Action {
/**
*
An instance of TokenProcessor to use for token
* functionality.

*/
private static TokenProcessor token = TokenProcessor.getInstance();

// NOTE: We can make the tken variable protected and remove Actions
// token methods or leave it private and allow the token methods to
// delegate their calls.
// ----------------------------------------------------- Instance Variables

/**
*
The servlet to which we are attached.

*/
protected transient ActionServlet servlet = null;

// ------------------------------------------------------------- Properties

/**
*
Return the servlet instance to which we are attached.

*
* @return The servlet instance to which we are attached.
*/
public ActionServlet getServlet() {
return (this.servlet);
}

No.. Action class is not a servlet. The only servlet class in plain struts framework (without spring etc.) is ActionServlet.

Action class is not a servlet but it is having the properties like a servlet. For example servlets have request and response objects similarly action classes is also having request and response objects. So we can say action classes are having the servlet behaviour but they are not servlets. Since servlets are having init, service and destroy methods are there but action classes are not having these ..


Wednesday, May 20, 2015

datastructures

http://www.javaworld.com/article/2073526/core-java/datastructures-and-algorithms-part-2.html?page=2

Saturday, May 16, 2015

links

http://www.java-success.com/scenarios-java-multithreading-interview-questions/

JAXB

JAXB Tutorial

JAXB tutorial provides concepts and API to convert object into XML and XML into object. Our JAXB tutorial is designed for beginners and professionals.
JAXB stands for Java Architecture for XML Binding. It provides mechanism to marshal (write) java objects into XML and unmarshal (read) XML into object. Simply, you can say it is used to convert java object into xml and vice-versa.
JAXB 2 Tutorial

Features of JAXB 2.0

JAXB 2.0 includes several features that were not present in JAXB 1.x. They are as follows:
1) Annotation support: JAXB 2.0 provides support to annotation so less coding is required to develop JAXB application. The javax.xml.bind.annotation package provides classes and interfaces for JAXB 2.0.
2) Support for all W3C XML Schema features: it supports all the W3C schema unlike JAXB 1.0.
3) Additional Validation Capabilities: it provides additional validation support by JAXP 1.3 validation API.
4) Small Runtime Library: it required small runtime library that JAXB 1.0.
5) Reduction of generated schema-derived classes: it reduces a lot of generated schema-derived classes.

Simple JAXB Marshalling Example: Converting Object into XML

Let's see the steps to convert java object into XML document.
  • Create POJO or bind the schema and generate the classes
  • Create the JAXBContext object
  • Create the Marshaller objects
  • Create the content tree by using set methods
  • Call the marshal method
File: Employee.java
  1. import javax.xml.bind.annotation.XmlAttribute;  
  2. import javax.xml.bind.annotation.XmlElement;  
  3. import javax.xml.bind.annotation.XmlRootElement;  
  4.   
  5. @XmlRootElement  
  6. public class Employee {  
  7.     private int id;  
  8.     private String name;  
  9.     private float salary;  
  10.   
  11. public Employee() {}  
  12. public Employee(int id, String name, float salary) {  
  13.     super();  
  14.     this.id = id;  
  15.     this.name = name;  
  16.     this.salary = salary;  
  17. }  
  18. @XmlAttribute  
  19. public int getId() {  
  20.     return id;  
  21. }  
  22. public void setId(int id) {  
  23.     this.id = id;  
  24. }  
  25. @XmlElement  
  26. public String getName() {  
  27.     return name;  
  28. }  
  29. public void setName(String name) {  
  30.     this.name = name;  
  31. }  
  32. @XmlElement  
  33. public float getSalary() {  
  34.     return salary;  
  35. }  
  36. public void setSalary(float salary) {  
  37.     this.salary = salary;  
  38. }  
  39.   
  40.   
  41. }  
@XmlRootElement specifies the root element for the xml document.
@XmlAttribute specifies the attribute for the root element.
@XmlElement specifies the sub element for the root element.
File: ObjectToXml.java
  1. import java.io.FileOutputStream;  
  2.   
  3. import javax.xml.bind.JAXBContext;  
  4. import javax.xml.bind.Marshaller;  
  5.   
  6.   
  7. public class ObjectToXml {  
  8. public static void main(String[] args) throws Exception{  
  9.     JAXBContext contextObj = JAXBContext.newInstance(Employee.class);  
  10.   
  11.     Marshaller marshallerObj = contextObj.createMarshaller();  
  12.     marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  
  13.   
  14.     Employee emp1=new Employee(1,"Vimal Jaiswal",50000);  
  15.       
  16.     marshallerObj.marshal(emp1, new FileOutputStream("employee.xml"));  
  17.        
  18. }  
  19. }  

Output:

The generated xml file will look like this:
File: employee.xml
  1. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>  
  2. <employee id="1">  
  3.     <name>Vimal Jaiswal</name>  
  4.     <salary>50000.0</salary>  
  5. </employee>  

Simple JAXB UnMarshalling Example: Converting XML into Object

File: XMLToObject.java
  1. import java.io.File;  
  2. import javax.xml.bind.JAXBContext;  
  3. import javax.xml.bind.JAXBException;  
  4. import javax.xml.bind.Unmarshaller;  
  5.   
  6. public class XMLToObject {  
  7. public static void main(String[] args) {  
  8.      try {    
  9.             File file = new File("employee.xml");    
  10.             JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);    
  11.          
  12.             Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();    
  13.             Employee e=(Employee) jaxbUnmarshaller.unmarshal(file);    
  14.             System.out.println(e.getId()+" "+e.getName()+" "+e.getSalary());  
  15.               
  16.           } catch (JAXBException e) {e.printStackTrace(); }    
  17.          
  18. }  
  19. }