How are Servlets and JSP Pages related?

October 24th, 2006 Admin Posted in Java Interview Questions No Comments »

JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed.

AddThis Social Bookmark Button

How can I set a cookie in JSP?

October 24th, 2006 Admin Posted in Java Interview Questions No Comments »

response.setHeader(”Set-Cookie”, “cookie string”);
To give the response-object to a bean, write a method setResponse
(HttpServletResponse response)
- to the bean, and in jsp-file:
<%
bean.setResponse (response);
%>
114) How can I delete a cookie with JSP?
Ans: Say that I have a cookie called “foo,” that I set a while ago & I want it to go away. I simply:
< %
Cookie killCookie = new Cookie("foo", null);
KillCookie.setPath("/");
killCookie.setMaxAge(0);
response.addCookie(killCookie);
% >

AddThis Social Bookmark Button

How do you pass data (including JavaBeans) to a JSP from a servlet?

October 24th, 2006 Admin Posted in Java Interview Questions No Comments »

(1) Request Lifetime: Using this technique to pass beans, a request dispatcher (using either “include” or forward ” ) can be called. This bean will disappear after processing this request has been completed.
Servlet: request.setAttribute( “theBean”, myBean );
RequestDispatcher rd =   getServletContext( ).getRequestDispatcher( “Thepage.jsp” );
rd.forward(request, response);
JSP PAGE:
< jsp: useBean id="theBean" scope="request" class="....." />
(2) Session Lifetime: Using this technique to pass beans that are relevant to a particular session ( such as in individual user login ) over a number of requests. This bean will disappear when the session is invalidated or it times out, or when you remove it.Servlet:
HttpSession session = request.getSession(true);
session.putValue(”theBean”, myBean);
/* You can do a request dispatcher here,or just let the bean be visible on the
next request */
JSP Page:

3) Application Lifetime: Using this technique to pass beans that are relevant to all servlets and JSP pages in a particular app, for all users. For example, I use this to make a JDBC connection pool object available to the various servlets   and JSP pages in my apps. This bean will disappear when the servlet engine is shut down, or when you remove it.
Servlet:
GetServletContext(). setAttribute(”theBean”, myBean);
JSP PAGE:
< jsp:useBean id="theBean" scope="application" class="..." / >

AddThis Social Bookmark Button