Solved

How do I include a servlet in a JSP?

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

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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

When you work with shopping cart / ecommerce relates web sites, you need to pass the certain form post details to the payment gateway process page with required details for the products items you give to order. Also you may need to track the ordered…
SASS allows you to treat your CSS code in a more OOP way. Let's have a look on how you can structure your code in order for it to be easily maintained and reused.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

759 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now