# JSP & Servlet Interview Questions and Answers
## 1. What is a Servlet?
A Servlet is a Java program that runs on a web server and handles client requests.
It extends the capabilities of a server by generating dynamic web content.
### Example: Simple Servlet
```java
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().println("Hello, Servlet!");
}
}
```
---
## 2. What is JSP?
JSP (JavaServer Pages) is a technology that allows embedding Java code inside HTML
pages for dynamic web content generation.
### Example: Displaying Data in JSP
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<body>
<h2>Welcome, <%= request.getParameter("name") %>!</h2>
</body>
</html>
```
---
## 3. Difference Between JSP and Servlets?
| Feature | JSP | Servlet |
|---------|----|---------|
| Type | HTML-based with Java | Java-based |
| Speed | Slower than Servlets | Faster |
| Use Case | UI Pages | Backend Logic |
---
## 4. Servlet Lifecycle?
1. **Loading & Instantiation** - Servlet class is loaded.
2. **Initialization (`init()`)** - Called once.
3. **Request Handling (`service()`)** - Called for each request.
4. **Destruction (`destroy()`)** - Called when the servlet is removed.
### Example:
```java
public void init() { System.out.println("Servlet Initialized"); }
public void destroy() { System.out.println("Servlet Destroyed"); }
```
---
## 5. Difference Between `doGet()` and `doPost()`?
| Feature | `doGet()` | `doPost()` |
|---------|----------|----------|
| Data Visibility | Sent in URL | Sent in Body |
| Security | Less secure | More secure |
| Use Case | Fetch Data | Submit Data |
### Example:
```java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
response.getWriter().println("Hello, " + username);
}
```
---
## 6. What is RequestDispatcher?
It forwards or includes requests between Servlets/JSPs.
### Example (Forwarding a Request):
```java
RequestDispatcher rd = request.getRequestDispatcher("dashboard.jsp");
rd.forward(request, response);
```
---
## 7. Difference Between `forward()` and `sendRedirect()`?
| Feature | `forward()` | `sendRedirect()` |
|---------|------------|------------|
| Type | Server-side | Client-side |
| URL Change | No | Yes |
---
## 8. What are JSP Implicit Objects?
| Object | Description |
|--------|------------|
| `request` | Client request details |
| `session` | User session data |
| `out` | Sends output to browser |
### Example:
```jsp
Welcome, ${sessionScope.username}!
```
---
## 9. What is `session` Scope vs `application` Scope?
| Feature | `session` | `application` |
|---------|----------|--------------|
| Lifetime | Per user session | Until server restarts |
| Data Access | User-specific | Shared across users |
---
## 10. What is ServletContext and ServletConfig?
- **ServletContext**: Stores global application data.
- **ServletConfig**: Stores servlet-specific configuration.
---
## 11. What are Filters?
Filters intercept requests/responses for logging, authentication, etc.
### Example (Authentication Filter):
```java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpSession session = request.getSession(false);
if (session == null) {
((HttpServletResponse) res).sendRedirect("login.jsp");
} else {
chain.doFilter(req, res);
}
}
```
---
## 12. How to Handle Sessions in Servlets?
```java
HttpSession session = request.getSession();
session.setAttribute("username", "John");
```
---
## 13. What are Cookies in Servlets?
Cookies store user preferences in the browser.
### Example (Setting a Cookie):
```java
Cookie cookie = new Cookie("user", "John");
response.addCookie(cookie);
```
---
## 14. What is Expression Language (EL)?
EL simplifies accessing request/session attributes.
### Example:
```jsp
Welcome, ${sessionScope.username}
```
---
## 15. What is JSTL?
JSTL provides tags for common operations.
### Example (Loop in JSTL):
```jsp
<c:forEach var="name" items="${namesList}">
<p>${name}</p>
</c:forEach>
```
---
## 16. What is MVC in JSP and Servlets?
- **Model**: Business logic (JavaBeans, DAO)
- **View**: UI (JSP)
- **Controller**: Handles requests (Servlets)
### Example (Servlet Controller):
```java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
request.setAttribute("user", username);
RequestDispatcher rd = request.getRequestDispatcher("welcome.jsp");
rd.forward(request, response);
}
```
---
## 17. What is `web.xml`?
`web.xml` is a deployment descriptor that configures Servlets, Filters, and session
settings.
---
## 18. What is an `HttpSessionListener`?
It tracks session creation and destruction.
### Example:
```java
public class MySessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
System.out.println("Session Created: " + event.getSession().getId());
}
public void sessionDestroyed(HttpSessionEvent event) {
System.out.println("Session Destroyed");
}
}
```
---
## 19. What is a `ServletConfig` Parameter?
Defines per-servlet configurations in `web.xml`.
### Example:
```xml
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.example.MyServlet</servlet-class>
<init-param>
<param-name>database</param-name>
<param-value>MySQL</param-value>
</init-param>
</servlet>
```
---
## 20. What is the Difference Between JSP and Thymeleaf?
| Feature | JSP | Thymeleaf |
|---------|----|----------|
| Language | Java-based | Java & HTML |
| Performance | Slower | Faster |
| Use Case | Traditional Java EE | Modern Spring Apps |