Set 24 – Servlets, JSP, JSTL Interview Questions

1. What is the userName value printed if the html input field “user” does not exist.
Choose the right option.

import javax.servlet.*;	import javax.servlet.http.*;    import java.io.*;
public class Demo extends HttpServlet
{
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        PrintWriter out = response.getWriter();
        String userName = request.getParameter("user");        
        out.println(userName);
    }
}

1. null
2. empty string
3. raises exception
4. none above

2. Choose all the right options fit for the blank to compile successfully and send response to client in the following servlet.

a) HTML code

  
Enter Employee Name

b) Servlet code

import javax.servlet.*;	   import javax.servlet.http.*;    import java.io.*;
public class DemoServlet extends GenericServlet
{
    public void service(ServletRequest req, ServletResponse res) throws ServletException, 
IOException
    {
        String empname = req.getParameter("nameField");
        ---------------------------------      // blank
        out.println(empname);
        out.close();
    }
}  

1. PrintWriter out = res.getWriter();
2. ServletOutputStream out = res.getOutputStream();
3. PrintStream out = res.getOutputStream();
4. OutputStreamWriter out = res.getOutputStreamWriter();

3. Choose the right option that is true regarding the following servlet.

import javax.servlet.*;	   import javax.servlet.http.*;    import java.io.*;
public class DemoServlet extends GenericServlet
{
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws 
ServletException, IOException
    {
        PrintWriter out = res.getWriter();       
        out.println("Your password is " + req.getParameter("password")); 
        out.close();
    }
}

1. the servlet code does not compile
2. the servlet code compiles successfully
3, compiles but throws exceptions at runtime
4. none above

4. Choose all the right options that are true for the following servlet code.

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;
public class DemoServlet extends HttpServlet
{
    public void service(HttpServletRequest req, HttpServletResponse res) throws 
ServletException, IOException
    {
         res.setContentType("text/html");
         PrintWriter out = res.getWriter();
         out.println("");
         out.println("");  
         out.println("");
         out.println("
BookRate
"); out.close(); } }

1. Above code sends HTML table to client created dynamically.
2. Table does not occupy complete width of the browser
3. HTML can be embedded in a servlet to create a view
4. none above

5. What could be the right URL mapping in the web.xml for the following servlet.
Choose all the right options.

public class Validate extends HttpServlet { }

1. <servlet-mapping>
<servlet-name>xxxx</servlet-name>
<url-pattern>/roses/*</url-pattern>
</servlet-mapping>

2. <servlet-mapping>
<servlet-name>Validate</servlet-name>
<url-pattern>/roses/*</url-pattern>
</servlet-mapping>

3. <servlet-mapping>
<servlet-class>Validate</servlet-class>
<url-pattern>/roses/*</url-pattern>
</servlet-mapping>

4. <servlet-mapping>
<servlet-name>xxxx</servlet-name>
<servlet-class>/Validate/*</servlet-class>
</servlet-mapping>

6. Look at the snippet of servlet code and choose the right option for the blank.

import javax.servlet.http.*;    import java.io.*;
public class DemoServlet extends HttpServlet
{
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws 
javax.servlet.ServletException, IOException
    {
          PrintWriter out = res.getWriter();            
          java.util.Enumeration e = req.getParameterNames();    
          while(e.hasMoreElements())
          {
            String name = (String) -------------; // blank here
            String value = req.getParameter(name);
            out.println(name + " : " + value +"
"); } } }

1. e.nextElement();
2. e.next();
3. e.nextToken();
4. e.nextField();

7. Observe at the servlet code.

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;
public class DemoServlet extends HttpServlet
{
    protected void service(HttpServletRequest req, HttpServletResponse res) throws 
ServletException, IOException
    {
        PrintWriter out = res.getWriter();
        out.println("Hello");	
        out.close();
    }
}

In the above servlet setContentType(“text/html”) is not set. Choose all the right options that are true.

1. servlet does not compile due to protected service() method
2. servlet compiles
3. Hello is sent to client in bold and underline
4. Hello is sent to client in plain/text (without HTML parsing)

8. Choose the right option to import java.sql package in JSP.



<%
  Class.forName("oracle.jdbc.driver.OracleDriver");
  Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
  Statement stmt=con.createStatement();
  stmt.executeUpdate("insert into Employee values(100, 'S N Rao', 2000.50)");
  out.println("Record inserted");
  // closing statements here
%>

1. <%@ page import=”java.sql.*” %>
2. <%@ page include=”java.sql.*” %>
3. <%@ include package=”java.sql.*” %>
4. <%@ page package=”java.sql.*” %>

9. Choose all the right options that are true for the following servlet snippet of code.

public void service(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException
{
      response.setContentType("text/html");    
      PrintWriter out = response.getWriter();
      String visitPlace = request.getParameter("place");
      if(visitPlace.trim().equalsIgnoreCase("hyderabad"))
      {
           out.println("

Hyderabad Sightseeing

"); out.println("Shilparamam
"); out.println("Necklace Road"); } else if(visitPlace.trim().equalsIgnoreCase("secunderabad")) { out.println("

Secunderabd Sightseeing

"); out.println("Paiga Palace
"); out.println("Hussain Sagar"); } out.close(); }

1. code does not contain errors and compiles successfully
2. client gets all the sightseeing places depending on the place entered
3. code does not compile due to syntax errors
4. none of above

10. Choose all the right options which are true for the following servlet code.

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;  
public class Servlet1 extends HttpServlet
{
 public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
 {
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  if(request.getParameter("password").trim().equals("tcs"))
  {
    response.sendRedirect("index.jsp");
  }
  else
  {
    out.println("

Login Form

"); out.println("
"); out.println("Enter Password
"); out.println(""); out.println("
"); } } }

1. By chance if password evaluates to false, a dynamic form goes to client.
2. HTML code can be embedded in Servlet.
3. All the response does not go to the client as out object is not closed and thereby complete response is not flushed
4. All are false

11. Choose all right options that can retrieve an object of ResultSet.

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;  import java.sql.*;
public class DemoServlet extends HttpServlet
{
   public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
   {
       try
       {
           Class.forName("oracle.jdbc.driver.OracleDriver");
           Connection con  = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott",  "tiger");
           Statement stmt = con.createStatement();
           ResultSet rs = -------   // blank here
           // JDBC code goes further
       }
       catch(Exception e) {  }
   }
}

1. stmt.executeQuery(“select * from Employee”);
2. stmt.executeQuery(“select empid, empname, empsal from Employee”);
3. stmt.executeUpdate(“select * from Employee”);
4. stmt.executeUpdate(“select empid, empname, empsal from Employee”);

12. Choose all the right options that create an object of PreparedStatement for the table with three columns empid, empname, empsal. Observe the following snippet of code.

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
 try
 {
  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  Connection con = DriverManager.getConnection("jdbc:odbc:snrao", "scott", "tiger");
  PreparedStatement pst   = -----------------   // blank here      
       // JDBC code goes further
   }
   catch(Exception e) {   }
}

1. con.prepareStatement(“insert into table Employee(empid, empname, empsal) values(?, ?, ?)”);
2. con.prepareStatement(“insert values(?, ?, ?) into Employee(empid, empname, empsal)”);
3. con.prepareStatement(“insert into Employee(empid, empname, empsal) values(?, ?, ?)”);
4. con.prepareStatement(“insert into Employee values(?, ?, ?)”);

13. Read the code snippet carefully. Choose all the right options that will compile the servlet successfully.

a) web.xml file snippet


     GoldRate
     3575


     GoldWeight
     25

b) Servlet snippet

import javax.servlet.*;	    import javax.servlet.http.*;      import java.io.*;
public class DemoServlet extends HttpServlet
{
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException
  {
    response.setContentType("text/html");
    ServletConfig config = getServletConfig();

    --------------------------         // blank 1
    -------------------------         // blank 2

    response.getWriter().println("Parameters are " + xyz1 + ", " + xyz2);
  }
}

1. String xyz1 = config.getInitParameter(“GoldRate”);
String xyz2 = config.getInitParameter(“GoldWeight”);

2. String xyz1 = (String) config.getInitParameter(“GoldRate”);
String xyz2 = (String) config.getInitParameter(“GoldWeight”);

3. Object xyz1 = config.getInitParameter(“GoldRate”);
Object xyz2 = config.getInitParameter(“GoldWeight”);

4. StringBuffer xyz1 = config.getInitParameter(“GoldRate”);
StringBuffer xyz2 = config.getInitParameter(“GoldWeight”);

14. Choose all the right options that are true with the following JSP code.

a) HTML code calling Demo.jsp

  
Enter User Name

b) Demo.jsp code


<%
         String str = request.getParameter("userField");
         out.println("Hello Mr." + str + " Best Wishes of the Day");
%>

Hello Sir <%= str %> You are credited with loan amount

1. String object str scope does not exist in expression
2. Compilation error
3. No problem in the code
4. Both messages of scriplet and expression go to client

15. Choose all the right options for the following JSP code.

a) HTML code calling Demo.jsp

  
Enter User Name

b) Demo.jsp code


<%!
        public void jspDestroy()
        {
            out.close();
        }
%>
<%
        out.println("Best Wishes " + request.getParameter("userField"));
%>

1. println() message goes to client
2. No problem in the code
3. Code raises compilation error
4. Error exist in the code

16. Choose all the right options for the following JSP code.


<%!
          String str;                    
          public void jspInit()
          {
              str = "Hello";                    
          }
          public void jspDestroy()
          {
               str = null;
          }
%>
<%
           out.println(str);
%>        

1. code is fine without errors
2. println() message goes to client
3. code is erroneous
4. scope problem exist in code

17. Which statements create an anonymous object of RequestDispatcher and calls the other servlet Servlet2. Choose all the right options.

1. getServletContext().getRequestDispatcher(“/Servlet2”).include(request, response);
2. getServletConfig().getRequestDispatcher(“/Servlet2”).include(request, response);
3. request.getRequestDispatcher(“Servlet2”).include(request, response);
4. response.getRequestDispatcher(“/Servlet2”).include(request, response);

18. Observe the snippet of JDBC code. Choose the right option to affect all the batch statements in database table.

public static void main(String args[]) throws Exception
{
 Class.forName("oracle.jdbc.driver.OracleDriver");
 Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
 Statement stmt=con.createStatement();
 stmt.addBatch("insert into Employee values(100, ‘S N Rao’, 2000.50)");
 stmt.addBatch("Delete from Employee where empsal > 8000");
 stmt.addBatch("update Employee set empsal=empsal+500 where empid=100");
 --------------------------------  // blank
}

Choose the right option that compiles successfully for the above blank.

1. stmt.executeBatch();
2. stmt.executeUpdate();
3. stmt.executeAll();
4. stmt.execute();

19. Choose all the right options that are true for the following code.


 <%
        <%@ include file="abc.html" %>
        
        out.println("Files contents are displayed");
%>

1. include directive cannot be placed in scriptlet
2. include action cannot be placed in scriptlet
3. code is does not contain any errors
4. Client gets the response

20. Choose the right option that is true for the following servlet.
Observe, in the code, both doGet() and service() exist.

a) HTML code calling DemoServlet


b) Servlet code

import javax.servlet.*;    import javax.servlet.http.*;      import java.io.*;
public class DemoServlet extends HttpServlet
{
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException
    {
        HttpSession session = request.getSession();
        session.setAttribute("TCS1", "Hyderabad");
        response.getWriter().println(session.getAttribute("TCS1"));
    }
    public void service(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException
    {
        HttpSession session = request.getSession();
        session.setAttribute("TCS2", "Secunderabad");
        response.getWriter().println(session.getAttribute("TCS2"));
     }
}

1. code does not compile
2. code compiles but throws exception at runtime
3. output will be Hyderabad
4. output will be Secunderabad

21. Choose the right option to fill up the blank that iterate the loop.



 


1. $xyz
2. $xyz$
3. xyz
4. none of above

22. Choose all the right options that are true for the following code.

a) Servlet calling Shopping.jsp

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;  
public class Servlet1 extends HttpServlet
{
 public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
 {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   request.setAttribute("Cost", 2500.50);
   out.println("Hyderabad Shopping Mall
"); out.println("Following are Bill Particulars"); request.getRequestDispatcher("/Shopping.jsp").include(request, response); out.println("Thank you. Visit again"); } }

b) Shopping.jsp


<%
    Object obj1 = request.getAttribute("Cost");
    out.println("
Pay Rs." + obj1 +"
"); %>

1. code compiles and executes successfully
2. client gets the response of both servlet and JSP
3. does not compile as a servlet cannot call a JSP file
4. ‘Cost’ of servlet is not visible from JSP

23. Read the code and choose all the right options that are true about the code.

a) HTML code calling Validate servlet


     
Enter Password

b) Servlet code

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;  
public class Validate extends HttpServlet
{
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String userPass = request.getParameter("password").trim();

        if(userPass.equals("tcs"))
        {
          out.println("

Login Successful

"); } else { out.println("

Login Failed

"); } out.println(""); out.close(); } }

1. code does not compile as HTML cannot be embedded inside println() statements
2. code does not compile due to other errors
3. code compiles successfully as servlet does not contain any errors
4. client browser background color changes as per the validation

24. Imagine there is an Employee table with three fields empid number, empname varchar2(15) and empsal number(6,2). Choose all the right options to fill the three blanks that print all the records.


<%
try
{
  // loaded the driver and Connection con object is created
  Statement stmt = con.createStatement();
  ResultSet res = stmt.executeQuery("select * from Employee");       
  while(res.next())    
  {     	         
    out.println(----- + " " + ----- + " " + ----- + "
"); // three blanks here } // clean up code goes here } catch(Exception e) { out.println("Problem in database access: " + e); } %>

1. res.getInt(1), res.getString(2), res.getDouble(3)
2. res.getInt(“empid”), res.getString(“empname”), res.getDouble(“empsal”)
3. res.getString (1), res.getString(2), res.getString (3)
4. res.getString (“empid”), res.getString(“empname”), res.getString (“empsal”)

25. Choose the right option to fill up the blank that compiles successfully.

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;  
public class Servlet1 extends HttpServlet
{
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        session.setAttribute("cost", 45);
        session.setAttribute("tax", 10.5);
        session.setAttribute("gst", "15");

        --------------------------------        // blank here
        while(e.hasMoreElements())
        {
           String str = (String) e.nextElement();
           Object obj1 = session.getAttribute(str);
           out.println(str + " : " + obj1 + "
"); } out.close(); } }

1. java.util.Enumeration e = session.getSessionAttributes();
2. java.util.Enumeration e = session.getAttributeValues);
3. java.util.Enumeration e = session.getAttributeNames();
4. none of above

26. Choose all the right options for the following procedure and Java code.

Procedure Name: first_pro()

create or replace procedure first_pro(x in number, y out number) as
begin
y:= x * x;
end;

b) Java application code

import java.sql.*;
public class ExecuteProcedure
{
 public static void main(String args[])
 {
   try
   {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:snrao", "scott", "tiger");
    CallableStatement cst = con.prepareCall(" { call first_pro( ?, ? ) } ");
    cst.registerOutParameter(2, Types.INTEGER);  
    cst.setInt(1, 10); 
    cst.execute();
    int k = cst.getInt(2);
    System.out.println("Result is " + k); 
    cst.close();   con.close();
   }
   catch(Exception e) { System.out.println("Database problem: " + e.getMessage()); }
   }     
}

1. code does not compile as sql stored procedure is erroneous
2. code does not compile as calling procedure from Java application is erroneous
3. no problem with procedure syntax
4. no problem with Java syntax

27. What is the output of the following JSTL code? Choose the right option,

<%@ taglib uri=”http://java.sun.com/jsp/jstl/core” prefix=”c” %>

 

1. 2, 4, 6, 8, 10, 12
2. 2, 4, 6, 8, 10
3. 4, 6, 8, 10, 12
4. 4, 6, 8, 10

28. Read the code and choose the right option that is true.

If “c” is the prefix for JSTL core tag library, what is the output of the following snippet of code?





1. does not compile
2. 0
3. 1
4. hello

29. Read the code and choose all the right options that are true.


<%@ page  import="java.sql.*" %>
<%
try  {	
 // loading driver, Connection (of object con) and Statement (of object stmt) goes here
 stmt.executeUpdate("insert into Employee values(100,'TCS', 4500.50)");	
 stmt.close();	con.close();
}
catch(ClassNotFoundException e)
{
  out.println("OracleDriver is not found. " + e);
}
catch(SQLException e)
{
  out.println("Problem occurred: " + e);
} %>  

1. code is no errors and inserts a record
2. code is following JDBC and JSP syntax rules
3. problem lies in catch exception handlers
4. problem lies with SQL insert statement

30. Read the code carefully.

a) web.xml entry


    goldrate
    4100



    xxxxx
    DemoServlet
    
         silverrate
         39
    

b) Servlet code to read above tags.

import javax.servlet.*;	   import javax.servlet.http.*;    import java.io.*;
public class DemoServlet extends HttpServlet
{
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, 
IOException
    {
        String gr = getInitParameter("goldrate");           
        String sr = getInitParameter("silverrate");
        PrintWriter out = res.getWriter();
        out.println(gr + " and " + sr);        // output of the servlet (goes to client)

        // JDBC Connection and Statement code here to insert the data to a permanent storage
        stmt.executeUpdate("insert into rates values("'" + gr + "'"); 
        stmt.executeUpdate("insert into rates values("'" + sr + "'");         
        out.close();
    }
}

What is the output of the above servlet? Choose the right option that is true.

1. code does not compile as ServletConfig object is not created to call getInitParameter(String) method
2. 4100 and 39
3. null and 39
4. null and null

SOLUTIONS

1. 1 2. 1, 2 3. 1 4. 1, 2, 3 5. 1, 2
6. 1 7. 2, 3 8. 1 9. 1, 2 10. 1, 2
11. 1, 2 12. 3, 4 13. 1, 2, 3 14. 3, 4 15. 3, 4
16. 1, 2 17. 1, 3 18. 1 19. 1, 2 20. 4
21. 3 22. 1, 2 23. 3, 4 24. 1, 2, 3, 4 25. 3
26. 3, 4 27. 1 28. 2 29. 1, 2 30. 3

Leave a Comment

Your email address will not be published. Required fields are marked *