JSP not detecting the javascript file - java

From a servlet, I'm forwarding the request to a JSP page which renders a FusionChart.
But I've a problem in loading the chart. The JSP file is not detecting the JavaScript file. The folder structure is:
axis
|
WebContent
|
WEB-INF
|
classes
|_ com
|_FusionCharts.js
|_MyChartJsp.jsp
|_Line.swf
And the JSP code:
<html>
<head>
<script language="text/javascript" src="/WEB-INF/classes/FusionCharts.js"></script>
</head>
<body bgcolor="#ffffff">
<div id="chartdiv" align="left">The chart will appear within
this DIV. This text will be replaced by the chart.</div>
<script type="text/javascript">
var foo = //value fetched from DAO
var myChart = new FusionCharts("/WEB-INF/classes/Line.swf",
"myChartId", "1000", "500");
myChart
.setDataXML("<graph caption='aCaption' xAxisName='xAxis' yAxisName='yAxis' showNames='1' decimalPrecision='0' formatNumberScale='0'>"+foo+"</graph>");
myChart.render("chartdiv");
</script>
</body>
</html>
The Servlet code to forward the request:
final RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/classes/MyChartJsp.jsp");
requestDispatcher.forward(request, response);
The request is getting forwarded to the JSP. But the chart is not getting displayed because it is unable to figure out what FusionCharts is in the line
var myChart = new FusionCharts("/WEB-INF/classes/Line.swf",
"myChartId", "1000", "500");
I tried
src="/FusionCharts.js"
src="FusionCharts.js"
but no luck.
Has it something to do with the request being forwarded??

You cannot have .js (or .swf, .jpg, etc.) files in WEB-INF - they are not publically accessible.
Move it to /js/
There is no reason to hide static resources (like scripts and css) in WEB-INF. If you insist on that, you should make a servlet that, given the name of the js/css, would read it from its location and will serve it as a response. This is what the default servlet does when you access static resources.
The flow of the page loading is as follows: the browser sends a request to the servlet; the servlet forwards internally to the JSP, and the JSP is rendered as a response; then the browser parses the <script> tag and fires another request to the script. If the script is not accessible via URL, it's not loaded.
Then, to make the script url fixed to the servlet context root, use
src="<c:url value="/js/script.js" />"
This will work regardless of what is the current url

Not the cause of your problem, but also note that your <script> element is incorrect. It should be <script type="text/javascript"....
(I tried to post this as a comment, but for some reason it wouldn't let me.)

I was facing same issue. In my case when I calling the myFile.jsp directly its reading the myFile.js;
But when calling through login-> myFile.jsp, its not reading the myFile.js;
After analyzing the path through the Developer tools :=> console, I found that its inserting the uri, so final path was incorrect.
Final Solution:
I'd used the absolute path for all .js and .css. Now its called from everywhere.
My Project Structure is:
In my servlet-context.xml
i) <context:component-scan base-package="com.SBP.SHWeb" />
ii) <resources mapping="/resources/**" location="/resources/" />
My old path for including .js was: /resources/MyJs/myfile.js ===> Its not get called sometimes.
My Absolute path, which get called from all places is like this:
/SHweb/resources/MyJs/myfile.js ==> Its get called from everywhere.
Hope it help you.

Related

Load Jsp page from Another Jsp page inside IFrame

I am trying to load a JSP page in IFrame under webapp/WEB-INF/jsps like following:-
<iframe id="frame1" frameborder="1" src="framebody.jsp" width="100%" height="350px">
Note:- Both the pages are in same directory webapp/WEB-INF/jsps.
Getting Exception on browser console : -
Failed to load resource: the server responded with a status of 500 .
Files located within WEB-INF folder can not be accessed directly.
You need to make the src to a servlet request,and make the response of the request to the jsp file.
<iframe id="frame1" frameborder="1" src="queryBody" width="100%" height="350px">
#RequestMapping("queryBody")
public String queryBody(){
return "framebody.jsp";//make sure you have set the prefix to /WEB-INF/jsps
}

jsp ${pageContext.request.contextPath} dosent get requested

Currently i have a .jsp project where my welcome page is a servlet
<welcome-file>frontpage</welcome-file>
The servlet sets gets two ressources, a header file containing the < nav> and a footer containing the < footer>
request.setAttribute("header1", sc.getResource("/includes/nav.jsp").toString());
request.setAttribute("footer", sc.getResource("/includes/footer.jsp").toString());
And forwards to the index.jsp page
getServletContext().getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response);
My question is.
When i get the ressource (footer.jsp), how can i in the footer.jsp dynamically import / include images?
I tried the following
<img src="${pageContext.request.contextPath}/images/picture1.png" alt="picture1"/>
But the expression ${pageContext.request.contextPath} gets treated as a string instead of a command, and does not get the context path.
I suspect its because the content of the footer.jsp is fetched in this manner and their for the context path isint actually ever requested within the footer.jsp.
But how do i solve this?
add <%# page isELIgnored="false" %> in top of your JSP page, to enable expression language.
and to include a JSP page with other use <jsp:include like:
<jsp:include page="/includes/nav.jsp"/>
<jsp:include page="/includes/footer.jsp"/>
This is not the way to include stuff. Use jsp:include action to include the header/footer. If for some reason you really want to do it in the servlet, see this post. As long as you just grab a resource like you do, you're reading the file like any text, there is no JSP compilation/evaluation.

Struts Action property can't be accessed from external javaScript

I am working on a project using struts2. In my Action class I have a String testString with setter/getter and I can access it
from my jsp file using ${testString}. Works fine.
Now I need to access it form javascript and tried an internal script inside my jsp file like this:
<script >
function testJs() {
alert("${testString}");
}
</script>
I used the testJs() method in an button onclick
<input type="button" value="click me " onclick="testJs()" >
This also works fine, means when i click the button is shows me the value of the string(Hello World) of my Action class in an alert.
But the problem is when i added this method in a external (test.js) file and added the .js file in jsp file like this
<script src="resource/js/test.js" ></script>
The alert message don't show the String value. its just show ${testString}
The method testJs() get and parse the String value from an internal script but cant from an external script!!!
Any possible reason or explanation for this.?
If any body want some additional information please let me know.
When you write EL(Expression Language) in your .jsp file, that .jsp file is parse by its JSP container and EL are processed. Consider the following code :
anyfile.jsp
<script type="text/javascript">
function testJs() {
alert("${testString}"); // JSP Container will replace '${testString}' with its value
}
</script>
JSP container did not processed any of the above code Except EL, and therefore only ${testingString} is replaced. I mean, container do not know about <script> or function testJs().
JSP container will only process the files with .jsp (or .jspx, or some other files) extension. In the above code your javascript was inside .jsp file.
But on the other hand, when you replaced above code with this -
<script src="resource/js/test.js" ></script>
Now the previous code is inside test.js file. But how container can know about that!
You are expecting JSP container to understand this code i.e. to understand that test.js is added as javascript in the .jsp file by using <script> element and src attribute. But it didn't.
Container actually not have to do anything with this code. And your code will be sent to client without any changes.
But if you stills want to use your javascript code to work from other file, you can use following code :
anyfile.jsp
<script type="text/javascript">
<jsp:include page="test.jsp" />
</script>
And
test.jsp
<%#page contentType="text/javascript" pageEncoding="UTF-8"%>
function go() {
alert("${testString}");
}

Servlet in Eclipse - Where to put static content [duplicate]

This question already has answers here:
Simplest way to serve static data from outside the application server in a Java web application
(10 answers)
Closed 9 years ago.
When writing a servlet with Eclipse, where am I to put my static content (images, CSS, etc.), so that I can make my HTML link to it (e.g. <img src="http://localhost:8080/context/image.png>). I have tried putting it into the WebContent directory, but that didn't work (or I didn't know how to link to it, I tried <img src="image.png"> and also <img src="http://localhost:8080/context/image.png">).
I attached an image of my Project Explorer, so you can maybe sort it in.
To make it easier to find, here is everything I posted in comments or elsewhere:
The project's web.xml: http://pastebin.com/sTg4ugyw
My Servlet code: http://pastebin.com/az97bZAY
One of my HTML templates: http:pastebin.com/6KALf0Bw
Create a test.html file and place it at /Blog/WebContent/test.html in your Eclipse project.
<html>
<head>
<title>Test WebContent</title>
</head>
<body>
<img src="images/test.png" />
</body>
</html>
Also place a test.png image file inside the /Blog/WebContent/images folder.
Now, point your browser to http://localhost:8080/<your-web-app-name>/test.html and check if test.png gets rendered or not. If yes, then the problem lies in the way you're writing HTML output from your servlet.
For a sample ImgServlet configured as
<servlet>
<servlet-name>ImgServlet</servlet-name>
<servlet-class>pkg.path.to.ImgServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImgServlet</servlet-name>
<url-pattern>/ImgServlet</url-pattern>
</servlet-mapping>
your doGet() method should ouput HTML as
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Test WebContent</title></head>" +
"<body><img src=\"images/test.png\" /></body></html>");
EDIT: To print all the request parameters your servlet is receiving add the following just before your handleRequest() method call (which you can comment out also for testing)
PrintWriter out = response.getWriter();
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String param = (String) parameterNames.nextElement();
out.println(param + " = [" + request.getParameter(param) + "]");
}
Try
<img src="/context/image.png">
But it does depend on how you deploy your application. Anyways, files like images must be inside WebContent folder.
First of all, dont hard code your context in your link, it will make you hard to change the link later if your context path is changed. Instead, use EL to make the relative path:
<img src="${pageContext.request.contextPath}/img/abc.png" />
Secondly, I dont see any image in your WebContent, if you put the image manually into the window folder, you need to refresh eclipse project in order to let eclipse detects all the added files. Right click on your project in the Project Explorer and select Refresh

Assigning url to an ajax (js) function into Java EE project

I'm experimenting with my first project in Ajax and I'm having a problem with assigning an absolute URL that points to the file to fetch from the server.
This is my function:
<script type="text/javascript">
function fetchData(url, objectID){
var pageRequest=null;
if(window.XMLHttpRequest)pageRequest=new XMLHttpRequest();
else if(window.ActiveXObject)pageRequest=new ActiveXObject("Microsoft.XMLHTTP");
else return false;
pageRequest.onreadystatechange= function(){
var object=document.getElementById(objectID);
object.innerHTML = pageRequest.responseText;
}
pageRequest.open("GET",url,true);
pageRequest.send(null);
}
</script>
and it's called like this:
<div id="control" onclick="fetchData('/WEB-INF/views/data.jsp','message');">Click here for Ajax!</div>
Tomcat returns a 404 no file source found error.
The file to fetch is at the same level as the other JSP files, this is the structure in Eclipse:
Project>
WebContent>
WEB-INF>
home.jsp
index.jsp
**data.jsp**
otherjsp
Shall I put that file somewhere else?
I have been trying to change the URL, but nothing.
The rest of the application works fine, so the requests are flowing properly.
You have a problem with your project layout, Ajax or any HTTP Call will not find the path
/WEB-INF/views/data.jsp
Because WEB-INF is protected from your JSP Container, try to put your JSP Files outside the WEB-INF directory.
http://tutorials.jenkov.com/java-web-apps/web-app-directory-layout.html
i hope the issue is with the url , can u give the absolute path instead of '/WEB-INF/views/data.jsp' and try again
change the url as like views/data.jsp
otherwise try below
keep all the jsp files inside webcontent and use this url views/data.jsp

Categories

Resources