How do I include a servlet in a JSP?

I have written a servlet containing the following code:

Cookie[] cookies = request.getCookies();
String staffName = ServletUtilities.getCookieValue(cookies, "user");
if(staffName == null) {
   String address = "/login.jsp";
   RequestDispatcher dispatcher = getServletContext).getRequestDispatcher(address);
   dispatcher.forward(request, response);
   }
   else {
      HttpSession session = request.getSession(true);
      session.setAttribute("user", staffName);
   }

This is supposed to get the user from a cookie or forward to a login page.
To run this I thought I could include it in a titlebar.jsp with the following code:

<%@ include file="/IdentifyUser.class" %>

When I executed my program I get the text of my java program in the webpage when I expected to be presented by a login page.

Can you explain what is going on?

If I want to include a servlet in a JSP how do I do it?

Colin
cjmackenzieAsked:
Who is Participating?
 
objectsConnect With a Mentor Commented:
> try writing the code as a scriptlet

If you're only interested in jsp then try simply using the jsp:forward tag.
0
 
rrzCommented:
I don't think you can use the include directive because that construct lets you  insert code into the main page before that main page is translated into a servlet. Thus you were trying to add bytecode(in IdentifyUser.class) to text(in titlebar.jsp).
You can use the  jsp:include action.
<jsp:include page="/servlet/IdentifyUser" flush="true" />
This will include the output of your servlet at the time that titlebar.jsp  is requested.
0
 
cheekycjCommented:
Why don't you add a mapping to the servlet and do the file include to that mapping.

CJ
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
objectsCommented:
You can't include bytecode as mentioned above.
You could put the above code into a method and then call that method from both your jsp and servlet.

public class Utils
{
  public static void doStuff(HttpServletRequest request, HttpServletResponse response)
  {
    Cookie[] cookies = request.getCookies();
    String staffName = ServletUtilities.getCookieValue(cookies, "user");
    if(staffName == null) {
      String address = "/login.jsp";
      RequestDispatcher dispatcher =
       getServletContext).getRequestDispatcher(address);
      dispatcher.forward(request, response);
     }
     else {
       HttpSession session = request.getSession(true);
       session.setAttribute("user", staffName);
     }
  }
}

Then in you jsp:

<%  Utils.doStuff(request, response); %>
0
 
cjmackenzieAuthor Commented:
OK I'm getting a better understanding but I'm hitting other problems. If I use the jsp:include action, I get an error: "Cannot forward as OutputStream or Writer has already been obtained". I guess that's because I've included from a jsp.
I suspect I'd get the same error if I moved the method to a utility class. I tried it anyway and I can't compile it because I call getServletContext() and a static class cannot inherit from servlet.
I think I'm going to try writing the code as a scriptlet in the titlebar...........

Colin
0
 
objectsCommented:
Then just pass the context:

public class Utils
{
 public static void doStuff(ServletContext context, HttpServletRequest request, HttpServletResponse response)
 {
   Cookie[] cookies = request.getCookies();
   String staffName = ServletUtilities.getCookieValue(cookies, "user");
   if(staffName == null) {
     String address = "/login.jsp";
     RequestDispatcher dispatcher =
      context.getRequestDispatcher(address);
     dispatcher.forward(request, response);
    }
    else {
      HttpSession session = request.getSession(true);
      session.setAttribute("user", staffName);
    }
 }
}
0
 
cjmackenzieAuthor Commented:
OK I'm getting a better understanding but I'm hitting other problems. If I use the jsp:include action, I get an error: "Cannot forward as OutputStream or Writer has already been obtained". I guess that's because I've included from a jsp.
I suspect I'd get the same error if I moved the method to a utility class. I tried it anyway and I can't compile it because I call getServletContext() and a static class cannot inherit from servlet.
I think I'm going to try writing the code as a scriptlet in the titlebar...........

Colin
0
 
cjmackenzieAuthor Commented:
Of course, including the ServletContext should have been obvious. Wouldn't I still have the problem that I can't forward the response?
In the meantime, I have placed the following code into my jsp, it works and I think its quite tidy:
<%      
Cookie[] cookies = request.getCookies();
String staffName = ServletUtilities.getCookieValue(cookies, "user");
if(staffName == null) {
%>
    <jsp:forward page = "/login.jsp" />
<%
}
else {
    session.setAttribute("user", staffName);
}
%>

Colin
0
 
cjmackenzieAuthor Commented:
Of course, including the ServletContext should have been obvious. Wouldn't I still have the problem that I can't forward the response?
In the meantime, I have placed the following code into my jsp, it works and I think its quite tidy:
<%      
Cookie[] cookies = request.getCookies();
String staffName = ServletUtilities.getCookieValue(cookies, "user");
if(staffName == null) {
%>
    <jsp:forward page = "/login.jsp" />
<%
}
else {
    session.setAttribute("user", staffName);
}
%>

Colin
0
 
cjmackenzieAuthor Commented:
I think we are agreed that the scriptlet is best because I want to do a conditional forward from my code.
My original question is answered:
I should use jsp:forward if I want to include the output from a servlet.
0
 
rrzCommented:
For your original question,
Did you try changing the flush attribute?
<jsp:include page="/servlet/IdentifyUser" flush="false" />
0
 
objectsCommented:
0
 
cjmackenzieAuthor Commented:
I didn't try changing the flush attribute. What does it do?

Here what my check_user.jsp code looks like now:

<%
String staffName = ServletUtilities.getCookieValue(request, "staffName");
if(staffName == null) {
%>
<jsp:forward page = "/login.jsp" />
<%
}
else {
%>
Welcome <%= session.getAttribute("staffName") %>. If you are not <%= session.getAttribute("staffName") %>
<A href="/login.jsp">please click here </A>to log in
<jsp:include page = "/titlebar_body_common.jsp" flush = "true" />//I had to include the titlebar in the check_user rather than vice versa
<%
}
%>

The login page calls a SetCookie servlet:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
        String staffName = request.getParameter("staffName");
        String password = request.getParameter("password");
        // Check the password is correct using the database

        if(password.equals("password")) {
            Cookie userCookie = new Cookie("staffName",staffName);
            userCookie.setMaxAge(60*60*24*365);
            response.addCookie(userCookie);
            HttpSession session = request.getSession(true);            
            session.setAttribute("staffName", staffName);
            RequestDispatcher dispatcher =
                request.getRequestDispatcher("/check_user.jsp");//will be a home page in final application
            dispatcher.include(request, response);
        }
        else {
            java.io.PrintWriter out = response.getWriter();            
            out.println("<center>");
            out.println("Login failed");
            out.println("Please re-enter password");
            out.println("</center>");
            RequestDispatcher dispatcher = request.getRequestDispatcher("/login.jsp");
            dispatcher.include(request, response);
        }
    }

Everything seems to be working now. Thanks to everyone for helping me understand how this works. Apologies to cheekycj - I didn't know what you meant by a mapping so I didn't follow that up. No doubt I missed a trick there.......

Colin
0
 
cheekycjCommented:
no problem, as long as you found a working solution.

CJ
0
 
rrzCommented:
>I didn't try changing the flush attribute. What does it do?
I was thinking that it might prevent the error you received
>"Cannot forward as OutputStream or Writer has already been obtained".
0
 
cjmackenzieAuthor Commented:
OK I tried to change the flush attribute and my compiler wouldn't let me - "true is only option allowed in JSP version 1.0".
I've changed my <jsp:forward page = "/login.jsp" /> to be an include, and the rest of my page is entirely in the else clause, so it works now.

Colin
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.