Servlet interview questions [ Part 4 ]

1. How does Cookies work in Servlets?
Cookies are used a lot in web client-server communication, it?s not something specific to java. Cookies are text data sent by server to the client and it gets saved at the client local machine.
Servlet API provides cookies support through javax.servlet.http.Cookie class that implements Serializable and Cloneable interfaces.
HttpServletRequest getCookies() method is provided to get the array of Cookies from request, since there is no point of adding Cookie to request, there are no methods to set or add cookie to request.
Similarly HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in response header, there are no getter methods for cookie.

2. How to add cookie in browser using servlet?

3. How to remove cookie from browser using servlet?

4. How to notify an object in session when session is invalidated or timed­out?
If we have to make sure an object gets notified when session is destroyed, the object should implement javax.servlet.http.HttpSessionBindingListener interface. This interface defines two callback methods ? valueBound() and valueUnbound() that we can define to implement processing logic when the object is added as attribute to the session and when session is destroyed.

5. Use of hidden fields?

6. What is the effective way to make sure all the servlets are accessible only when user has a valid session?

7. Why do we have servlet filters?

8. Why do we have servlet listeners?

9. How to handle exceptions thrown by application with another servlet?

10. Write a servlet to upload file on server.
<form action="go" method="post" enctype="multipart/form-data">  
Select File:<input type="file" name="fname"/><br/> 
<input type="submit" value="upload"/>

public class UploadServlet extends HttpServlet {  
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
PrintWriter out = response.getWriter(); 
MultipartRequest m=new MultipartRequest(request,"d:/new"); 
out.print("successfully uploaded"); 

Related Post