Adv-Java Unit 2: Questions & Answers
Unit 2: Servlets • JSP • JSTL -> Generated and Prepared By Thiruselvan (ThiruXD)
1. MULTIPLE CHOICE QUESTIONS (MCQs)
Easy
1. A Servlet is managed by:
a) JVM
b) Web Container
c) Operating System
d) Browser
Ans: b) Web Container
2. Which method is called only once in the Servlet life cycle?
a) service()
b) doGet()
c) init()
d) doPost()
Ans: c) init()
3. Which HTTP method is used when form data is sent in the URL?
a) POST
b) GET
c) PUT
d) DELETE
Ans: b) GET
4. Which object is used to store user-specific data on the server?
a) Cookie
b) ServletContext
c) HttpSession
d) ServletConfig
Ans: c) HttpSession
5. JSP pages are finally converted into:
a) HTML
b) Servlet
c) Applet
d) JavaBean
Ans: b) Servlet
Medium
6. Which method is used for server-side navigation without changing the browser URL?
a) sendRedirect()
b) forward()
c) include()
d) Both b and c
Ans: d) Both b and c
7. What is the default session tracking mechanism used by the container?
a) URL Rewriting
b) Hidden Form Fields
c) Cookies (JSESSIONID)
d) HttpSessionListener
Ans: c) Cookies (JSESSIONID)
8. Which annotation is used to map a URL to a Servlet?
a) @WebFilter
b) @WebServlet
c) @WebListener
d) @MultipartConfig
Ans: b) @WebServlet
9. How many implicit objects are available in a JSP page?
a) 5
b) 7
c) 9
d) 11
Ans: c) 9
10. Which JSTL tag is used for looping?
a) <c:if>
b) <c:forEach>
c) <c:set>
d) <c:out>
Ans: b) <c:forEach>
Hard
11. What happens when request.getSession(false) is called and no session exists?
a) Creates a new session
b) Returns null
c) Throws exception
d) Returns ServletContext
Ans: b) Returns null
12. Which of the following is true about sendRedirect()?
a) Request attributes are preserved
b) It is faster than forward()
c) Browser URL changes
d) It can only redirect within the same application
Ans: c) Browser URL changes
13. In JSP, which implicit object is available only in error pages?
a) request
b) session
c) exception
d) application
Ans: c) exception
14. What is the correct way to declare the JSTL Core library?
a) <%@ taglib prefix="c" uri="java.sun.com/jsp/jstl/core" %>
b) <%@ taglib prefix="c" uri="jakarta.tags.core" %>
c) Both a and b (depending on version)
d) None
Ans: c) Both a and b (depending on version)
15. Which scope has the longest lifetime?
a) page
b) request
c) session
d) application
Ans: d) application
2. THEORY QUESTIONS
Easy
Q1. What is a Servlet?
Ans: A Servlet is a Java class that runs inside a web container and handles HTTP requests to generate dynamic responses. It extends HttpServlet and is completely managed by the container.
Q2. List the three main methods of the Servlet Life Cycle.
Ans:
init()– called once when servlet is loadedservice()– called for every requestdestroy()– called once before servlet is unloaded
Q3. What is the difference between doGet() and doPost()?
| Point | doGet() | doPost() |
|---|---|---|
| Data location | URL (Query String) | Request Body |
| Visibility | Visible in address bar | Not visible |
| Bookmarkable | Yes | No |
| Best used for | Reading / Navigation | Form submission / Sensitive data |
Q4. What is HttpSession?
Ans: HttpSession is a server-side object used to store user-specific data across multiple requests. The container tracks it using the JSESSIONID cookie.
Medium
Q5. Explain the difference between forward() and sendRedirect().
| Point | forward() | sendRedirect() |
|---|---|---|
| Execution | Server-side | Client-side |
| Browser URL | Does not change | Changes |
| Request object | Same | New request is created |
| Attributes | Preserved | Lost |
| Speed | Faster | Slower |
| Can go outside app | No | Yes |
Q6. Why is HTTP called a stateless protocol? How does session management solve this?
Ans: HTTP treats every request as independent and does not remember previous requests. Session management techniques (HttpSession, Cookies, URL Rewriting, Hidden Fields) are used to maintain conversation state between client and server.
Q7. What are the 9 Implicit Objects in JSP?
Ans:
request, response, out, session, application, config, pageContext, page, exception
Q8. What is the difference between <jsp:include> and <%@ include %>?
Ans:
<%@ include %>→ Static include (happens at translation time)<jsp:include>→ Dynamic include (happens at request time)
Hard
Q9. Explain the complete life cycle of a JSP page.
Ans:
- Translation – Container converts .jsp file into a Servlet Java source file
- Compilation – The generated servlet is compiled into .class file
- jspInit() – Called once when the JSP is first loaded
- _jspService() – Called for every client request
- jspDestroy() – Called once before the JSP is unloaded
Q10. What is the purpose of Filters in Servlets? Give two real-life uses.
Ans: Filters are used to intercept requests and responses before they reach the servlet or after the response is generated.
Uses:
- Authentication / Authorization
- Logging
- Compression
- Encoding
- CORS handling
Q11. Explain the four techniques of Session Management.
Ans:
- HttpSession – Server-side object (most preferred)
- Cookies – Small data stored in the browser
- URL Rewriting – Session ID is appended to the URL (used when cookies are disabled)
- Hidden Form Fields – Data is carried in hidden input fields of the form
Q12. Why should we prefer EL + JSTL instead of scriptlets in modern JSP?
Ans:
- Scriptlets mix Java code with HTML → poor readability and maintainability
- EL + JSTL provide clean separation of presentation and logic
- Automatic HTML escaping (
<c:out>) prevents XSS attacks - Easier for web designers to work with the page
3. ANALYTICAL / CODE-BASED QUESTIONS
Easy
Q1. Predict the output of the following code:
@WebServlet("/test")
public class TestServlet extends HttpServlet {
public void init() {
System.out.println("Init");
}
protected void doGet(HttpServletRequest req, HttpServletResponse res) {
System.out.println("doGet");
}
}If the servlet is accessed 3 times, what will be printed in the console?
Ans:
Init
doGet
doGet
doGet(init is called only once)
Q2. What will be the output?
<%! int count = 0; %>
<% count++; %>
Visit Count: <%= count %>If the page is refreshed 4 times, what values will be shown?
Ans: 1, 2, 3, 4
(Declaration variable is instance variable of the generated servlet)
Medium
Q3. Predict the output / behavior:
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException {
req.setAttribute("name", "Rahul");
res.sendRedirect("welcome.jsp");
}In welcome.jsp:
Name: <%= request.getAttribute("name") %>Ans: Name: null
(sendRedirect creates a new request, so attributes are lost)
Q4. Correct the following code if there is any error:
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
response.getWriter().println("Hello");Ans: Error – After forward(), the response is already committed. Writing after forward will throw IllegalStateException. The println statement should be removed.
Q5. What will happen in this code?
HttpSession session = request.getSession(false);
session.setAttribute("user", "Amit");Ans: If no session exists, getSession(false) returns null, and calling setAttribute() on null will throw NullPointerException.
Hard
Q6. Analyze the following code and answer the questions:
@WebServlet("/process")
public class ProcessServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String user = req.getParameter("username");
req.setAttribute("user", user);
RequestDispatcher rd = req.getRequestDispatcher("result.jsp");
rd.forward(req, res);
}
}Questions:
a) Will the browser URL change after form submission?
b) Can result.jsp access the username using request.getAttribute("user")?
c) If we replace forward with sendRedirect("result.jsp"), will the attribute still be available?
Answers:
a) No (forward is server-side)
b) Yes
c) No (attributes are lost in redirect)
Q7. Write the output of the following JSP + JSTL code:
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<c:set var="marks" value="75"/>
<c:choose>
<c:when test="${marks >= 90}">Grade A</c:when>
<c:when test="${marks >= 75}">Grade B</c:when>
<c:when test="${marks >= 50}">Grade C</c:when>
<c:otherwise>Fail</c:otherwise>
</c:choose>Ans: Grade B
Q8. Analytical Question:
A developer wants to show a common header and footer on every page. Which approach is better and why?
Option A:
<%@ include file="header.jsp" %>
... content ...
<%@ include file="footer.jsp" %>Option B:
<jsp:include page="header.jsp"/>
... content ...
<jsp:include page="footer.jsp"/>Ans:
Both work, but:
- Option A (static include) is faster because inclusion happens at translation time.
- Option B (dynamic include) is more flexible if the included page changes frequently or needs request-time data.
In most cases for header/footer, static include (
<%@ include %>) is preferred.
Q9. Code Writing (Analytical):
Write a Servlet that:
- Accepts username and password using POST
- If username = "admin" and password = "1234", create a session and redirect to
home.jsp - Otherwise forward to
login.jspwith an error message
Sample Answer:
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String user = req.getParameter("username");
String pass = req.getParameter("password");
if ("admin".equals(user) && "1234".equals(pass)) {
HttpSession session = req.getSession();
session.setAttribute("user", user);
res.sendRedirect("home.jsp");
} else {
req.setAttribute("error", "Invalid Username or Password");
req.getRequestDispatcher("login.jsp").forward(req, res);
}
}
}Q10. Hard Conceptual:
Why is it recommended to call session.invalidate() on logout instead of just removing attributes?
Ans:
removeAttribute() only removes specific data, but the session object still exists and the same JSESSIONID remains valid.
invalidate() completely destroys the session and makes the JSESSIONID invalid, which is more secure and prevents session fixation attacks.
Quick Exam Tips for Module-2
- Always remember: init() and destroy() → once, service() → many times
- forward() = same request, URL does not change
- sendRedirect() = new request, URL changes
- Session tracking default = Cookie (JSESSIONID)
- JSP → translated to Servlet
- Prefer EL + JSTL over scriptlets
- 9 Implicit objects – especially
exceptionis only for error pages <c:forEach>,<c:if>,<c:choose>,<c:out>,<c:set>are most important JSTL tags