Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How do I include a servlet in a JSP?

Posted on 2002-07-28
16
Medium Priority
?
211 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
[X]
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
  • 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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Preface In the first article: A Better Website Login System (http://www.experts-exchange.com/A_2902.html) I introduced the EE Collaborative Login System and its intended purpose. In this article I will discuss some of the design consideratio…
Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
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…

715 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