EzDevInfo.com

jsp interview questions

Top jsp frequently asked interview questions

How do you import classes in JSP?

I am a complete JSP beginner. I am trying to use a java.util.List in a JSP page. What do I need to do to use classes other than ones in java.lang?


Source: (StackOverflow)

Difference between getAttribute() and getParameter()

What is the difference between getAttribute() and getParameter() methods within HttpServletRequest class?


Source: (StackOverflow)

Advertisements

How to submit form on change of dropdown list?

I am creating a page in JSP where I have a dropdown list and once the user selects a value he has to click on the go button and then the value is sent to the Servlet.

            </select>
            <input type="submit" name="GO" value="Go"/>

How do I make it so that it does it on change? E.g. when the user selects John all his details are retrived from the DB and displayed. I want the system to do it without having to click the go button.


Source: (StackOverflow)

Design Patterns web based applications

I am designing a simple web based application. I am new to this web based domain.I needed your advice regarding the design patterns like how responsibility should be distributed among Servlets, criteria to make new Servlet, etc.

Actually I have few entities on my home page and corresponding to each one of them we have few options like add, edit and delete. Earlier I was using one Servlet per options like Servlet1 for add entity1, Servlet2 for edit entity1 and so on and in this way we ended up having a large number of servlets.

Now we are changing our design. My question is how you exactly choose how you choose the responsibility of a servlet. Should we have one Servlet per entity which will process all it's options and forward request to service layer.Or should we have one servlet for the whole page which will process the whole page request and then forward it to corresponding service layer.Also should the request object forwarded to service layer or not.

Please you guide us in choosing the best design.Also any pointer to a good design pattern material will be welcome.


Source: (StackOverflow)

Access Enum value using EL with JSTL

I have an Enum called Status defined as such:

public enum Status { 

    VALID("valid"), OLD("old");

    private final String val;

    Status(String val) {
        this.val = val;
    }

    public String getStatus() {
        return val;
    }

}

I would like to access the value of VALID from a JSTL tag. Specifically the test attribute of the <c:when> tag. E.g.

<c:when test="${dp.status eq Status.VALID">

I'm not sure if this is possible, so any help would be much appreciated.


Source: (StackOverflow)

I never really understood: what is CGI?

CGI is a Common Gateway Interface. As the name says, it is a "common" gateway interface for everything. It is so trivial and naive from the name. I feel that I understood this and I felt this every time I encountered this word. But frankly, I didn't. I'm still confused.

I am a PHP programmer. I did lot of web development.

user (client) request for page ---> webserver(->embedded PHP interpreter) ----> Server side(PHP) Script ---> MySQL Server.

Now say my PHP Script can fetch results from MySQL Server && MATLAB Server && Some other server.

So, now PHP Script is the CGI? because its interface for the between webserver & All other servers? I don't know. Sometimes they call CGI, a technology & othertimes they call CGI a program or someother server.

  • What exactly is CGI?

  • Whats the big deal with /cgi-bin/*.cgi? What's up with this? I don't know what is this cgi-bin directory on the server for. I don't know why they have *.cgi extensions.

  • Why does Perl always comes in the way. CGI & Perl (language). I also don't know what's up with these two. Almost all the time I keep hearing these two in combination "CGI & Perl". This book is another great example CGI Programming with Perl. Why not "CGI Programming with PHP/JSP/ASP"? I never saw such things.

  • CGI Programming in C, confuses me a lot. "in C"?? Seriously?? I don't know what to say. I'm just confused. "in C"?? This changes everything. Program needs to be compiled and executed. This entirely changes my view of web programming. When do I compile? How does the program gets executed (because it will be a machine code, so it must execute as a independent process). How does it communicate with the web server? IPC? and interfacing with all the servers (in my example MATLAB & MySQL) using socket programming? I'm lost!!

  • They say that CGI is depreciated. Its no more in use. Is it so? What is its latest update?

Once, I ran into a situation where I had to give HTTP PUT request access to web server (Apache HTTPD). Its a long back. So, as far as I remember this is what I did:

  1. Edited the configuration file of Apache HTTPD to tell webserver to pass all HTTP PUT requests to some put.php ( I had to write this PHP script)

  2. Implement put.php to handle the request (save the file to the location mentioned)

People said that I wrote a CGI Script. Seriously, I didn't have a clue what they were talking about.

  • Did I really write CGI Script?

I hope you understood what my confusion is. (Because I myself don't know where I'm confused). I request you guys to keep your answer as simple as possible. I really can't understand any fancy technical terminology. At least not in this case.

EDIT:

I found this amazing tutorial "CGI Programming Is Simple!" - CGI Tutorial, which explains the concepts in simplest possible way. After reading this article you may want to read Getting Started with CGI Programming in C to supplement your understanding with actual code samples. I've also added these links to this tutorial to Wikipedia's article : http://en.wikipedia.org/wiki/Common_Gateway_Interface


Source: (StackOverflow)

How to upload files to server using JSP/Servlet?

How can I upload files to server using JSP/Servlet? I tried this:

<form action="upload" method="post">
    <input type="text" name="description" />
    <input type="file" name="file" />
    <input type="submit" />
</form>

However, I only get the file name, not the file content. When I add enctype="multipart/form-data" to the <form>, then request.getParameter() returns null.

During research I stumbled upon Apache Common FileUpload. I tried this:

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request); // This line is where it died.

Unfortunately, the servlet threw an exception without a clear message and cause. Here is the stacktrace:

SEVERE: Servlet.service() for servlet UploadServlet threw exception
javax.servlet.ServletException: Servlet execution threw an exception
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:313)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:637)

Source: (StackOverflow)

Download a file by jQuery.Ajax

I have a Struts2 action in the server side for file downloading.

<action name="download" class="com.xxx.DownAction">
    <result name="success" type="stream">
        <param name="contentType">text/plain</param>
        <param name="inputName">imageStream</param>
        <param name="contentDisposition">attachment;filename={fileName}</param>
        <param name="bufferSize">1024</param>
    </result>
</action>

However when I call the action using the jQuery:

$.post(
  "/download.action",{
    para1:value1,
    para2:value2
    ....
  },function(data){
      console.info(data);
   }
);

in Firebug I see the data is retreived with the Binary stream. I wonder how to open the file downloading window with which the user can save the file locally?


Source: (StackOverflow)

Java web development, what skills do I need? [closed]

I want to learn, at least at a basic level, how to build Java web applications (coming from a .NET background).

Meaning, I would like to be able to build, deploy a simple CMS type application from the ground up.

What exactly do I need to learn?

Tomcat seems to be a good web server for Java.

What options are there for the web? I know there is Hibernate for an ORM.

Does Java have MVC? What about JSP? Can MVC and JSP be together? NetBeans?

Maybe a book that covers all of these?


Source: (StackOverflow)

if...else within JSP or JSTL

I have a kind of open-ended question..

I want to have a HTML code based on condition (desktop/ipad)..say Condition 1/Condition 2

I want to have separate HTML snippets for each of these conditions...

if (Condition 1)
Some HTML code for con1
else if (Condition 2)
Some HTML code for con2

The condition I want to test (in JS) is;

var isiPad = navigator.userAgent.match(/iPad/i) != null;
if (isiPad)
{}
else
{}

Now this has to be implemented in a .jsp page...

So how do I do that? Should I use JSTL ? What is the best way?

The main thing is that only corresponding code should actually be loaded/rendered e.g. if condition 1 is true, the HTML code in condition 2 should not be executed at all (apart from being hidden in the browser)


Source: (StackOverflow)

Servlet for serving static content

I deploy a webapp on two different containers (Tomcat and Jetty), but their default servlets for serving the static content have a different way of handling the URL structure I want to use (details).

I am therefore looking to include a small servlet in the webapp to serve its own static content (images, CSS, etc.). The servlet should have the following properties:

  • No external dependencies
  • Simple and reliable
  • Support for If-Modified-Since header (i.e. custom getLastModified method)
  • (Optional) support for gzip encoding, etags,...

Is such a servlet available somewhere? The closest I can find is example 4-10 from the servlet book.

Update: The URL structure I want to use - in case you are wondering - is simply:

    <servlet-mapping>
            <servlet-name>main</servlet-name>
            <url-pattern>/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
            <servlet-name>default</servlet-name>
            <url-pattern>/static/*</url-pattern>
    </servlet-mapping>

So all requests should be passed to the main servlet, unless they are for the static path. The problem is that Tomcat's default servlet does not take the ServletPath into account (so it looks for the static files in the main folder), while Jetty does (so it looks in the static folder).


Source: (StackOverflow)

Include another JSP file

I am currently trying to learn JSP. My question is, at present I used to include the header and footer of the page using:

<%@include file="includes/header.jsp" %>

and

<%@include file="includes/footer.jsp" %>

But now, I have separated the page content also. So, if user clicks on a page, say products, it has to load the JSP file which is situated in: includes/pages/products.jsp So, the link to the user is like: <a rel='nofollow' href="index.jsp?p=products">Products</a>.

So, I have to get the p value and display the page based on it.

Following is what I have done so far.

<%
 if(request.getParameter("p")!=null)
 { 
   String p = request.getParameter("p");
%>    

<%@include file="includes/page_name.jsp" %>

<% 
 }
%>

So, how do I place the value of variable "p" in position of "page_name" ?

Or, is there any other method that I could use ?

In PHP, we could use the include() or include_once(). I am bit stuck in this JSP. :(

Thanks in advance. :)


Source: (StackOverflow)

What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files?

It seems that there are two methods for templating with JSP. Including files with one of these statements

<%@ include file="foo.html" %>
<jsp:include page="foo.html" />

or using JSP tag files

// Save this as mytag.tag
<%@ tag description="Description" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
    <jsp:doBody/>
</body>
</html>

And in another JSP page call it with

<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:mytag>
    <h1>Hello World</h1>
</t:mytag>

So which method should I use? Is one now considered deprecated or are they both valid and cover different use cases?

Edit

Isn't using this tag file the same as using an include?

// Save this as product.tag
<%@ tag description="Product templage" pageEncoding="UTF-8"%>
<%@ tag import="com.myapp.Product" %>
<%@ attribute name="product" required="true" type="com.myapp.Product"%>

Product name: ${product.name} <br/>
Quantity: ${product.quantity} <br/>

And call it on another JSP with

<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:product>
    <c:forEach items="${cart.products}" var="product">
        <t:product product="${product}"/>
    </c:forEach>
</t:product>

That seems to me to be the very same as using an include and passing parameters to it. So are Tag Files the same as includes?


Source: (StackOverflow)

JSF vs Facelets vs JSP [duplicate]

This question already has an answer here:

I can't seem to get a clear answer as to the concrete difference between Java Server Faces vs. so-called facelets. Can anyone give me a clear-as-day answer?!?

Also, I understand that either JSF or JSP can be used to create dynamic web pages, but two seemingly-conflicting details are confusing me. I've heard both of the following:

  1. That JSF is a replacement for JSP; and

  2. JSF and JSP form different parts of the View in Java's web-tier MVC paradigm

So which is it? Logic dictates it almost certainly can't be both!


Source: (StackOverflow)

How to get parameters from the URL with JSP

In JSP how do I get parameters from the URL?

For example I have a URL www.somesite.com/Transaction_List.jsp?accountID=5
I want to get the 5.

Is there a request.getAttribute( "accountID" ) like there is for sessions or something similar?


Source: (StackOverflow)