how do i load a jsp page from a jsp page? - java

I am writing a JSP code which goes like this:
<% if(---)
{----}
else
{ ---
%>
<jsp:forward page="error.jsp">
<jsp:param name="" value=""/>
</jsp:forward>
<%
}
%>
The error.jsp is in the same directory as the current jsp file still it is throwing "class not found exception". What to do?

Not much clear from your question what you are trying to achieve but If you are adding the another jsp page within current jsp page then use jsp:include otherwise if trying to redirect to another jsp page then following could be used.
Use in scriptlet response.sendRedirect in your case as below:
<%
response.setHeader("header_key", "header_value");
response.sendRedirect("your_page_location")
%>
Above could be used for external pages as well like "www.google.com"
On the other hand you could use request forward with all old parameters and data from calling page. See below:
RequestDispatcher rd = servletContext.getRequestDispatcher("/pathToResource");
rd.forward(request, response);
Also, another easy way could be to submit a form with action="your_jsp.jsp" but this should be used in case of form submissions where you are sending some data etc.
Make choice for any of above options on a case basis.
Hope it helps!

Related

JSP should redirect to a dynamic URL in a new window or tab

I have a jsp page from which i have to redirect to an external URL and this URL has a dynamic field at the end which i bring from another class. The task for me is to open this url in a new tab or window when that jsp is loaded. I tried the target attribute in the HTML tag but it did not work.
<html target="_blank">
<body>
<%
String filename=(String)request.getAttribute("fileToOpen");
response.sendRedirect("http://manuals/example/"+filename+".pdf");
%>
</body>
</html>
have you tried javascript?
you can put a tag (which are always loaded before the HTML).
for example (http://jsfiddle.net/yeLpy4st/)
For your case you can use something like
<%
String filename=(String)request.getAttribute("fileToOpen");
%>
<script>
window.open("http://manuals/example/"+<%= filename %>+".pdf", "_blank");
</script>
you can also change where you want the new page to open (in this case it's '_blank'), a good reference is Window open() Method reference from W3Schools
You could try it with Javascript :
window.open('www.newtab.com','_newtab');
I used the 'target' attribute in the anchor tag. I did not use JavaScript because of some application constraints. It worked!

How to call servlet from a jsp

I have a question, how to call a servlet from a jsp(chart.jsp) without using <jsp:include page="/servletURL" />because I tried before and I don't know if this is the right reason but it crashes when I use this code above.
I put in my doGet() method to retrieve information from DB and populate my dropdownlist (in chart.jsp) using JSTL+option and then redirect to my page (the same page), what I believe is that everytime the browser writes a new page using c:forEachtag it calls again my servlet and there is a never ending loop (Again, that's just my presumptions)
Here is my code to make it more clear:
my servlet:
ArrayList<Machine> foundMachines = MachineDB.getAllMachines();
request.getSession().setAttribute("foundMachineList", foundMachines);
RequestDispatcher rd = request.getRequestDispatcher("charts/chart.jsp");
rd.forward(request, response);
my jsp:
<jsp:include page="/searchServlet" />
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach var="machine" items="${sessionScope.foundMachineList}">
<option value="${machine.machineId}">${Machine.machineName}
</option>
</c:forEach>
So my question is why my <jsp:include page="/servletURL" /> tag crashes my page and how to fix it. Any sugestion is welcome
Use
response.sendRedirect("//your servlet name");
Most probably is not related but change
${Machine.machineName} to ${machine.machineName}

Setting parent jsp variables in child jsp

I have a parent jsp a.jsp which includes another jsp b.jsp. I am calculating some values in b.jsp which needs to be used in parent jsp a.jsp , which will pass this calculated value to another jsp say c.jsp. How can I evaluate value in child jsp and pass it to parent jsp before that page completely loads?
How are you including the "child" jar inside the parent? static or dynamic import?
if you have
<%# include file="myFile.jsp" %>
change it by
<jsp:include file="myFile.jsp" />
then in the parent set a property in the request (not in the session, that would be "dirtier"):
<% request.setAttribute("attrName", myValue) %>
finally, in the "child" jsp:
<% myValue = (MyValueType)request.getAttribute("attrName") %>
If you need to pass an attribute between including and included jsp (and viceversa)you should use the page context, which is the more short context (from lifecycle perspective)
You can set variables in the request in b.jsp, and use them in parent.jsp. But you can only use them in the parent jsp after the <jsp:include> tag. Remember that this is all evaluated on the server side, so when you say "before that page completely loads," you can be guaranteed that the server has evaluated it before the browser has loaded it. If you mean that you want to delay evaluation on the server until some code below it is evaluated, that's not going to be possible. At least not like this.
b.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="myVar" scope="request" value="Hello"/>
parent.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<jsp:include page="b.jsp"></jsp:include>
<span>
The value is ${requestScope.myVar}.
</span>
You could you session scope to accomplish this.
(b.jsp)
session.setAttribute("value",value);
(c.jsp)
session.getAttribute("value");
However, I would recommend doing some major restructuring instead. In your example, the value of your data depends on the order of the elements on the page. If you ever need to re-arrange things (for instance, moving the b.jsp include after the c.jsp include), you risk breaking the business logic.
A good pattern for web development is a model-view-controller pattern. The "controller" determines what page should be displayed, the "model" calculates all the data and makes it available, and the "view" does the display and formatting.
I would recommend reviewing this article, which is helpful for understanding why MVC is a valuable approach:
http://www.javaranch.com/journal/200603/Journal200603.jsp#a5
Edit: As other users have mentioned, request scope would be cleaner than session scope. However, I still recommend determining the value first before writing any display content.

JSP: Use information from one page to another

I currently have a JSP page with a Form for the user to enter their name, but what I want is to get the user forwarded to a different JSP page after form submission and to carry on their name to be used.
I don't want to use JSTL EL just simple JSP uses.
I was thinking of using a bean storing the detail in a session but how would it work.
Thanks.
You'd have JSP enter the info into a form and POST it to a servlet. The servlet would validate the form input, instantiate the bean, add it to session, and redirect the response to the second JSP to display.
You need a servlet in-between. JSPs using JSTL are for display; using the servlet this way is called MVC 2. Another way to think of it is the front controller pattern, where a single servlet handles all mapped requests and simply routes them to controllers/handlers.
duffymo you have the best idea but here is a quick solution by just passing things through the JSP.
Here is the JSP with the form
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Simple jsp page</title></head>
<body><form name="test" action="./stackTest2.jsp" method="POST">
Text Field<input type="text" name="textField">
<input type="submit">
</form> </body>
</html>
and then the second page looks like this:
<html>
<head><title>Simple jsp page</title></head>
<body><%=request.getParameter("textField")%></body>
</html>
And then put information in a hidden field, you can get information by using the request.getParameter method. This just prints out what was in the form, but using the same idea for inputting it in to the hidden field in a form. I recommend this as all my experience with sessions have ended in a failure. I STRONGLY DO NOT Recommend this method, MVC is a much better way of developing things.
Dean

How to check if external URL content loads correctly into an <IFRAME> in JSP page using HTTP response code

I am looking into a solution that would allow to load an external URL content into an <iframe> element in a JSP page.
However, before displaying any content, JSP code would first check for HTTP response of included in iframe's src URL and if 200/OK returned then display it otherwise a custom message or another page is displayed instead. I'd like to do it on the server side only.
Is there a way of achieving it without AJAX / user side scripting that could have potential cross-browser incompatibilities?
You can make use of JSTL (just drop jstl-1.2.jar in /WEB-INF/lib) c:import tag to import an external resource, which will throw FileNotFoundException if the URL is invalid, which in turn can be catched using JSTL c:catch tag. You can finally use JSTL c:choose to check whether to display the iframe or the eventual error.
Here's an SSCCE, copy'n'paste'n'run it (with JSTL installed):
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!doctype html>
<html lang="en">
<head>
<title>SO question 2291085</title>
</head>
<body>
<c:set var="url" value="http://google.com" />
<c:catch var="e">
<c:import url="${url}" varReader="ignore" />
</c:catch>
<c:choose>
<c:when test="${empty e}">
<iframe src="${url}"></iframe>
</c:when>
<c:otherwise>
<p>Error! ${e}</p>
</c:otherwise>
</c:choose>
</body>
</html>
Change http://google.com to http://google.com/foo or something invalid, you'll see that the error shows instead.
Note that I used varReader="ignore" to have it buffered but unread, so that it won't entirely hauled in which may be expensive because after all you're requesting the same URL twice.
Update: Alternatively, you can use a Servlet for this which preprocesses the request inside doGet() method with help of java.net.URLConnection. Here's a kickoff example.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
URL url = new URL("http://google.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int status = connection.getResponseCode(); // 200 = OK, 404 = Not Found, etc.
if (status == 200) {
request.setAttribute("url", url);
} else {
// Do your thing to set custom message or request another page.
}
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}
...and in page.jsp then just have something like
<c:if test="${not empty url}">
<iframe src="${url}"></iframe>
</c:if>
Map the servlet on an url-pattern of something like /foo and call it on http:/example.com/contexty/foo instead of the JSP.
The actual loading of the <iframe> is going to take place because the client loads it. There have simply got to be better ways of validating the URL than by trying to include it via JSP. Do it in Java, or just don't do it at all: have the server return a "not found" page that runs some Javascript to hide the iframe. (Have it show an error for people browsing with Javascript turned off.)

Categories