Set 22 – Servlets, JSP, JSTL Interview Questions


1.
a) Read the following servlet

import javax.servlet.*;	  import javax.servlet.http.*;      import java.io.*;
public class DemoServlet extends HttpServlet
{
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
          response.setContentType("text/html");
          response.getWriter().println("Hello Servlet");
    }
}

What could be right URL mapping in web.xml for the above servlet. Choose the right option.

1.
<servlet-mapping>
<servlet-name>ds</servlet-name>
<url-pattern>/myDemoServlet/*</url-pattern>
</servlet-mapping>

2.
<servlet-mapping>
<servlet-name>ds</servlet-name>
<url-path>/myDemoServlet/*</url-path>
</servlet-mapping>

3.
<servlet-mapping>
<servlet-class>DemoServlet</servlet-class>
<url-pattern>/myDemoServlet/*</url-pattern>
</servlet-mapping>

4.
<servlet-mapping>
<servlet-class>DemoServlet</servlet-class>
<url-path>/myDemoServlet/*</url-path>
</servlet-mapping>

2. For the following Servlet URL, guess the right options.

a) URL: http://localhost:8080/roses?nameField=nag+rao

b) Servlet

import javax.servlet.*;	import javax.servlet.http.*;    import java.io.*; 
public class DemoServlet extends HttpServlet
{
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
          response.setContentType("text/html");
          String s1 = request.getParameter("nameField");
          response.getWriter().println(s1);
     }
}

Choose the right option of what s1 prints.

1. nag, rao
2. nag rao
3. nag+rao
4. nag,rao

3. Choose all the right options that create a table view on client’s browser.

import javax.servlet.*;	   import javax.servlet.http.*;     import java.io.*;
public class SendTable extends HttpServlet
{
   public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
   {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      ------------------   // blank to create a table view
    }
}

1. out.println(“<body><table border=1 width=800px>”);
out.println(“<tr> <th>State</th> <th>Capital</th> </tr>”);
out.println(“<tr> <td>Telangana</td> <td>Hyderabad</td> </tr>”);
out.println(“</table></body>”);
out.close();

2. out.println(“<body><table border=1 width=800px> <tr> <th>State</th>”);
out.println(“<th>Capital</th> </tr> <tr> <td>Telangana</td>”);
out.println(“<td>Hyderabad</td> </tr> </table></body>”);
out.close();

3. out.println(“<body><table border=1 width=800px> <tr> <th>State</th>”);
out.println(“<th>Capital</th> </tr> <td>Telangana</td>”);
out.println(“<td>Hyderabad</td> </tr> </table></body>”out.close());

4. out.println(“<body><table border=”1″ width=”800px”> <tr> <th>State</th>”);
out.println(“<th>Capital</th> </tr> <td>Telangana</td>”);
out.println(“<td>Hyderabad</td> </tr> </table></body>”);
out.println();

4. 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

Enter Login Password

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

5. What could be the blank in the following snippet of servlet?

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");
         PrintWriter out = response.getWriter();
         ---------------- protocolUsed = request.getProtocol();       // blank here of return type
         out.println(protocolUsed);
         out.close();
    }
}

1. URL
2. int
3. String
4. Object

6. Choose all the right options to get the values entered by the client as per the following URL.

a) URL: http://lorvent:8080/roses?t1=t2&t3=t4

b) Servlet

import javax.servlet.*;           import java.io.*;
public class DemoServlet 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");   	// statement 1
        String str2 = request.getParameter("t2");   	// statement 2
        String str3 = request.getParameter("t3");   	// statement 3
        String str4 = request.getParameter("t4");   	// statement 4

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

1. statement 1
2. statement 2
3. statement 3
4. statement 4

7. What could be the blank in the following snippet of servlet? Choose the right option.

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();

        ------------ address = request.getRemoteAddr(); // blank here

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

1. URL
2. String
3. StringBuffer
4. Enumeration

8. What could be the blank in the following servlet to compile successfully.
Choose the right option (or options).

import javax.servlet.*;       import java.io.*; 
public class Servlet1 extends GenericServlet
{
     public void ------------------ (ServletRequest request, ServletResponse response) throws ServletException, IOException                        // blank
     {
         response.setContentType("text/plain");
         PrintWriter out = response.getWriter();
         out.println("Hello 1");
         out.close();
     }
}

1. service
2. doGet
3. doPost
4. none above

9. Observe the following snippet of code and choose the right option that is true.

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();
      HttpSession session = request.getSession();
      String id = session.getId();	
      out.println("Know your session id:  " + id);
      out.close();	
    }
}

1. does not compile as MIME type is not set
2. does not compile as getId() does not return a string but returns an int value
3. does not compile as it should be getSession(true)
4. Compiles, executes and sends session id to client

10. Choose all the right options to fill the blank to compile successfully and send HTML form to client.

import javax.servlet.*; 	      import javax.servlet.http.*;        import java.io.*;
public class Validate extends HttpServlet
{
   public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
   {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      ----------------------------------    // blank code that sends a form to client
      out.close();
    }
}  

1. out.println(“<body><form action=http://localhost:8080/Demo.jsp>”);
out.println(“Enter Login Password <input type=password name=password>”);
out.println(“<input type=submit value=SEND>”);
out.println(“</form></body>”);

2. out.println(“<body><form action=http://localhost:8080/Demo.jsp>”);
out.println(“Enter Login Password <input type=password name=password> <input type=submit value=SEND>”);
out.println(“</form></body>”);

3. out.println(“<body><form action=http://localhost:8080/Demo.jsp> Enter Login Password <input type=password name=password> <input type=submit value=SEND> </form></body>”);

4. none above

11. Choose all the right options that create an object of RequestDispatcher.

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");
        request.setAttribute("GoldRate", 3500);
        RequestDispatcher rd =  ------------------------  // blank
        rd.include(request, response); 
        out.println("Hello 2");
        out.close();
    }
}

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

12. Choose all the right options that can fill the blank to compile successfully and get response by the client.

a) First 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
    {
        PrintWriter out = response.getWriter();
        out.println("Hello 1");
        -----------------------------------      // blank
        RequestDispatcher rd = request.getRequestDispatcher("Servlet2");
        rd.include(request, response); 
        out.println("Hello 2");
    }
}

b) Second servlet

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();
        Object obj = request.getAttribute("GoldRate");
        out.println("Gold value is Rs."+ obj);
    }
}

1. request.setAttribute(“GoldRate”, 3500);
2. request.setAttribute(“GoldRate”, “3500”);
3. request.setAttribute(new String(“GoldRate”), new Integer(3500));
4. request.setAttribute(new StringBuffer(), 3500);

13. Read the snippet of code and choose the right option that is true.

a) HTML snippet

Enter Password

b) First servlet

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
    {
        PrintWriter out = response.getWriter();
        out.println("Hello 1");
        RequestDispatcher rd = request.getRequestDispatcher("Servlet2");
        rd.forward(request, response);
        out.println("Hello 2");
    }            				
}

c) Second servlet

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

1. Client gets Hello 1, Hello2 and password
2. Client gets Hello2 and password
3. Client gets Hello 1 and password
4. Client gets only password

14. Choose all the right options that can fill the blank to compile and execute successfully.

import java.sql.*;
public class Demo
{
   public static void main(String args[]) throws ClassNotFoundException, SQLException
   {
       Class.forName("oracle.jdbc.driver.OracleDriver");
       Connection con  = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",
"scott", "tiger");
        Statement stmt = con.createStatement(---------------,  ResultSet.CONCUR_READ_ONLY);  // blank
        int k = stmt.executeUpdate("insert into Employee values(555, 'S N Rao', 6789.99)");
        System.out.println("Records inserted: " + k);
        stmt.close();    con.close();
    }
}

1. ResultSet.TYPE_FORWARD_ONLY
2. ResultSet.TYPE_SCROLL_SENSITIVE
3. ResultSet.CONCUR_UPDATABLE
4. ResultSet.TYPE_SCROLL_INSENSITIVE

15. Choose the right option that is true about the following code.

a) HTML snippet

Enter Employee ID to delete
Enter Password

b) Servlet

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(); 
       String password = request.getParameter("password");
       int empid = Integer.parseInt(request.getParameter("eid"));
       if(password.equals("tcs"))
       {
         try
         {
          Class.forName("oracle.jdbc.driver.OracleDriver");
          Connection con  = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");
          Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
          int k = stmt.executeUpdate("delete from Employee where empid=" + empid);
          out.println("Deleted");
          stmt.close();    con.close();
        }
        catch(Exception e)  {  out.println("Some problem: " +e);  }
      }
      else
      {
         out.println("Your password is not valid");
      }
      out.close();
   }
}

1. syntax of stmt object creation is wrong
2. return type of executeUpdate() method is wrong
3. syntax of loading the driver is wrong
4. no problem with the code, compiles and deletes the record(s) successfully

16. Choose the right option that is true about the servlet snippet.

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,  SQLException, ClassNotFoundException
    {
         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");
         res.close();   stmt.close();    con.close();
   }
}

1. ResultSet res object is not used and is error
2. service() method cannot throw more exceptions than ServletException and IOException
3. JDBC code is erroneous
4. code is perfect and compiles successfully

17. Choose the right option that is true for the following snippet of code.

a) HTML snippet

Enter Student Name

b) Demo.jsp

<%  String str1 = request.getParameter("name");  %>
         User name is       
<%   out.println(str1);   %>

User name is <%= str1 %>

1. In a single page, it is not possible to have multiple scriptlets
2. expression syntax is wrong as scope of str1 does not exist in expression
3. HTML file syntax is wrong as in name=”name”
4. code is no problem and client gets his name twice

18. Choose the right option that is true for the following snippet of code.

a) HTML snippet

b) Demo.jsp

<%!
    public void jspInit()
    {
       out.println("Hello 1");
    }
    public void jspDestroy()
    {
        out.close();
    }
%>
<%
     out.println("Hello 2");
%>

1. no problem with the code and client receives messages Hello 1 and Hello 2
2, no problem with the code and client receives message Hello 2 only as jspInit() is not called
3. compiler says jspInit() and jspDestroy() cannot be overridden
4. compiler says out scope does not exist in declaration

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

a) Demo.jsp

<%
         application.setAttribute("price", "150.5");
%>

b) Test.jsp

<%
          String s1 = (String) application.getAttribute("price"); 
          double d1 = Double.parseDouble(s1);
          out.println("Double the price is " + Math.pow(d1, 2));
%>

1. application is an implicit object of ServletContext interface
2. application attribute value can be obtained from any other JSP file
3. code is no problem and executes successfully
4. none of above

20. Choose the right option that can fill the blank to compile successfully.

a) HTML snippet that calls Records.jsp

Enter table name

b) Records.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 = ---------------------- ;      // blank
             while(res.next())      
             {
                  out.println(res.getString(1) + " : " + res.getString(2) + " : " + res.getString(3) + "
"); } res.close(); stmt.close(); con.close(); } catch(Exception e) { out.println("Problem in access: " + e); } %>

What could be the blank to iterate the ResultSet and print all the records.

1. stmt.executeQuery(“select * from ” + tableName)
2. stmt.executeQuery(“select * from tableName”)
3. stmt.executeQuery(“select * from ‘tableName'”)
4. none above

21. Choose the right option that is true for the following snippet of code.

a) HTML snippet that calls Servlet1

Enter User Name

b) Servlet1 that calls JSP file

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
    {
        String userName = request.getParameter("user");         
        if(userName.trim().equals("tcs"))
        {
            response.sendRedirect("EmployeeInsert.jsp");
        }
        else
        {
            response.sendRedirect("Failure.jsp");
        }
   }
}

1. A JSP file can’t be send with sendRedirect(), only HTML file can be sent
2. trim() can’t be applied in servlets
3. method=post does not work with sendRedirect()
4. code contains no errors and works fine

22. Choose the right option that is true.

a) HTML snippet calling Servlet1

Enter User Name

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
    {
        PrintWriter out = response.getWriter();  
        out.println("Hello 1");
        getServletContext().getRequestDispatcher("/Demo.jsp").forward(request, response);
        out.println("Hello 2");    
   }
}

c) Demo.jsp snippet

<%
        String userName = request.getParameter("user");      
        out.println(userName);
%>

1. RequestDispatcher syntax is wrong
2. user name cannot be retrieved from JSP file and can be retrieved only from servlet
3. code contains no errors and client gets Hello1, user name and Hello 2
4. code contains no errors and client gets only user name

23. Choose all the right options that are true with the following 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();
        response.addCookie(new Cookie("Lux", "10"));     // line 1
        response.addCookie(new Cookie("Santoor", "5"));

        Cookie carray[] = request.getCookies();		// line 2
        for(Cookie cook : carray)				// line 3
        {
           out.println(cook.getName() + " : " + cook.getValue() + "
"); // line 4 } out.close(); } }

1. line 1 and line 2 are erroneous
2. line 3 and line 4 are erroneous
3. code is without errors
4. prints all cookies names and values

24. Choose all the right options that are true with the following snippet of code.

a) HTML snippet that calls Servlet1

b) Servlet snippet

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
    {
        HttpSession session = request.getSession();
        Integer count = (Integer) session.getAttribute("counter");
        if(count == null)
        {
          count = new Integer(1);
        }
        else
        {
           count = new Integer(count.intValue() + 1);
        }
        session.setAttribute("counter",  count);
        response.getWriter().println(session.getAttribute("counter"));
   }
}

1. count increments every time and displays the count
2. code is without errors
3. count will not be incremented as every time new session is created
4. getAttribute(“counter”) syntax is erroneous

25. Choose the right option for the blank in the servlet that compiles the servlet 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
    {
        String userName = request.getParameter("user");
        HttpSession session = request.getSession();
        session.setAttribute("password", userName);
        ------------ xyz = session.getAttribute("password"); 
   }
}

1. String
2. Object
3. StringBuffer
4. none of above

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


 


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

27. Choose all the right options that are true.

a) HTML snippet

Enter Employee ID to delete

b) Demo.jsp file:

<%@ page import="java.sql.*" %>
<%!
public Connection getStatement() throws ClassNotFoundException, SQLException
{
   Class.forName("oracle.jdbc.driver.OracleDriver");
   Connection con  = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");
   return con;
}
%>
<%
     try
     {
         Connection con = getStatement();
         PreparedStatement psmt = con.prepareStatement("select * from Employee where empid=?"); 
         int eid = Integer.parseInt(request.getParameter("id"));
         psmt.setInt(1, eid);
         ResultSet res = psmt.executeQuery();
         res.next();
         out.println("Employee ID: " + res.getInt("empid"));
         out.println("
Employee Name: " + res.getString("empname")); out.println("
Employee Salary: " + res.getDouble("empsal")); psmt.close(); con.close(); } catch(Exception e) { out.println("From scriptlet. Problem: " + e.getMessage()); } %>

1. executeQuery() cannot be used with PreparedStatement
2. code does not contain any errors
3. exceptions thrown by getStatement() are erroneous
4. client gets the employee particulars without any problem

28. Choose the right option for the blank that iterates the loop.

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

 
Creating Array and Printing Elements

forEach loop iteration

    <%-- blank --%>

1. items
2. elements
3. tokens
4. non above

29. Choose all the right options that are true for the following snippet.

a) Procedure

create or replace procedure calculateInterest(x in number, y in number, z in number, k out number)  as  
begin
k:= (x * y* z)/100;
end;

b) Demo.java that calls above procedure

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:XE", "system", "tiger");
       CallableStatement cst = con.prepareCall("{ call calculateInterest(?, ?, ?, ? )}");
       cst.registerOutParameter(4, Types.INTEGER);  
       cst.setInt(1, 10000); 
       cst.setInt(2, 3); 
       cst.setInt(3, 12); 
       cst.execute();
       int m = cst.getInt(4);
       System.out.println("Interest is Rs." + m); 
       cst.close();   con.close();
     }
     catch(Exception e) {  System.out.println("Problem: " + e);  }
  }
}

1. syntax errors exist in cst object creation
2. execute() should be replaced with executeUpdate()
3. procedure creation do not have any errors
4. JSP code does not contain any errors and client gets the interest information without any problem

30. Choose the right option that is true for the following servlet code.

import javax.servlet.*;   import java.io.*;     
public class DemoServlet implements Servlet
{
   ServletConfig c1 = null;
   public void init(ServletConfig config)  { c1 = config;    }   // Line 1       
   public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {  }  // Line 2
   public void destroy()  {    }   				  // Line 3       
   public String getServletInfo()  { return "Hello";   }   	  // Line 4   
   public ServletConfig getServletConfig()  {  return c1;   }  // Line 5 
}

Which lines presence is a must to compile the above servlet successfully.

1. Line 1, Line 2, Line 3
2. Line 4, Line 5
3. Line 1, Line 2, Line 3, Line 4, Line 5
4. the code does not compile

SOLUTIONS

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

Leave a Comment

Your email address will not be published.