how to set base context url for different request url - java

i have been trying to fix for days, but no fix yet, i want to have fix base url with root context , rest of the url string will change, but my base url should be fixed for each request.
here is scenario,
in a home page, when user clicks "Login" it will call menu controller and the request url will be as below
http://localhost:8080/myApp/menu/login.jsp
once my login page loads, when i do "Sing in", the url should be as below
http://localhost:8080/myApp/user/singIn.jsp
but above was not working and my url request is some thing like
http://localhost:8080/myApp/menu/user/singIn.jsp
so it was taking relative path instead of absolute, i have code below code added to my layout jsp to fix this problem to have base url fixed, but it is not working.
<base href="${pageContext.servletContext.contextPath}">
above code i have added to layout.jsp which contains header, body and footer, and my request presents in body jsp.
Edit :- the request are jquery ajax request

use <base href="${pageContext.contextPath}">
instead of
<base href="${pageContext.servletContext.contextPath}">

`<%String path = request.getContextPath();
String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
`
<base href="<%=basePath%>">

Related

Several JSP pages and requestURI

I use Apache Tiles to unite multiple jsp pages.What I want is to get the URI of the request that came from web client (from browser). However, when in my jsp page I use
${pageContext.request.requestURI}
I get not web client uri but the local path of the jsp file. For example when web user enters http://company.com/something/ (I want to get /something/) I get /jsp/articles/index.jsp.
I tried requestScope.request.requestURI but it returns empty string. How can I get web client request URI
As per your question,you said when you enter "http://company.com/something/" in the browser,you get /jsp/articles/index.jsp in JSP,it seems your original request has been forwarded to new one. You can try below to get the orginal URI in JSP page.
<% String originalUri = (String) request.getAttribute("javax.servlet.forward.request_uri"); %>

How to set an attribute in a jsp page with hyperlink (request scope)

I think the title above is a bit confusing.
What I'm trying to achieve:
I have a jps page(located in WEB-INF) with a hyperlink in it that will call another jsp (in WEB-INF) via servlet.
I understand that this can be achieved using the following:
Go to this page
But because there will be lots of hyperlinks, my idea was to have a general servlet(OpenPagesServlet) to handle all those pages.
Something like this:
JSP page:
<% request.setAttribute("page", "page1.jsp");%>
Page 1
OpenPagesServlet in doGet method:
String page = (String) request.getAttribute("page");
request.getRequestDispatcher("/WEB-INF/" + page).forward(request, response);
I tried the code above and I get:
HTTP Status 404 - Not Found
type Status report
messageNot Found
descriptionThe requested resource is not available.
But if I try with session.setAttribute / sesion.getAttribute the code works fine, but I don't want to have sessions on each time I click on hyperlinks.
The other approach I found was to use:
Page 1
and inside the servlet:
String page = (String)request.getParameter("value");
request.getRequestDispatcher("/WEB-INF/" + page).forward(request, response);
It worked, but this approach is not good because the page can then be accessed directly using the url:
http://localhost:8080/WebApp/OpenPagesServlet?value=page1
So...my question is why request.setAttribute/request.getAttribute is returning 404?
Is there a different approach to achieve what I'm trying to do?
An HttpServletRequest and its attributes only live for the duration of one HTTP request/response cycle. After yo've set the attribute in the JSP, the JSP is rendered and sent as part of the HTTP response body. The Servlet container considers the request handled and clears its attributes. The attribute is now gone.
It is therefore no longer available in the next request that arrives after the user clicks the link.
The session attribute or request parameter is fine. Consider looking into the Front Controller pattern.
Also, consider using the core tag library (in particular the url tag) instead of scriptlets for constructing your links.

RequestDispatcher.include(...) appends servlet's package name

I have an index.jsp page which uploads an image. On submit it goes to a servlet Upload.java. In the servlet I am checking if the extension in of image("jpg","png",etc) and forwards to new jsp page else it shows an error message and includes the same index.jsp page.
My servlet is a package named "servlets".
If I select an image then it is working properly. But if I select any file other than image then it shows the error with the index.jsp page as intended. Till now it works fine but if I upload any file even image from here, the server complains.
Here is how I am including the index.jsp page in UploadServlet.java servlet.
out.println("This type of file is not allowed. Please select an image.");
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
dispatcher.include(request, response);
Here is the error from the server when I try to upload the image second time.
HTTP Status 404 - /UploadImage/servlets/servlets/UploadServlet
type Status report
message /UploadImage/servlets/servlets/UploadServlet
description The requested resource (/CropImage/servlets/servlets/UploadServlet) is not available.
Apache Tomcat/6.0.13
It is appending the servlet's package name to the url.
How to solve this problem?
Apparently you're using a relative action URL in your <form>.
<form action="servlets/UploadServlet" ...>
When you open index.jsp, the request URL is
http://localhost:8080/UploadImage/index.jsp
When you submit the form, the action URL is relative to the current folder, so request URL will be
http://localhost:8080/UploadImage/servlets/UploadServlet
When you submit the form once again, the will be still relative to current folder, so you end up in
http://localhost:8080/UploadImage/servlets/servlets/UploadServlet
You need to fix it to be a domain-relative URL, starting with a leading slash.
<form action="/UploadImage/servlets/UploadServlet" ...>
This way the URL will be resolved relative to the domain root. You can also resolve the context path dynamically by ${pageContext.request.contextPath}:
<form action="${pageContext.request.contextPath}/servlets/UploadServlet" ...>
Your url is wrong. You can open the web.xml and find the "servlet-mapping" element there you can find the mapping url.
I guess your url may be "/CropImage/servlets/UploadServlet" .you can try to delete one "servlets" in the url.

Java servlet sendRequest - getParameter encoding Problem

I'm building a web app for my lesson using java servlets. At some point i want to redirect to a jsp page, sending also some info that want to use there (using the GET method).
In my servlet i have the following code:
String link = new String("index.jsp?name="+metadata.getName()+"&title="+metadata.getTitle());
response.sendRedirect(response.encodeRedirectURL(link));
In the jsp, I get these parameters using
<%
request.getParameter("name");
request.getParameter("title");
%>
Everything works fine, except when the parameters do not contain only latin characters (in my case they can contain greek characters).
For example if name=ΕΡΕΥΝΑΣ i get name=¡¥.
How can i fix this encoding problem (setting it to UTF-8)?
Isn't encodeRedirectURL() doing this job? Should I also use encodeURL() at some point? I tried the last one but problem still existed.
Thanks in advance :)
The HttpServletResponse#encodeRedirectURL() does not URL-encode the URL. It only appends the jsessionid attribute to the URL whenever there's a session and the client has cookies disabled. Admittedly, it's a confusing method name.
You need to encode the request parameters with help of URLEncoder#encode() yourself during composing the URL.
String charset = "UTF-8";
String link = String.format("index.jsp?name=%s&title=%s",
URLEncoder.encode(metadata.getName(), charset),
URLEncoder.encode(metadata.getTitle(), charset));
response.sendRedirect(response.encodeRedirectURL(link));
And create a filter which is mapped on /* and does basically the following in doFilter() method:
request.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
And add the following to top of your JSP:
<%# page pageEncoding="UTF-8" %>
Finally you'll be able to display them as follows:
<p>Name: ${param.name}</p>
<p>Title: ${param.title}</p>
See also:
Unicode - How to get characters right?
Use the java.net.URLEncoder to encode each parameter before adding them to the url. Think about it this way: if your name contained a "&", how would you know that this was not a parameter delimiter?
You should encode every request parameter with URLEncoder.encode() before putting it into the query string .
The encodeRedirectURL method is only used to include the session ID into the URL if necessary (URL rewriting if no cookie support by the browser)
How about the following instead?
Set the name and title as attributes on the request object;
Get a request dispatcher for the JSP from the request object or via the servlet context;
Use the request dispatcher to forward the request to the JSP;
Access these attributes in the request from the JSP.
This saves redirecting the browser from the first servlet to the JSP derived servlet and avoids the whole parameter encoding issue entirely.
Also ensure the JSP page directive sets the content encoding to UTF-8.

JSP not detecting the javascript file

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.

Categories

Resources