Set 25 – Servlets, JSP, JSTL Interview Questions


1. Choose all the right options that are true about the following servlet.

a) web.xml entry snippet for DemoServlet


     xxxxx
     DemoServlet
     
         trafficfine
         3500
     

b) Servlet code

import javax.servlet.*;    import javax.servlet.http.*;      import java.io.*;  import java.util.*;
public class DemoServlet extends HttpServlet
{
    public void service(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException
    {
        PrintWriter out = response.getWriter();
        String fine = getInitParameter("trafficfine");
        out.println(fine);
     }
}

1. code does not compile as getInitParameter(“trafficfine”) is called without ServletConfig object
2. code compiles as getInitParameter() is inherited by HttpServlet from ServletConfig interface
3. gives output as 3500
4. code does not compile as out object is not closed

2. Read the following servlet.

import javax.servlet.*;       import javax.servlet.http.*;       import java.io.*;
public class Demo  extends  HttpServlet
{
    public void service(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException
    {
        ServletConfig config = getServletConfig();	// Line 1
        String str1 = config.getInitParameter("rate");  // Line 2

        ServletContext context = getServletContext();   // Line 3
        String str2 = context.getInitParameter("rate"); // Line 4
    }
}

Choose all the options that do not generate compilation error.

1. Line 1
2. Line 2
3. Line 3
4. Line 4

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

<c:set var=”quantity” value=”2″/>
<c:forEach var=”quantity” begin=”0″ end=”0″ step=”3″>
<c:out value=”${ quantity }” default=”hello”/>
</c:forEach>

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

4. Embed the HTML code in servlet that sends code to client changing background color of browser to red. Choose all the right options that can fill the blanks.

a) HTML snippet

Enter Login Password

b) Servlet snippet

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
    {
         PrintWriter out = response.getWriter();
         if(request.getParameter("password").equals("tcs"))
         {
             out.println("Password is valid");
         }
         else
         {
             ---------------------------------------    // blank 1
             ---------------------------------------    // blank 2
         }
         out.close();
    }
}

1. out.println(“<html> <body bgcolor=”red”> <h3>Password is Invalid”);
out.println(“</h3> </body> </html>”);

2. out.println(“<html> <body bgcolor=red>” + <h3>”Password is Invalid”);
out.println(“</h3> </body> </html>”);

3. out.println(“<html>” + “<body bgcolor=red>” + “<h3>Password is Invalid”);
out.println(“</h3> </body> </html>”);

4. out.println(“<html> <body bgcolor=red> <h3>Password is Invalid”);
out.println(“</h3> </body> </html>”);

5. Create a VIEW to client that changes the browser text color to red if Login fails and green if successful. Choose all the right options.

a) HTML snippet

<form method=”get” action=”http://localhost:8080/Demo.jsp”>
Enter Login Password <input type=”password” name=”password”>
<input type=”submit” value=”Send Validation”>
</form>

b) Demo.jsp snippet

<body>
—————————————- // blank to create view
</body>

1.
<%
if(request.getParameter(“password”).trim().equals(“tcs”))
out.println(“<body text=green>Login Successful</body>”);
else
out.println(“<body text=red>Login Failed</body>”);
%>
2.
<%
if(request.getParameter(“password”).trim().equals(“tcs”))
{ out.println(“<body text=green>”); out.println(“Login Successful”); }
else
{ out.println(“<body text=red>”); out.println(“Login Failed”); }
%>
<% out.println(“</body>”); %>

3.
<%
if(request.getParameter(“password”).trim().equals(“tcs”))
{ out.println(“<body text=green>”); Login Successful }
else
{ out.println(“<body text=red>”); Login Failed }
%>
<% out.println(“</body>”); %>

4.
<%
if(request.getParameter(“password”).trim().equals(“tcs”))
{ out.println(“<body text=green>); Login Successful” }
else
{ out.println(“<body text=red>); Login Failed” }
%>
<% out.println(“</body>”); %>

6. Choose all the right options for the following servlet code snippet that creates a view to client.

// imports here.  Take it granted that all variables like principal etc. are well defined.
public void service(HttpServletRequest request, HttpServletResponse response) throws -------, --------
{
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("");
    out.println("Your Payment Particulars");    
    out.println("
Pay Principal Rs." + principal); out.println("
Pay Interest Rs." + (p*t*r)/100); out.println(""); out.close(); }

1. the code does not compile
2. code compiles
3. client gets all the payment particulars
4. html code can be embedded within println() statements and is not an error

7. Choose all the right options that are true for the following html and servlet code.

a) HTML file to call Yoga servlet

<body>
<a href=”http://localhost:8080/Yoga”> Yoga Places in Hyderabad </a>
</body>

b) Servlet code

import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;  
public class Yoga extends HttpServlet
{
   public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
   {
      response.setContentType("text/html");    
      PrintWriter out = response.getWriter();
      
      out.println("Vemana Yoga Research Center
"); out.println("Amrutham Yoga and Meditation Center
"); out.println("Gandhi Gyan Mandir
"); out.close(); } }

1. <a> tag cannot be used to call a servlet
2. <body> tag cannot be placed in a servlet and raises compilation error
3. HTML code is capable to call servlet
4. client gets the response successfully

8. Choose all the right options that are true for the following html and servlet code.

a) HTML file to call Reservation servlet

<body>
<form action=”http://localhost:8080/reservation”>
<input type=”submit” value=”Send Reservation Form”>
</form>
</body>

b) Servlet code

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

IMAX Cinema Complex


"); out.println("
"); out.println("Enter Number of Tickets
"); out.println("Enter Date
"); out.println("Enter show timing
"); out.println(""); out.println("
"); out.close(); } }

1. HTML file does not contain any input field and is error
2. placing <form> tag in a servlet raises exceptions at runtime
3. HTML file is capable to call servlet
4. client gets the form created dynamically

9. What Web server does? Choose all the right options that are true.

1. Handles HTTP requests
2. Runs on HTTP protocol
3. Provides servlet container
4. capable to send both static and dynamic content to client

10. Choose all the right options that are true regarding the following servlet code.

// imports
public void init(ServletConfig config)
{
    out.println("From init() method");
}
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
{
    PrintWriter out = response.getWriter();
    out.println("From service() method");
}
public void destroy()
{
    out.println("From destroy() method");
}  

1. the code does not compile
2. the code compiles but throws exception
3. code compiles and executes without problems
4. out scope does not exist in init() and destroy() methods

11. Choose all the right options that can insert a record in table Employee.

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();
  -----------------------------------   // blank here
       // JDBC code goes further
 }
 catch(Exception e) {  }
}

1. stmt.executeUpdate(“insert into Employee values(100, ‘TCS’, 5500.50)”);
2. stmt.executeUpdate(“insert into Employee values(0, ‘TCS’, 0.00)”);
3. stmt.executeUpdate(“insert into Employee(100, ‘TCS’, 5500.50)”);
4. stmt.executeUpdate(“insert values into Employee(100, ‘TCS’, 5500.50)”);

12. Choose the exceptions thrown by the following JDBC code of try block.

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 = stmt.executeQuery("select * from Employee");
        // JDBC code goes further
 }
 catch(Exception e) {  }
}

1. SQLException
2. ClassForNameException
3. ClassNotFoundException
4. SQLQueryException

13. Choose the right option about the following JDBC code.

import java.sql.*;
public class Demo
{
 public static void main(String args[])
 {
  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("insert into Employee values(100,'S N Rao',5500.50)");
   System.out.println(x);
   stmt.close();   con.close();
  }
  catch(Exception  e) { System.out.println(e.getMessage());}
 }
}

What is the value printed by the variable x.

1. 1
2. 2
3. any number generated randomly
4. does not compile due to errors

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

<body>
<%
String str = request.getParameter(“userField”);
out.println(“Hello Mr.” + str + ” Best Wishes of the Day”);
%>
<%
out.println(“Hello Sir ” + str + ” You are credited with loan amount”);
%>
</body>

1. String object str scope does not exist in second scriptlet
2. Compilation error
3. No problem with the code
4. Both println() messages go to client

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

a) HTML snippet

Enter User Name

b) JSP snippet

<%!
       public void display(String s1)
       {
           out.println("Best wishes of the day Mr."+s1);
       }
%>
<%
         String str = request.getParameter("userField");
         display(str);
%>

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

16. Observe the following snippet of JSP code and choose all the right options.

<%@  page  import="java.util.*" %>
<%!
          Calendar cal;                    
          public void jspInit()
          {
              cal = Calendar.getInstance();                    
          }
          public void jspDestroy()
          {
               cal = null;
          }
%>
<%
           out.println("Year: " +  cal.get(Calendar.YEAR));
%>        

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

17. Observe the following snippet of code. Choose all the right options which are true.

public class Servlet1 extends HttpServlet
{
 public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
 {
  getServletContext().getRequestDispatcher("/Servlet2").include(req, res);
 }
}
public class Servlet2 extends HttpServlet
{
   public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
   {
      // JDBC code
   }
}

1. above code does not compile due to error in include(req, res) line
2. above code compiles
3. inter-servlet communication between Servlet1 and Servlet2
4. anonymous object of RequestDispatcher is created without error.

18. Choose all the right options that are true about the code.

a) HTML file calling selectrecords.jsp

  
Enter Database Table Name

b) selectrecords.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();
    ResultSet res = stmt.executeQuery("select empid, empname, empsal from " + tableName.trim());
    while(res.next())
    {
     out.println(res.getInt("empid") + ", " + res.getString("empname") + ", " + res.getDouble("empsal")+"
"); } } catch(Exception e) { out.println("Table does not exist" + e); } %>

1. code does not have errors, executes fine and sends all records to client
2. does not compile as errors exist in the JDBC code
3. catching exception is valid
4. it is res.nextRecord() and not res.next()

19. Read the snippet of code of file Records.jsp. Choose all the right options that are true.

File Name: Records.jsp

  try
  { 
   Class.forName("oracle.jdbc.driver.OracleDriver");
   Connection con  = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "system", "lion");
   Statement stmt = con.createStatement();
   stmt.executeUpdate("delete from Employee where empid=100");
   out.println("Record deleted");
   stmt.close();   con.close();
  }
  atch(Exception e) { out.println(e.getMessage());}

1. Record is not deleted as it is HTML code
2. Record is deleted as JSP file accepts HTML code also
3. JDBC Connection is not established
4. raises error

20. Choose the right option that is true about the following JSTL code.

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






1. compilation error as the syntax of if tag is incorrect.
2. false
3. Big Man
4. No output

21. Observe in the servlet code, overloaded init() method is used. Choose the right answer of what the servlet prints.

a) HTML snippet

b) Servlet code

import javax.servlet.*;    import javax.servlet.http.*;      import java.io.*;
public class DemoServlet extends HttpServlet
{
    String cityName = null;
    public void init() throws ServletException
    {
        cityName = "Hyderabad";
    }
    public void init(ServletConfig config) throws ServletException
    {
        cityName = "Secunderabad";
    }
    public void service(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException
    {
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        session.setAttribute("city", cityName);
        out.println(session.getAttribute("city"));
        session.invalidate();
        out.close();
     }
}  

1. Hyderabad
2. Secunderabad
3. null
4. either does not compile or throws exception at runtime

22. Choose all the options that are true about the following servlet.

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

1. the above code does not compile as constructor cannot exist in a servlet
2. compiles but throws exception at runtime
3. compiles successfully without a problem
4. runs successfully without a problem

23. Read the snippets and choose the right option.

a) HTML snippet

Enter Password

b) Servlet1

import javax.servlet.*;	import javax.servlet.http.*;    import java.io.*;
public class Servlet1 extends HttpServlet
{
 public void doPost(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException
 {
  if(request.getParameter("pass").trim().toUpperCase().equals("TCS"))
  {
    response.getWriter().println("Login is Successful");
  }
  else
  {
    --------  // blank to send Failure.jsp file to client
  }
 }
}

c) Failure.jsp snippet

     Your Login Failed

1. response.sendRedirect(“Failure.jsp”);
2. response.sendFile(“Failure.jsp”);
3. response.send(“Failure.jsp”);
4. response.disptch(“Failure.jsp”);

24.

<%@ 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 empid, empname, empsalary from Employee");       
 while(res.next())  {     	         
   out.println(res.getInt(1) + "   " + res.getString(2) + "   " + res.getDouble(3) + "
"); } res.close(); stmt.close(); con.close(); } catch(Throwable e) { out.println("Problem in database access: " + e) } %>

1. code is no errors and sends records information to client
2. code is following JDBC and JSP syntax rules
3. problem lies with catch exception handler
4. problem lies with SQL query statement

25. Which statement will send a JSP page from the following snippet of servlet to client.

a) HTML code

Enter Login Password

b) Servlet code

import javax.servlet.*;	   import javax.servlet.http.*;    import java.io.*;      import java.sql.*;
public class DemoServlet extends HttpServlet
{
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException
    {
     if(! req.getParameter("password").trim().equals("tcs"))
     {
        ---------------------
     }
    }

1. res.sendRedirect(“Login.jsp”);
2. res.send(“Login.jsp”);
3. res.redirect(“Login.jsp”);
4. res.forward(“Login.jsp”);

26. Imagine an Employee table with three columns of empid (of type number), empname (of type varchar) and empsal (of type number(6,2)). Observe the following snippet of code.

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); } %>

It is simply to retrieve values and display to the client. What could be the blanks. Choose all the right options.

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

27. Observe the code.

a) web.xml entry


    xxxxx
    DemoServlet
    
       goldrate
       4100
    

b) Servlet file that reads the above tag

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");
        PrintWriter out = res.getWriter();
        out.println("Today gold rate is Rs." + gr);	
        out.close();
    }
}

In the above servlet code, without creating ServletConfig object, getInitParameter(“goldrate”) is directly called. Choose the right option that is true about the code.

1. the code does not compile
2. code compiles and output of gold rate will go to the client
3. code compiles but output null will go to the client
4. none above

28. To execute the following procedure, create a CallableStatement object. Choose the right option.

a) Following is the procedure:

create or replace procedure updateSalary as
begin
update Employee set empsal = empsal+500;
end;

b) Java code snippet calling the above procedure

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");
 CallableStatement cst = --------  // blank to create cst object 
 cst.execute();
     	// remaining code goes here
}

1. con.prepareStoredProcedure(“{ call updateSalary() }”);
2. con.callProcedure(“{ call updateSalary() }”);
3. con.preparedCall(“{ call updateSalary() }”);
4. con.prepareCall(“{ call updateSalary() }”);

29. Read the following servlet.

import javax.servlet.*;   import javax.servlet.http.*;  import java.io.*;
public class Demo extends GenericServlet
{
  public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
  {
    ServletInputStream  in  = req.getInputStream();     // Line 1
    ServletOutputStream  out1  = res.getOutputStream(); // Line 2
    PrintWriter out2 = res.getWriter();		        // Line 3
  }
}

Choose all the options that do not generate compilation error.

1. Line 1
2. Line 2
3. Line 3
4. none above

30. Choose the right option that sets and deletes the attribute to a session object.

a) HTML snippet

Enter Password

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();
         HttpSession session = request.getSession();
         ---------------------   // blank of code here
         out.println("Your password is removed from session");
         out.close();	
    }
}

1. session.setAttribute(“pass”, request.getParameter(“password”));
session.removeAttribute(“password”);

2. session.setAttribute(request.getParameter(“password”));
session.deleteAttribute();

3. session.setAttribute(“password”, request.getParameter(“password”));
session.deleteAttribute(“password”);

4. session.setAttribute(“password”, request.getParameter(“password”));
session.removeAttribute(“password”);

SOLUTIONS

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

Leave a Comment

Your email address will not be published.