Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

How do I include a servlet in a JSP?

Posted on 2002-07-28
16
205 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 27

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
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 

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 75 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 27

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 27

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: 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.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How can I write .htaccess code to redirect 301 pages? 1 126
 shows up in Outlook, not OWA or on phone 3 71
.php tree directory? 5 83
Grunt script for Build Process 1 42
This article covers the basics of the Sass, which is a CSS extension language. You will learn about variables, mixins, and nesting.
Shoutout to Emily Plummer (http://www.experts-exchange.com/members/eplummer26.html) for giving me this article! She did most of it, I just finished it up and posted it for her :)    Introduction In a previous article (http://www.experts-exchang…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…

791 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