Category Archives: Core Java

Basic Core Java Concepts

First of all, advance bail on my behalf if my content is insignificant at this point. I thought of writing this blog post after searching through Google Trends and noting that there are good amount of search queries till now looking for these basic core java concepts.

I don’t want to split this blogs into multiple parts as i feel it wouldn’t be good for a reader to go onto various parts and would like to keep it an ever evolving blog post with full support from my readers.

[TODO]

My previous blogs could give some inputs in bulleted points to new Java developers as given below:-

Basic Java FAQ – Part 1

Basic Java FAQ – Part 2

Basic Java FAQ – Part 3

SCJP – Quick Notes

and finally and small mock example to check knowledge

Mock Exam

Page Visitors: 422

Web Service Framework Comparison – 2013 – Part II

As promised here is my Part II of the blog. You can find Part I of the blog in here. Also my chapter on Spring WS in my Spring book in here.

The Blog is still under construction but i would like to publish it and then keep on updating with more content. Apologies for incomplete blog post.

Apache CXF

The project is a merger between two open source projects namely Celtix developed by IONA technologies and XFire developed by Codehaus. As you would have already figure why the name CXF – Celtix XFire. Rather than me plagiarizing, I would suggest reading the Wikipedia for more details http://en.wikipedia.org/wiki/Apache_CXF.

Some of the advantages associated with Apache CXF is as follows:-

  • Good cohesive support for the Spring Framework.
  • Good OSGi support (How much this is a valid constraint for the evaluation is questionable, i agree).
  • Good support for more strong web service functionalities like WS-Security, WS-Policy etc. to name a few.
  • It also has a compliant JAX-RS implementation allowing it to expose web service as REST and SOAP based.
  • It also has W3C compliant SOAP/JMS implementation if they are required.
  • Much easier to use and implement.
  • Less verbose when it generates basic classes for WS/WS-Client from the WSDL.
  • More “standards based” API’s. The API’s are slim and trim with good performance and ease of use.
  • Considered more “embeddable” as opposed to other WS frameworks, especially with the Spring Framework.
  • CXF provides support for code first and contract first development, and provides ability to plug-in various flexible binding mechanisms.
  • The front end programming API’s is spectated from the core code making it really flexible.

Some of the disadvantages associated with Apache CXF is as follows:-

  • Doesn’t support Orchestration and WS transactions yet (I really don’t know how relevant this is, i plagiarized it from Ankur Kumar blog, refer reference section of this blog post. As he is well-versed with WS, i think i should believe him. Might be Daniel Kulp will help me with this.)
  • WSDL 2.0 support is not yet there.
  • Again, CXF is very good with SOAP, so for web services based on REST, due to its very good support for SOAP, CXF brings in added weight and complexity (I am expecting Daniel Kulp to help on this as well)

Apache Axis2

As explained earlier is a completely re-written version of the famous Apache Axis SOAP stack. While doing so it has to some extend looked upon various lessons learnt and corrected it. Some of the advantages of using Axis2 are as detailed below:-

  • Good support for more strong web service functionalities like WS-Security, WS-Policy etc. to name a few.
  • Good integration support for binding frameworks like XMLBeans, making it suitable for creating web services having complex schema definitions.
  • Somewhat better integration support with the Spring Framework. More details can be found at http://axis.apache.org/axis2/java/core/docs/spring.html.
  • Considering performance aspects, it performs a bit faster compared to Apache Axis2 due to use of proprietary API’s.
  • Supports bothe Contract-First and Contract-Last approach, which gives good flexibility and choice to the users. This is key to some extend.

Some of the disadvantages attributed to Axis2 are as detailed below:-

  • Lack of cohesive support with JAX-WS. the support is detailed in the following URL: http://axis.apache.org/axis2/java/core/docs/jaxws-guide.html.
  • Again good cohesive support between Axis2 and Spring Framework as opposed to other WS frameworks.
  • Good amount of classes, a bit hard to understand and difficult to refactor in case if it is required.
  • Churns out more proprietary API’s and you as a developer would have to handle these.
  • Quick turnaround with fixes and releases. You could read Part I of this blog which compared these aspects in detail.
  • Slowly Apache is phasing out Axis2 in favour of Apache CXF (Please dont quote me on this, but this is slowly happening)
  • It’s a web application by its own with all the services deployed in WEB-INF/services folder as AAR (Axis 2 Archives). This structure as a whole can be problematic while deploying, maintaining, upgrading, versioning and testing to a greater extend.

Spring WS

Some of the advantages associated with Spring WS is as follows:-

  • Full support of the Spring programming model and this can be a very good advantage to take this framework on. The Spring Framework is leading the Java web framework race, now almost single handedly and this advantage is key according to me.
  • Clean API’s (same as above because Spring having clean API’s has influenced this to a larger extend)
  • Clean mapping of the incoming SOAP messages to the methods
  • If your web application framework is based on Spring MVC, Spring WS gives easy and clean mixing between WS endpoints and Spring MVC’s controllers. Also coding of endpoints is as easy as coding a new controller in Spring MVC.
  • Easy unit/integration testing capabilities.
  • Support for different XML marshallers.
  • No generated code/deployment descriptors.

Some of the disadvantages associated with Spring WS is as follows:-

  • Supports only Contract-First approach, which could result in lack of flexibility to the users.
  • Most of WS-* support might be questionable. By the way how much of WS-* things we use?

Technologies grow faster and with open community development, issues identified gets fixed quickly. Having said that, there is an article which i would like to share; http://www.ibm.com/developerworks/java/library/j-jws19/index.html; which rates Apache CXF more as compared with Apache Axis2 in security aspects. Many issues identified would have got corrected over the period of 3 years, but its worth noting these.

Although my comparison is not that well structured, i found a blog released on the same day as i was typing mine, which details the set of criteria which should be used for evaluating the web service frameworks. If i have to do this extensive comparison, it would take me at least 3 months. Since i don’t have much time at this point, i still don’t want the reader not to see these evaluation criteria, which is well structured and though through:

http://naveenbalani.com/index.php/2010/05/evaluating-web-service-frameworks/

Things which I think (Purely my own)

  • For almost 80% of the projects the capabilities required can be covered in a good way by using either Apache CXF or Apache Axis2. If already you application is based on Spring Framework, I would suggest using Apache CXF along with Spring Framework OR using Spring WS with use of CXF as the web service engine.
  • Spring WS similar to the Spring programming model has good and clean API’s, making it easy for developers (juniors) to code web services in Spring WS fast and easy. If you would like more standards, i think Apache CXF is a good choice over Apache Axis2. Again Apache Axis2 is slowly getting itself eaten up by Apache CXF. Fro an enterprise application point of view longevity and community support id required and here CXF scores well compared to Axis2.

Spring WS > Apache CXF > Apache Axis2

I cannot really say that Spring WS is above Apache CXF, because they are very very good fraewmorks. According to your application requirement, i would suggest using either Spring WS or Apache CXF.

Finally to finish off the blog, i would again like to share a picture, which gives Google Search Trends for these Web Service Frameworks in the year 2013 – WorldWide. How much it gives an edge to Apache CXF is questionable, nevertheless gives an indication as to what people are looking for in Google with regards to these frameworks and which is more active.

GoogleTrendsWSFrameworks

There is a beautiful page maintained in Apache which compares the various WS frameworks as a whole. The page is edit last in the year 2011, but I felt the page is a good share in my blog (note Spring WS is missing in the list because it is not an Apache project).

http://wiki.apache.org/ws/StackComparison

References

Page Visitors: 6063

Web Service Framework Comparison – 2013 – Part I

I have done a similar blog post earlier, namely Spring Integration Vs. Apache Camel, surprisingly it received good review from the community and i thought i will do a similar exercise on one of the other big topic of comparison these days, Web Services Framework.

I have a Spring Book Chapter in Spring Web Service, which you can find in my Spring Book, Chapter 16.

Again, i am not biased on selecting any of the frameworks. The view expressed are solely mine. To be honest i don’t have a great deal of experience in the field of web services, but again as part of one of my projects i came into a scenario where i have to select on these frameworks and i thoughts to share the details that i collected. Again, i don’t want to give a verdict, as i don’t consider myself capable of doing so. Just so that anyone in situation can go through the blog and get details, compile it, present it to the team and based on it take the final decision for your project.

Also i have taken three web service framework, which i felt was top in the industry as of now. If anyone disagrees, please feel free to comment on the blog and looking at its relevance i will correct it, as i don’t want this blog to a misleading one for the community as a whole.

Apache CXF

Apache CXF is an open source services framework. CXF helps you build and develop services using frontend programming APIs, like JAX-WS and JAX-RS. These services can speak a variety of protocols such as SOAP, XML/HTTP, RESTful HTTP, or CORBA and work over a variety of transports such as HTTP, JMS or JBI.

– http://cxf.apache.org

Axis2

Apache Axis2™ is a Web Services / SOAP / WSDL engine, the successor to the widely used Apache Axis SOAP stack. There are two implementations of the Apache Axis2 Web services engine – Apache Axis2/Java and Apache Axis2/C.

– http://axis.apache.org

Spring WS

Spring Web Services is a product of the Spring community focused on creating document-driven Web services. Spring Web Services aims to facilitate contract-first SOAP service development, allowing for the creation of flexible web services using one of the many ways to manipulate XML payloads.

– http://static.springsource.org/spring-ws/sites/2.0

Comparison from ohloh.net for the two projects:-

WebServiceComparison1

WebServiceComparison2

I think the comparison figure that is shown above doesn’t convey the exact comparison that we expect. Just by looking the figure above, Spring WS scores very low and can be taken out immediately from comparison. BUT that’s not the case IMHO. Lets get dirty and try the various comparison in some detail.

This is something new in this post, job trends on these technologies from indeed.com is as shown below. What it shows? It might not be relevant, but it shows what companies are looking at hiring when it comes to these technologies. It might be misleading but it shows that what companies are thinking and which technology is popular in various organization’s mind.

JobTrend

JobTrend1

The above comparison figure on the various web service framework’s job opening’s doesnt really give any technical comparison between them but is a good to know fact. It also gives some trends followed by various companies.

Note:- Spring Web Service project was added by me in ohloh.net, solely for comparison perspective. The code location was already added in the main Spring Framework project. If anyone feels that this is not the right way, please feel free to send me a comment and i will do the needful. Also, if it is violating any of the legal terms doing so, please don’t sue me.. :). If given proper directions, i will correct it as early as possible.

In Part II of the post, i will be covering the comparison of these frameworks in detail, looking at various aspects and trying to get some conclusion as to which framework has an edge over the other and what is the reason for me to think so.

Let me have my short and sweet weekend and by next week you can read my blog post, which will be more useful and informative.

 

Page Visitors: 1225

What is rt.jar? What constitutes JDK and JRE?

For a beginner, this will be one of the question which they might have. For an expert even though this is well known jar file in Java, very few will know as to what it is and why it is so important. This blog post is a very short post, just giving some details of what rt.jar is and what constitutes Java as a whole (JDK/JRE).

rt.jar contains all the RunTime classes that comprise the Java SE platform’s core API’s. In simple terms this is the jar which contains classes like java.lag.String, java.io package etc. The source code for these API’s can be found in src.zip file in JAVA_HOME.

Since all the classes in the rt.jar are known to the JVM, these classes tend to be left alone with various checks that JVM does while loading these classes onto it. This is also done for various performance reasons. These jars are loaded by primodial class loaders and that’s the reason these classes avoid the basic security checks which the JVM does for other jars/classes.

The base files and folders in the JDK/JRE is shown in the below figure.

JDK-JREFiles

Image Courtesy – docs.oracle.com

For more details on all the various files and directories comprising JDK and JRE, i would suggest going through the official Oracle documentation as follows:

http://docs.oracle.com/javase/6/docs/technotes/tools/windows/jdkfiles.html

As pointed out by one of the reader, since the above link is no longer maintained, the below link which details JDK 1.7 is given:

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdkfiles.html

 

Page Visitors: 5130

Garbage Collection – Java Performance Tuning

While i was reading the latest Java Magazine (July-August 2013), i came across a topic namely, “Adaptive Size Policy” with regards to one of the important components in JVM, garbage collection.

I researched on this topic and this blog post is my attempt to explain this in some details with good references for follow up reading.

Before going on to explain “Adaptive Size Policy”, i need to cover certain basics in the field of garbage collection. I will be covering this blog under such sub-topic for easy understanding and reading.

JVM Heap in General

JVM heap, aka heap, is divided into two regions, called as generation, namely

  • Young Generation
  • Old Generation

The Young generation region is further divided into sub-regions, namely

  • Eden
  • Survivor Space 1
  • Survivor Space 2

This is how it works when an object is created:

  • The object will be created in Eden and it could be destroyed there itself
  • If the Eden region is full, the object is pushed to Survivor Space 1
  • If the Survivor space 1 is full, the object is pushed to Survivor Space 2
  • The objects which are not destroyed in Survivor Space 2 are retired to the Old Generation region of the heap

To tweak the heap size commonly used Java options as -Xms and -Xmx. You can get a complete list of -X commands that you can use with respect to Java Heap Size, please run the command java -X. Below screenshot shows the various commends that can be used.

Java -X commands which can be used for Heap Management
Java -X commands which can be used for Heap Management

Java Garbage Collection in General

Most of the programming language including Java has a very important feature of automatic memory management, also known as “Garbage Collection”. Objects created during execution of a program, at various stages becomes unreachable and are considered as “garbage”. Over a period of time for managing memory, these garbage is removed and the space is regained for useful staff. Java has very good garbage collection and over a period of time, with some very good engineers working on it, using various algorithms, have made significant progress and enhancement this all important feature.

The core component in the Java SE platform is JVM (Java Virtual Machine). In the case of Oracle JVM, its called as “Oracle’s Hotspot JVM”. We will discuss garbage collection with respect to this Hotspot JVM as GC (Garbage Collection) methodologies differ according to the JVM being used.

Garbage collection is one of the biggest benefit which the Java language provides. If used in a proper manner it will be really beneficial, but if not used cautiously, it can doom your application big time. Some of the considerations with respect to garbage collection which have to be kept in mind are the following:

  • JVM Pause – The time taken by the JVM to do the GC during which the JVM pauses
  • Throughput – The time interval between successive GC

Our goal as an application tuner is to minimize the JVM pause and maximize throughput. There is no hard and fast rule that you can reply on to do this. It comes with experience and the environment in which your JVM/application functions, which will interfere to a greater extend.

There are various GC modes which are possible to be configured using various JVM commend line options. Having said that, these JVM options configured is dependent on various components like the hardware you are running, JVM version etc. to name a few. The default GC mode also depends on the JVM vendor. The various GC modes with respect to Hotspot JVM is as detailed below:-

Serial GC

As the name suggests it is executed by a single thread and requires a complete stop on all the processes carried out by JVM during the execution. The JVM switch for this is specified as -XX:+UseSerialGC

Parallel Scavenge

As the name suggests the collection is parallelized between multiple threads. This also requires the entire JVM operations to be stopped/deferred but during to parallelism, the time required will be reduced to a greater extend. The JVM switch for this is specified as -XX:+UseParallelGC. In modern days due to availability of multicore/multiprocessor this has become more of a norm.

Parallel Old GC

Incremental advancement over Parallel GC mode. I don’t want to go into much more detail, as this post is a head start for beginners to get a primer on GC. The JVM switch for this is specified as -XX:+UseParallelOldGC

Adaptive Size Policy

A special mode of Parallel Scavange in which the JVM automatically adapts and adjust the various heap sizes and does the GC. Might sound a big scary as you might feel that there isn’t much control in overall space allocation by JVM. But IMHO, the java engineers have put lots of effort and experience building this and they shouldn’t be taken as complete wrong and we should have fairly good confidence in using this switch as well. The JVM switch for this is specified as -XX:+UseAdaptiveSizePolicy

Concurrent Mark Sweep (CMS)

Its a low pause collector and the way by which it handles this by using different algorithms for collecting the various heap regions. The JVM switch for this is specified as -XX:+UseConcMarkSweepGC

CMS incremental mode

In this the CMS competes with the CPU cores to perform the GC. The GC thread and application thread works in parallel and in modern day hardware IMHO this is good option. The JVM switch for this is specified as -XX:+CMSIncrementalMode

G1 Garbage Collector

New generation collection mode introduced as part of JVM 1.6. For more details you can find the link to a blog by Alexey Ragozin. The JVM switch for this is specified as -XX:+UseG1GC

Adaptive Size Policy in Detail

Now coming to the main point in this blog, “Adaptive Size Policy”. Since now you have a good idea of the various basics with respect to JVM Heap and JVM GC options, I would be able to explain this concept much easily.

By defining adaptive size policy in a JVM, you are commanding the JVM to adapt itself to the surrounding environment by dynamically re-sizing the heap and its regions so as to attain certain goals already set as follows:

  • Minimize the footprint created by the heap
  • Adhere to the maximum garbage collection JVM pause as desired
  • Adhere to the minimum garbage collection throughput goal as desired

As detailed in the earlier section, to enable this set the JVM switch as follows:

-XX:+UseAdaptiveSizePolicy

To set the desired policy values, you can use the following switches:

-XX:MxGCPauseMillis=nnn – Tells the VM that maximum of nnn milliseconds on less is desired

-XX:GCTimeRatio=nnn – The ratio of GC time to application time

Ideally if you specify the -Xms value to be equal to -Xmx, adaptive size policy is nullified. In cases this might be desirable, but in most of the cases believing the engineers behind this algorithm will surely make your application perform faster and in no case IMHO this should be done whereby a feature is nullified as good amount of research and experience is employed while designing and developing it.

Note:-

Its good to not that options beginning with -X are non-standard, means, need not be supported by all the VM vendors in the market and these are subject to change according to vendor discretion. The options beginning with -XX are non-stable and similar to -X, these are subject to change without notice.

GURU’s with regards to this topic – References

Good Primer – http://blog.ragozin.info/2011/12/garbage-collection-in-hotspot-jvm.html

In simple words – http://www.informit.com/guides/content.aspx?g=java&seqNum=27

Java Hotspot VM options – http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html

Complete list of -XX options for Java JVM – http://stas-blogspot.blogspot.co.uk/2011/07/most-complete-list-of-xx-options-for.html

That’s all folks. Thanks once again for all the reference materials, which helped to me learn these concepts and write this blog.

Page Visitors: 3196

Spring Integration Vs. Apache Camel

The debate on which integration technology to use namely Spring Integration versus Apache Camel is one of the prominent topic now a days similar to mobile web application versus native mobile apps.

I don’t have any bias towards either Camel or Spring but for judgmental reasons I wanted to know which one to choose when given a chance in one of my projects. While doing so I did good amount of net surfing, and this blog post is an effort from my end to consolidate all the points that I could see in the internet. I have indeed plagiarized certain very good points from various blogs while doing so and some of the prominent blogs I have given as reference. Over the course of time I will be updating the blog post with more details as and when I find time.

Note: – I still haven’t been able to find an answer to my question and I am still using both co-jointly in my application. When using a connector I still don’t have a clear picture whether to use Spring connector or Camel connector.

Apache Camel – is a powerful open source integration framework based on known Enterprise Integration Patterns.

Spring Integration – It provides an extension to the Spring Framework to support the well-known Enterprise Integration Patterns while using the principles of Spring programming model.

Apache Camel as well as Spring Integration provides a lightweight alternative to ESB (Enterprise Service Bus), focusing on the programming model in such a way that the developer spends less time with infrastructural boilerplate.

 

 


Comparison from ohloh.net for the two projects:-

  • Camel has a total connector counts of >130 in all which does outscore Spring Integration by a great deal with Spring Integration catching up with every release. +1 Camel
  • Both are using Apache License version 2.0 which states, you can do whatever you want with the code. +1 Camel +1 Spring Integration.
  • Both projects have good activity with good amount of commits from good amount of committers. Camel does have an edge though over the number of commits with respect to Spring Integration. +1 Camel
  • Both started in the year 2007. The effort put for building Camel outscores Spring Integration by large. The lines of code with respect to Camel also outscore Spring Integration by a large distance. +1 Camel for the features it has with respect to lines of code. +1 Spring Integration as code lines cannot be said as a plus point (sometimes less code can be more effective and non-buggy).
  • Vibrant response community of Camel does outscore Spring Integration by a great deal. Might be because of Camel’s focused approach on integration as opposed to Spring’s all in one approach. What it means that most of the problems you face using Camel can be solved quickly by Googling as opposed to Spring Integration. Also the amount of stuff available in the case of Camel does outscore Spring Integration by a great deal as well. + Camel
  • JIRA activity is healthy in the case of Camel as opposed to Spring Integration. Again I see this because of the focused approach of Camel as well as attributed to the vibrant community along with good amount of code lines as compared to Spring Integration. Healthy JIRA activity does mean that turnaround time for a bug is quick in the case of Camel as compared to Spring Integration. +1 Camel
  • CamelOne conference for Camel and none for Spring Integration. Again this can be attributed to non-focus nature of Spring Framework as a whole as compared to Camel. +1 Camel
  • Both has good amount of tooling support in the form of STS and Fuse IDE. +1 Camel +1 Spring Integration
  • Both have commercial support and good amount of 3rd party consultants who are ready to help if you have more money to shell. +1 Camel +1 Spring Integration
  • Camel supports other DSL’s (Domain Specification Language) to a greater extend as compared with Spring Integration (ease of use and learn). +1 Camel

There is a very good presentation from Kai Wähner (Twitter: @KaiWaehner), which he presented in CamelOne Conference 2012, which does cover good amount of points and below is the slideshare details which he has shared. A well-documented comparison between various integration options available today on the Java (JVM) Platform. The author has played it safe similar to me by not giving a final verdict, but it will definitely help you to take into considerations and according to your application requirement take a right choice.

Some conclusions which can help the final decision:-

  • If you already have a Spring application which requires an integration layer, definitely Spring Integration is a good choice to make. If you have a non-spring application, using/introducing Camel as the integration layer would be really the way to go.

I don’t want to take any credit away from authors who has taken pain in doing this research. That’s the reason I would like to put the reference as the first section in my blog. I have gone through various blogs, tutorials and then compiled a blog in a focused and easy to understand manner.

References

http://www.ofbizian.com/2012/12/spring-integration-22-is-out-it-is-time.html

One of the post from Mark Fisher will surely give an insight into the reason behind developing Spring Integration – http://www.coderanch.com/t/568364/Spring/Camel-Spring-Integration-Part

http://www.kai-waehner.de/blog/2012/01/10/spoilt-for-choice-which-integration-framework-to-use-spring-integration-mule-esb-or-apache-camel/

Page Visitors: 5375

Basic Java FAQ – Part 3

101) What is RMI architecture?

Ans: – RMI architecture consists of four layers and each layer performs specific functions:

a) Application layer —- contains the actual object definition

b) Proxy layer —- consists of stub and skeleton

c) Remote Reference layer —- gets the stream of bytes from the transport layer and sends it to the proxy layer

d) Transportation layer —- responsible for handling the actual machine-to-machine communication

102) What is UnicastRemoteObject?

Ans: All remote objects must extend UnicastRemoteObject, which provides functionality that is needed to make objects available from remote machines.

103) Explain the methods, rebind( ) and lookup() in Naming class?

Ans: rebind( ) of the Naming class(found in java.rmi) is used to update the RMI registry on the server machine.

Naming. rebind(“AddSever”, AddServerImpl);

lookup( ) of the Naming class accepts one argument, the rmi URL and returns a reference to an object of type AddServerImpl.

104) What is a Java Bean?

Ans: A Java Bean is a software component that has been designed to be reusable in a variety of different environments.

105) What is a Jar file?

Ans: Jar file allows to efficiently deploying a set of classes and their associated resources. The elements in a jar file are compressed, which makes downloading a Jar file much faster than separately downloading several uncompressed files.

The package java.util.zip contains classes that read and write jar files.

106) What is BDK?

Ans: BDK, Bean Development Kit is a tool that enables to create, configure and connect a set of set of Beans and it can be used to test Beans without writing a code.

107) What is JSP?

Ans: JSP is a dynamic scripting capability for web pages that allows Java as well as a few special tags to be embedded into a web file (HTML/XML, etc). The suffix traditionally ends with .jsp to indicate to the web server that the file is a JSP files. JSP is a server side technology – you can’t do any client side validation with it.

The advantages are:

a) The JSP assists in making the HTML more functional. Servlets on the other hand allow outputting of

HTML but it is a tedious process.

b) It is easy to make a change and then let the JSP capability of the web server you are using deal with compiling it into a servlet and running it.

108) What are JSP scripting elements?

Ans: JSP scripting elements lets to insert Java code into the servlet that will be generated from the current JSP page. There are three forms:

a) Expressions of the form <%= expression %> that are evaluated and inserted into the output,

b) Scriptlets of the form <% code %> that are inserted into the servlet’s service method, and

c) Declarations of the form <%! Code %> that are inserted into the body of the servlet class, outside of any existing methods.

109) What are JSP Directives?

Ans: A JSP directive affects the overall structure of the servlet class. It usually has the following form:

<%@ directive attribute=”value” %>

However, you can also combine multiple attribute settings for a single directive, as follows:

<%@ directive attribute1=”value1″

attribute 2=”value2″

attributeN =”valueN” %>

There are two main types of directive: page, which lets to do things like import classes, customize the servlet superclass, and the like; and include, which lets to insert a file into the servlet class at the time the JSP file is translated into a servlet

110) What are Predefined variables or implicit objects?

Ans: To simplify code in JSP expressions and scriptlets, we can use eight automatically defined variables, sometimes called implicit objects. They are request, response, out, session, application, config, pageContext, and page.

111) What are JSP ACTIONS?

Ans: JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Available actions include:

112) How do you pass data (including JavaBeans) to a JSP from a servlet?

Ans: (1) Request Lifetime: Using this technique to pass beans, a request dispatcher (using either “include” or forward”) can be called. This bean will disappear after processing this request has been completed.

Servlet:

request.setAttribute(“theBean”, myBean);

RequestDispatcher rd = getServletContext().getRequestDispatcher(“thepage.jsp”);

rd.forward(request, response);

JSP PAGE:

(2) Session Lifetime: Using this technique to pass beans that are relevant to a particular session

(such as in individual user login) over a number of requests. This bean will disappear when the

session is invalidated or it times out, or when you remove it.

Servlet:

HttpSession session = request.getSession(true);

session.putValue(“theBean”, myBean);

/* You can do a request dispatcher here,

or just let the bean be visible on the

next request */

JSP Page:

3) Application Lifetime: Using this technique to pass beans that are relevant to all servlets and JSP pages in a particular app, for all users. For example, I use this to make a JDBC connection pool object available to the various servlets and JSP pages in my apps. This bean will disappear when the servlet engine is shut down, or when you remove it.

Servlet:

GetServletContext(). setAttribute(“theBean”, myBean);

JSP PAGE:

113) How can I set a cookie in JSP?

Ans: response.setHeader(“Set-Cookie”, “cookie string”);

To give the response-object to a bean, write a method setResponse

(HttpServletResponse response)

– to the bean, and in jsp-file:

<%

bean.setResponse (response);

%>

114) How can I delete a cookie with JSP?

Ans: Say that I have a cookie called “foo,” that I set a while ago & I want it to go away. I simply:

<%

Cookie killCookie = new Cookie(“foo”, null);

KillCookie.setPath(“/”);

killCookie.setMaxAge(0);

response.addCookie(killCookie);

%>

115) How are Servlets and JSP Pages related?

Ans: JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed.

Page Visitors: 254