Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

How do I include a servlet in a JSP?

Posted on 2002-07-28
16
Medium Priority
?
213 Views
Last Modified: 2013-11-18
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
0
Comment
Question by:cjmackenzie
  • 7
  • 4
  • 3
  • +1
16 Comments
 
LVL 28

Expert Comment

by:rrz
ID: 7183538
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
 
LVL 19

Expert Comment

by:cheekycj
ID: 7184112
Why don't you add a mapping to the servlet and do the file include to that mapping.

CJ
0
 
LVL 92

Expert Comment

by:objects
ID: 7184194
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:cjmackenzie
ID: 7184758
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
 
LVL 92

Expert Comment

by:objects
ID: 7184782
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
 

Author Comment

by:cjmackenzie
ID: 7184794
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
 

Author Comment

by:cjmackenzie
ID: 7184817
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
 

Author Comment

by:cjmackenzie
ID: 7184819
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
 
LVL 92

Accepted Solution

by:
objects earned 300 total points
ID: 7184825
> try writing the code as a scriptlet

If you're only interested in jsp then try simply using the jsp:forward tag.
0
 

Author Comment

by:cjmackenzie
ID: 7184866
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
 
LVL 28

Expert Comment

by:rrz
ID: 7185374
For your original question,
Did you try changing the flush attribute?
<jsp:include page="/servlet/IdentifyUser" flush="false" />
0
 
LVL 92

Expert Comment

by:objects
ID: 7186839
0
 

Author Comment

by:cjmackenzie
ID: 7187567
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
 
LVL 19

Expert Comment

by:cheekycj
ID: 7188040
no problem, as long as you found a working solution.

CJ
0
 
LVL 28

Expert Comment

by:rrz
ID: 7188203
>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
 

Author Comment

by:cjmackenzie
ID: 7190156
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

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

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.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Browsers only know CSS so your awesome SASS code needs to be translated into normal CSS. Here I'll try to explain what you should aim for in order to take full advantage of SASS.
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.
Suggested Courses

916 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question