Showing posts with label JSP Servlet. Show all posts
Showing posts with label JSP Servlet. Show all posts

Wednesday, July 21, 2021

Difference Between JSP and Servlets

JSP, Servlets, Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Oracle Java Career

JSP vs Servlets

A Servlet is a server side software component written in Java and runs in a compatible container environment known as a Servelt container (like Apache Tomcat). Servlets are predominantly used in implementing web applications that generate dynamic web pages. They can however generate any other content type like XML, text, images, sound clips, PDF, Excel files programmatically.

A Servlet written to generate some HTML may look like this:

public class MyServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

PrintWriter w = response.getWriter();

w.write(“<html>”);

w.write(“<body>”);

Date d = new Date();

w.write(d.toString());

w.write(“</body>”);

w.write(“</html>”);

}

}

JSP, Servlets, Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Oracle Java Career
The code above contains a mixture of HTML and Java source code. Such is not very readable and maintainable. JSP which stands for JavaServer Pages provides a better alternative. For example, the following is a fragment of JSP code that results in identical output:

<%@page import=”java.util.Date”%>

<html>

<body>

<%= new Date().toString() %>

</body>

</html>

Web page authors find JSP easier to write and maintain. JSP files are however translated into Servlets by a Servlet container at the time JSP files are first accessed. However, business logic writers find Servlets to be easier to work with.

A request received by a web application should trigger the execution of some business logic and then generate a resultant web page as the response. In modern day web applications, controlling the overall request processing cycle is mostly handed by Servlets. As the last stage in processing a request, such a Servlet generally hands over the responsibility of generating the dynamic HTML to a JSP.

Saturday, April 11, 2020

10 examples of displaytag in JSP, Struts and Spring

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Guides, Oracle Java Prep

Display tag is one of the best free open source libraries for showing data in tabular format in a J2EE application using jsp, struts or spring. it is shipped as tag library so you can just include this  in your jsp and add corresponding jar and there dependency in class-path and you are ready to use it. Display tag is my favorite solution for displaying any tabular data because of its inherent capability on paging and sorting. It provides great support for pagination on its own but it also allows you to implement your own pagination solution. On Sorting front you can sort your data based on any column, implement default sorting etc.

There is so much resource available on using display tag including examples, demos, and guides. In this article, we will see some important points to note while using display tag in jsp. Though this library is very stable and rich in functionality still there are some subtle things which matter and if you don't know you could potentially waste hours to fix those things. These are the points I found out while I was using displaytag in my project and I have listed those down here for benefits of all.

displaytag examples


I have outlined all the examples based upon task I had to perform and due to those tasks, I discovered and get myself familiar with display tag. It’s my personal opinion that task-based approach works better in terms of understanding something than feature based. It’s simply easy for the mind to understand the problem first and then a solution.

1) Provide UID while using two tables in one page.


In many scenarios, we need to show two separate tables in one jsp page. We can do this by using two tags easily but the catch is that sorting will not work as expected. When you sort one table, the second table will automatically sort or vice-versa. To make two tables independent of each other for functionality like exporting and sorting you need to provide "uid" attribute to table tag as shown below. I accidentally found this when I encounter sorting issue on display tag.

<displaytag:table name="listofStocks" id="current_row" export="true" uid="1">
<displaytag:table name="listofStockExchanges" id="current_row" export="true" uid="2">

just make sure "uid" should be different for each table.

2) Displaytag paging request starts with "d-"


There was a bug in one of our jsp which shows data using displatag, with each paging request it was reloading data which was making it slow. Then we thought to filter out displaytag paging request and upon looking the pattern of displaytag paging request we found that it always starts with "d-", so by using this information you can filter out display tags paging request. Since we were using spring it was even easier as shown in below

Example:

Map stockParamMap = WebUtils.getParametersStartingWith(request, "d-");
if(stockParamMap.size() !=0){
out.println("This request is displaytag pagination request");
}

3) Getting reference to current row in display tag


Many times we require reference of current row while rendering display tag data into a jsp page. In our case we need to get something from currentRow and then get Something from another Map whose key was value retrieved from current row, to implement this, of course, we some how need a reference of the current row in display tag. After looking online and displaytag.org we found that by using "id" attribute we can make current row reference available in pageScope. Name of variable would be the value of "id" attribute, this would be much clear by seeing below example:

<displaytag:table name="pennyStocks" id="current_penny_stock" export="true" uid="1">

<di:column title="Stock Price" value="${pennyStockPrice[current_penny_stock.RIC]}" sortable="true" />

This way we are displaying stock price from pennyStockPrice Map whose key was RIC(Reuters Information Code) of penny Stock. You see name of variable used to refer current row is "current_penny_stock"

4) Formatting date in displaytag in JSP


Formatting date and numbers are extremely easy in display tag, you just need to specify a "format" attribute with <displaytag:column> tag and value of this tag would be date format as we used in SimpleDateFormat in Java. In Below example, I am showing date in "yyyy-MM-dd" format.

<di:column title="Stock Settlement Date" property="settlementDate" sortable="true" format="{0,date,yyyy-MM-dd}" />

You can also implement your own table decorator or column decorator but I found this option easy and ready to use.

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Guides, Oracle Java Prep

5) Sorting Columns in display tag


Again very easy you just need to specify sortable="true" with <displaytag:column> tag and display tag will make that column sortable. Here is an example of a sortable column in display tag.

<di:column title="Stock Price" property="stockPrice" sortable="true" />

6) Making a column link and passing its value as a request parameter.


Some time we need to make a particular columns value as link may be to show another set of data related to that value. we can do this easily in display tags by using "href" attribute of <displaytag:column> tag, value of this attribute should be path to target url.If you want to pass value as request parameter you can do that by using another attribute called "paramId", which would become name of request parameter.

Here is an example of making a link and passing the value as the request parameter in display tags.

<di:column property="stockSymbol"  sortable="true" href="details.jsp" paramId="symbol"/>

7) Default sorting and ordering in displaytag


If you want that your table data is by default sorted based upon a particular column when displayed then you need to defaine a column name for default sorting and an order e.g. ascending or descending. You can achieve this by using attribute "defaultsort" and "defaultorder" of <displaytag:table> tag as shown in below example.

<displaytag:table name="pennyStocks" id="current_penny_stock" export="true" defaultsort="1" defaultorder="descending" uid="1">

This will display table which would be sorted on the first column in descending order.

8) Sorting whole list data as compared to only page data in display tag


This was the issue we found once we done with our displaytag jsp. we found that whenever we sort the table by clicking on any sortable column header it only sort the data visible on that page, it was not sorting the whole list provided to display tag I mean data which was on other pages was left out. That was not the desirable action for us. Upon looking around we found that display tag by default sort only current page data but you can override this behavior by providing a displaytag.properties file in classpath and including below line in

displaytag.properties:
sort.amount = list

9) Configuring displaytag by using displaytag.properties


This was an important piece of information which we are not aware until we hit by above-mentioned the issue. Later we found that we can use displaytag.properties to customize different behaviors, appearence of displaytag. Another good behavior we discoved was showing empty table if provided list is null or empty. You can achieve this by adding line "basic.empty.showtable = true". Here was how our properties file looks like

//displaytag.properties
sort.amount = list
basic.empty.showtable = true
basic.msg.empty_list=No results matched your criteria.
paging.banner.placement=top

10) Specifying pagesize for paging in a JSP


You can specify how many rows you want to show in one page by using "pagesize" attribute of <displaytag:table>. We prefer to use it from configuration because this was subject to change.

Monday, February 17, 2020

Difference between include directive, include action and JSTL import tag in JSP?

Oracle Java Tutorial and Materials, Oracle Java Certification, Oracle Java JSTL, Oracle Java Prep

There are three main ways to include the content of one JSP into another:

include directive

JSP include action

and JSTL import tag

The include directive provides static inclusion. It ads content of the resource specified by its file attribute, which could be HTML, JSP or any other resource at translation time.

Any change you make in the file to be included after JSP is translated will not be picked up by include directive.

Since JSP is translated only once but can be requested many times it's not a very useful option. It was originally intended to include static contents like HTML header and footer for a web page.

The main difference between include directive and include action is that JSP includes action provides dynamic inclusion.

The content of another JSP or HTML page is included at request time, which any change you make in the file to be included will be visible to another JSP when requested.

This is ideal if you are importing content from dynamic resources like another JSP page. The file to be included is specified by page attribute of jsp: include tag.

Third option to include the output of one JSP page into another is JSTL import tag. This works pretty much like include action but the main difference between import tag and includes action is that import tag can include resources from the outside world.

If you use include directive or include action you are only limited to include the output of resource from the same project or another web application residing in the same container.

It is the most powerful and flexible way to include the content of one JSP to another. The file to be included is specified by url attribute of import tag.

Oracle Java Tutorial and Materials, Oracle Java Certification, Oracle Java JSTL, Oracle Java Prep

In short

1) The main difference between include directive and include action is that the former is static include while later is dynamic include. Also former uses file attribute to specify the location of the resource to be include while later uses page attribute.

3) The key difference between include action and JSTL import tag is that former can only include local resources but later can also include the output of remote resources, JSP pages or HTML pages outside the web container. include action uses page attribute while import tag uses URL attribute.

That's all on the difference between include direction, include action and JSTL import tag in JSP.

Thursday, January 30, 2020

Difference between SendRedirect() and Forward() in JSP Servlet

Java SendRedirect(), Java Forward(), JSP Servlet, Oracle Java Tutorial and Material

Difference between SendRedirect and forward is one of classical interview questions asked during java web developer interview. This is not just applicable for servlet but also for JSP in which we can use forward action or call sendRedirect() method from scriptlet. Before examining difference on forward and SendRedirect let’s see what send Redirect method and forward method does.

SendRedirect (): 

This method is declared in HttpServletResponse Interface.

Signature: void sendRedirect(String url)

This method is used to redirect client request to some other location for further processing ,the new location is available on different server or different context.our web container handle this and transfer the request using  browser ,and this request is visible in browser as a new request. Some time this is also called as client side redirect.

Forward():

This method is declared in RequestDispatcher Interface.

Signature: forward(ServletRequest request, ServletResponse response)
This method is used to pass the request to another resource for further processing within the same server, another resource could be any servlet, jsp page any kind of file.This process is taken care by web container when we call forward method request is sent to another resource without the client being informed, which resource will handle the request it has been mention on requestDispatcher object which we can get by two ways either using ServletContext or Request. This is also called server side redirect.

RequestDispatcher rd = request.getRequestDispatcher("pathToResource");
  rd.forward(request, response);

Or

RequestDispatcher rd = servletContext.getRequestDispatcher("/pathToResource");
  rd.forward(request, response);

Difference between SendRedirect and Forward


Now let’s see some difference between these two method of servlet API in tabular format.

Forward() SendRediret() 
When we use forward method request is transfer to other resource within the same server for further processing. In case of sendRedirect request is transfer to another resource to different domain or different server for futher processing.
In case of forward Web container handle all process internally and client or browser is not involved.  When you use SendRedirect container transfers the request to client or browser so url given inside the sendRedirect method is visible as a new request to the client.
When forward is called on requestdispather object we pass request and response object so our old request object is present on new resource which is going to process our request In case of SendRedirect call old request and response object is lost because it’s treated as new request by the browser.
Visually we are not able to see the forwarded address, its is transparent In address bar we are able to see the new redirected address it’s not transparent.
Using forward () method is faster then send redirect.  
SendRedirect is slower because one extra round trip is required beasue completely new request is created and old request object is lost.Two browser request requird.
When we redirect using forward and we want to use same data in new resource we can use request.setAttribute () as we have request object available. But in sendRedirect if we want to use we have to store the data in session or pass along with the URL.

Example of forward and SendRedirect in JSP Servlet:


Any kind of online payment when we use merchant site will redirect us to net banking site which is completely new request it process our request and again redirect to merchant site?

In Banking Application when we do login normally we use forward method. In case of online banking we are asked for username and password if it’s a correct some another servlet or resource will handle the request other wise request has been forwarded to error page.

Which one is good?


Its depends upon the scenario that which method is more useful.

If you want control is transfer to new server or context and it is treated as completely new task then we go for Send Redirect.
 
Normally forward should be used if the operation can be safely repeated upon a browser reload of the web page will not affect the result.

SendRedirect and forward method are still very useful while programming or working on any web application project using servlet jsp. This is still a popular interview questions so don’t forget to revise forward and sendRedirect before appearing for any job interview.