Set 23 – Servlets, JSP, JSTL Interview Questions


1. Choose all the right options that are valid URL mappings in web.xml file for the following servlet.

public class Servlet1 extends GenericServlet
{
// business logic goes here
}

1.
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/Servlet1/*</url-pattern>
</servlet-mapping>

2.
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/myServlet1/*</url-pattern>
</servlet-mapping>

3.
<servlet>
<servlet-name>myServlet1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>myServlet1</servlet-name>
<url-pattern>/myServlet1/*</url-pattern>
</servlet-mapping>

4.
<servlet>
<servlet-name>Servlet</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Servlet</servlet-name>
<url-pattern>/Servlet1/*</url-pattern>
</servlet-mapping>

2. The value entered by the client in the “user” input field is “SURE, NAG RAO”. What could be the URL displayed in the browser. Choose the right option.

1. http://localhost:8888/myServlet1?user=SURE%2C+NAG+RAO
2. http://localhost:8888/myServlet1?user=SURE,+NAG+RAO
3. http://localhost:8888/myServlet1?user=SURE, NAG RAO
4. http://localhost:8888/myServlet1?user=SURE+NAG+RAO

3. Choose all the right options for the following codes.

a) HTML snippet

 
    
Charminar, Old City
Shilparamam, New City

b) 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();
 
    String place = request.getParameter("hyderabad");

    out.println("");
    out.println("Following are the visiting places of Hyderabad
"); if(place.equals("CHMR")) { out.println("Charminar"); } else if(place.equals("SRM")) { out.println("Shilparamam"); } out.println(""); out.close(); } }

1. Syntax of HTML code is erroneous
2. Servlet code is erroneous
3. HTML code and Servlet code is error free
4. Client gets appropriate image when hyper link is clicked

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

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;  
public class Servlet1 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("");
        out.println("
Supply the items before the month end
"); out.close(); } }

1. The code sends the table text color in blue color
2. Syntax error in giving color to table text
3. This code does not work as it contains many errors
4. No problem with the code and is error free

5. Choose all the right options that are true for the following servlet code including the blank.

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/plain");
   res.getWriter().println("Following are context initialization values");
   ---------  xyz = getServletContext().getInitParameterNames();
 }
}

1. code compiles successfully
2. code does not compile as getServletContext() is called without object
3. the blank can be a java.util.Enumeration
4. the blank can be a String[]

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

a) URL mapping in web.xml file

   
        Servlet1
        Servlet1
    

    
        Servlet1
        /Servlet1/*
      

b) Servlet code

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*; 
public class Servlet1 extends HttpServlet
{
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
    {
          res.setContentType("text/plain");
          ServletOutputStream out = res.getOutputStream();
          out.println("Yes, it works");
          out.println("No, it does not work");
    }
}

1. The code does not work with the problem of service() method parameters
2. The code does not work with the out object problem or URL mapping code
3. The code is perfectly alright with no errors including URL mapping
4. Client gets the two messages of println() methods

7. Choose all the possible right options that can fill the blank to compile successfully.

import javax.servlet.*;	import javax.servlet.http.*;    import java.io.*; 
public class DemoServlet extends HttpServlet
{
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException
    {
       response.setCharacterEncoding("UTF-8");
       response.setContentType("text/plain");
       ----------------------  reader = request.getReader();
       StringBuilder sb = new StringBuilder();
       String str;
        while ((str = reader.readLine()) != null) {
            sb.append(str);
        }
        reader.close();
    }
}

1. BufferedReader
2. Reader
3. InputStreamReader
4. FileReader

8. Choose the right option for the following snippet of code.

a) HTML snippet

 
Enter User Name

b) Servlet with lifecycle methods

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*; 
public class Servlet1 extends HttpServlet
{
    String userName;
    public void init(ServletConfig config)
    {
       String userName = request.getParameter("user");   
       this.userName = userName;    		              
    }
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
          PrintWriter out = response.getWriter();
          out.println(userName);
    }
    public void destroy()
    {
         out = null;
    } 
}

1. code does not compile
2. code compiles successfully but throws exceptions at runtime
3. code compiles and runs successfully
4. none of above

9. Choose the right option that is true for the following snippets of code.

a) HTML file snippet

b) Servlet snippet

import javax.servlet.*;           import java.io.*;
public class Validate extends GenericServlet
{
    public void service(ServletRequest request, ServletResponse response) throws ServletException,  IOException
    {	
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();	
        String str1 = request.getParameter("t1");
        String str2 = request.getParameter("t2");
        out.println(str1 + ", "+ str2);
        out.close();
     }
}  

1. does not compile as HTML hidden fields cannot be read with getParameter() method as HTTP 1.1 and HTTPS prevents.
2. compiles but throws exception
3. hidden tags do not exist in html
4. compiles and executes successfully

10. Choose all the right options that are true for the following servlet creating Web form on-the-fly.

a) HTML snippet

  
       
Enter Login Password

b) Servlet

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").equals("tcs"))
     {
        out.println(" 

Shopping Cart

"); out.println("
"); out.println("Enter Item Name
"); out.println("Enter Item Quantity
"); out.println(""); out.println("
"); } else { out.println("Your Login failed
Try again"); } out.close(); } }

1. A Web form is created on-the-fly for a shopping cart and sent to client
2 No problem with the code
3. code contains errors and thereby form is not sent to client
4. html code cannot be put inside a service() method

11. Choose the right option that is true. RequestDispatcher include() method is called three times.

a) HTML Snippet

 
 See RequestDispatcher in Action

b) Servlet1

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 
  { 
    PrintWriter out = response.getWriter();
     out.println("Hello 1");

     RequestDispatcher rd = request.getRequestDispatcher("Servlet2");
     rd.include(request, response);
     rd.include(request, response);
     rd.include(request, response);

    out.println("Hello 3");
  }
}

b) Servlet2

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;
public class Servlet2 extends HttpServlet
{
    public void service(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException
    {
        PrintWriter out = response.getWriter();
        out.println("Hello 2");
    }
}

The response will be

1. Hello 1, Hello 2, Hello 2, Hello 2, Hello 3
2. Hello 1, Hello 2, Hello 3
3. code compiles but throws exception
4. code does not compile

12. Observe, the out object is closed in both the servlets. Choose the right option that is true about the response sent to client.

a) Servlet1

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 
  { 
    PrintWriter out = response.getWriter();
     out.println("Hello 1");

     RequestDispatcher rd = request.getRequestDispatcher("Servlet2");
     rd.include(request, response);
     
      out.println("Hello 3"); 
      out.close();
  }
}

b) Servelt2

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

1. Hello 1, Hello 2, Hello 3
2. Hello 1, Hello 3
3. Hello 1, Hello 2
4. no output (no response)

13. What are the parameters of service() method so that they can be passed to include() method.

        
import javax.servlet.*;    import javax.servlet.http.*;      import java.io.*;
public class DemoServlet extends HttpServlet
{
    public void service(--------------- request, ----------------- response) throws 
ServletException, IOException
    {
       RequestDispatcher rd = request.getRequestDispatcher("Servlet2");
       rd.include(request, response); 
    }
}

Choose all the right options possible to fill up the blanks to compile successfully.

1. HttpServletRequest, HttpServletResponse
2. ServletRequest, ServletResponse
3. ServletConfig, ServeltContext
4. none above

14. Choose the right option that is true for the following JDBC code.

import java.sql.*;
public class Demo
{
   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.executeUpdate("create table Employee(empid number, empname varchar(15), empsal number(6,2))");
       stmt.close();    con.close();
    }
}

1. driver problem exists
2. getConnection() syntax is wrong
3. SQL command problem exists
4. no problem with the code and table is created in the database

15. Choose the right option that is true for the following JDBC code.

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;    import java.sql.*;
public class Servlet1 extends HttpServlet
{
  public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException 
  { 
     PrintWriter out = response.getWriter();
     try
     {
         Class.forName("oracle.jdbc.driver.OracleDriver");
         Connection con  = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");
         Statement stmt = con.createStatement();
         int k  = stmt.executeUpdate("insert into Employee values(100, 'S N Rao', 5500.50)");
         int m  = stmt.executeUpdate("insert into Employee values(101, 'Jyothi', 6500.50)");
         out.println("No of records inserted: " + (k+m));
         stmt.close();    con.close();
     }
     catch(Exception e) {  out.println("Problem: " + e);  }
     out.close();
  }
}

What is the response of number of records inserted?

1. 0
2. 1
3. 2
4. does not compile as executeUpdate() does not return a value. It returns void.

16. Choose all the right options that are true about the JDBC code.

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;    import java.sql.*;
public class Servlet1 extends HttpServlet
{
  public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
  { 
     PrintWriter out = response.getWriter();
     try
     {
         Class.forName("oracle.jdbc.driver.OracleDriver");
         Connection con  = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");
         Statement stmt = con.createStatement();
         stmt.executeQuery("insert into Employee values(111, 'Sunny', 1111.11)");
         out.println("Record Inserted");
         stmt.close();    con.close();
     }
     catch(Exception e) {  out.println("Problem: " + e);  }
     out.close();
  }
}

1. record will not be inserted as executeQuery() is used instead of executeUpdate()
2. it is syntax error and the code will not be compiled
3. code will be compiled and executed
4. record is inserted and client gets the message of “Record Inserted”

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

a) HTML snippet

Enter User Name
Enter Password

b) File Name: Demo.jsp

<%
        String str1 = request.getParameter("name");
        String str2 = request.getParameter("password");
        out.println("Name is " + str1);
        out.println("
Password is " + str2); %>
Name is <%= str1 %>
Password is <%= str2 %>

1. code contains no errors
2. client gets the name and password two times
3. code is with errors as scope of str1 and str2 does not exist in expression
4. PrintWriter object out is not created but used

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

<%!
        String str1 = request.getParameter("name");
        String str2 = request.getParameter("password");
        out.priintln(str1 + ", " + str2);
%>
<%
        out.println("Name is " + str1);
        out.println("
Password is " + str2); %>

1. code does not compile as request object scope does not exist in declaration
2. code does not compile as out object scope does not exist in declaration
3. code is without errors
4. client gets the response

19. Read the snippet of code of file Retrieve.jsp. Choose all the right options which are true.

File Name: Retrieve.jsp

    		// JDBC code of Connection and Statement (of object stmt) etc goes here
        ResultSet rs = stmt.executeQuery("select empid, empname, empsal from Employee");   
    		// JDBC code goes further

1. ResultSet object is created
2. ResultSet object is not created
3. JDBC executeQuery() statement syntax is wrong
4. JDBC executeQuery() statement syntax is not wrong

20. Read the snippets of code carefully

a) HTML snippet that calls the following JSP

b) Following is the Records.jsp snippet:

       <%@ page import="java.sql.*" %>
<%
        try
        {
             Class.forName("oracle.jdbc.driver.OracleDriver");
             Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
             Statement stmt=con.createStatement();
             ResultSet res = stmt.executeQuery("select * from Employee");             
             while(res.next())
             {
                  out.println(res.getInt(1) + " : " + res.getString(2) + " : " + res.getDouble(3) + "
"); } res.close(); stmt.close(); con.close(); } catch(--------------------- e) { out.println("Problem: " + e); } catch(--------------------- e) { out.println("Problem: " + e); } %>

What could be the two blanks to handle the exceptions thrown by the try block. Choose all the right options.

1. NoClassDefFoundException, SQLException
2. ClassNotFoundException, JDBCException
3. ClassNotFoundException, SQLException
4. none above

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

a) HTML snippet calling Servlet1

Enter Ornament Weight

b) Servlet1 calling Demo.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 
  { 
    request.setAttribute("rate", 3650);
    RequestDispatcher rd = request.getRequestDispatcher("Demo.jsp");
    rd.include(request, response);
  }
}

c) Demo.jsp

 <%
    int goldrate = ((Integer) request.getAttribute("rate")).intValue();         // line 1
    int goldweight = Integer.parseInt(request.getParameter("weight"));   // line 2
    int gold_cost = goldrate * goldweight;
    out.println(gold_cost);
%>

1. no problem with the code
2. gold_cost is sent to client
3. parsing error in line 1
4. weight of HTML form input field cannot be retrieved from Demo.jsp in line 2

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

a) HTML snippet calling Servlet1

Enter User Name
Enter User Name

b) Servlet1

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;
public class Servlet1 extends HttpServlet
{
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
  { 
      if(request.getParameter("text").equals("tcs") && request.getParameter("password").equals("hyderabad"))
      {
        response.sendRedirect("index.jsp");
      }
      else
      {
        response.getWriter().println("Your inputs are invalid. Try again");
      }
  }
}

1. HTML syntax is wrong
2. HTML syntax is correct
3. if structure raises exceptions
4. if structure does not raise exceptions

23. Choose the right option that is true.

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;
public class Servlet1 extends HttpServlet
{
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
  { 
      PrintWriter out = response.getWriter();

      HttpSession session1 = request.getSession();
      HttpSession session2 = request.getSession(false);

      out.println(session1.getId());
      out.println(session2.getId());
      out.close();
  }
}

1. IDs of both session1 and session2 will be the same
2. IDs of both session1 and session2 will not be the same
3. program does not compile as two sessions cannot be created for the same client
4. none above

24. What could be the blank to compile the servlet successfully. Choose the right option.

a) HTML snippet

Enter User Name

b) Servlet1

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;
public class Servlet1 extends HttpServlet
{
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
  { 
      PrintWriter out = response.getWriter();
      String str = request.getParameter("user"); 
      HttpSession session = request.getSession();
      session.setAttribute("userName", str);
      -------------- value = session.getAttribute("userName");          // blank here
      out.println(value);
  }
}

1. Object
2. String
3. int
4. java.util.Enumeration

25. Choose the right option for the possible value of the blank that compiles the servlet successfully and client gets all the values.

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;  import java.util.*;
public class Servlet1 extends HttpServlet
{
  public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException 
  { 
      PrintWriter out = response.getWriter();
      HttpSession session = request.getSession();

      session.setAttribute("goldrate", "3600");
      session.setAttribute("silverrate", "41");
      session.setAttribute("tax", "10.5");

      Enumeration e = session.getAttributeNames();
      while(e.hasMoreElements())
      {
          ----------------------------	// blank
          out.println(session.getAttribute(xyz));
      }
      out.close();
  }
}

1. String xyz = (String) e.nextElement();
2. Object xyz = e.nextElement();
3. String xyz = e.nextElement();
4. none above

26. Choose the right option for the blank in the code that will delete the record successfully.

a) HTML snippet

Enter Employee ID to delete

b) Servlet1

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;    import java.sql.*;
public class Servlet1 extends HttpServlet
{
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
  { 
     PrintWriter out = response.getWriter();
     int id = Integer.parseInt(request.getParameter("idnum"));
     try
     {
         Class.forName("oracle.jdbc.driver.OracleDriver");
         Connection con  = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");
         Statement stmt = con.createStatement();
         -------------------------------      // delete statement here         
         out.println("Record Deleted");
         stmt.close();    con.close();
     }
     catch(Exception e) {  out.println("Problem: " + e);  }
     out.close();
  }
}

1. stmt.executeUpdate(“delete from Employee where empid=id”);
2. stmt.executeUpdate(“delete from Employee where empid+id”);
3. stmt.executeUpdate(“delete from Employee where empid=”+id);
4. none above

27. Imagine the database table entered by the user has 10 rows with 3 columns. Choose the right option that is true.

a) HTML snippet

Enter table name

b) Demo.jsp

<%@ page import = "java.sql.*"%>
<%
   String tableName = request.getParameter("table");
   try
    {
         Class.forName("oracle.jdbc.driver.OracleDriver");
         Connection con  = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");
         Statement stmt = con.createStatement();
         int x = stmt.executeUpdate("update " + tableName + " set empsal=empsal+500");
         out.println(x);
         stmt.close();    con.close();
    }
    catch(Exception e) {  out.println("Problem: " + e); }
 %>
 

1. the response will be 10
2. the response will be 3
3. the response will be 30
4. none above

28. Choose the right option to fill the blank for the following JSTL code.

a) HTML snippet

Enter Name
Enter Password

b) Demo.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page contentType="text/html" %>


 
Your Name:
Your Password:

What is the best comparison to compare the variable person with string 'tcs' that fits in the blank?

1. ${person eq 'tcs'}
2. ${person == 'tcs'}
3. ${person equals 'tcs'}
4. ${person compare 'tcs'}

29. Choose all the right options that are true.

a) HTML snippet

b) Demo.jsp

<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"  %>




 Number in words is Ten  
 Number in words is Twenty 
 Number in words is Thirty 
 Number in words is Forty 
      
      Wrong selection:  Select from 10 to 40 only
      


1. The code is without errors that compiles fine
2. Response is received by client
3. code is with errors at compilation stage
4. code throws exceptions at execution stage

30. Read the code and choose the right option for the blank to compile and execute successfully.

a) procedure

create or replace procedure calculateCircle(x in number, y out number, z out number) as
begin
y:= 3.14*x*x;
z:=2*3.14*x;
end;

b) JDBC application calling above procedure

import java.sql.*;
public class Demo 
{
  public static void main(String args[]) throws Exception     
  {
       Class.forName("oracle.jdbc.driver.OracleDriver");
       Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","tiger");
       CallableStatement cst = con.prepareCall(" { call calculateCircle( ?, ?, ? ) } ");
       cst.registerOutParameter(2, Types.DOUBLE);  
       cst.registerOutParameter(3, Types.DOUBLE);  
       cst.setInt(1, 10); 
       ----------------------------        	// blank
       double circleArea = cst.getDouble(2);
       double circlePerimeter = cst.getDouble(3);
       System.out.println("Circle area is " + circleArea); 
       System.out.println("Circle perimeter is " + circlePerimeter); 
       cst.close();      con.close();
   }     
}   

What could be the blank to call the CallableStatement to execute the code?

1. cst.execute();
2. cst.executeUpdate();
3. cst.executeCallableStatement();
4. cst.executeProcedure();

SOLUTIONS

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

Leave a Comment

Your email address will not be published.