Wrong URL after clicking submit on JSP from - java

I am new to JSP and I am dealing with a confusing issue. I have a JSP form located in a sub folder called "admin" in my web-app (named "CMS").
CMS/admin/display_content.jsp
My form has the following values for action and method attribute
<form action="/deleteContent" method="POST">
/deleteContent is the URL pattern for a servlet named DeleteContentServlet. It simply deletes from the DB the user selections. Anyway, my problem is once I click on submit I notice that I get the incorrect URL in my address bar. Instead of getting
http://localhost:8080/CMS/deleteContent
I get
http://localhost:8080/deleteContent
How can I fix this ? When I have sub folders, are the files only used for imports maybe ?
Thank you.

Use the JSTL <c:url> tag for all your URLs:
it prepends the context path (whatever it is) to absolute URLs
it writes the session ID in the URL in case the browser doesn't accept cookies:
<form action="<c:url value='/deleteContent'/>" method="POST">
For links, it also allows passing parameters to the URL, and encodes them properly (via the <c:param> inner tag).

According to this, you can use request.getContextPath() in your servlet to get the context path. And you need not specify the hostname for the action unless it is different than yours:
<form action="<%= request.getContextPath() %>/deleteContent" method="POST">
Hope that helps...

Related

What is the difference between ${pageContext.request.contextPath} and request.getContextPath()

So I have a .jsp that displays the header part of my web application. This is a very standard looking page. I have a bar at the top with things like Login, Register, Contact Us, etc... And below that we have a horizontal navigation bar.
This is a standard Spring web application with a maven build. It produces a file, web.war, that we deploy to tomcat. on dev, this works fine.
We are testing production, and want this war to be the root, so we rename the war to ROOT.war and restart. everything fine.
Now sometimes, we get the navigation section from a Content Management System. We set the text as a variable and display that. No obviously we can't use ${pageContext.request.contextPath} as that wont get parsed this way, so before we display the text we do this in the jsp
<% navcopy = navcopy.replace("${pageContext.request.contextPath}", request.getContextPath()); %>
Now this is adding the /web to the URL. Now this is baffling to me as registration link in the jsp works:
<a id="home-left-menu-item" href="${pageContext.request.contextPath}/register.html">Register Now!</a>
So hoe does ${pageContext.request.contextPath} parsed in the jsp return the correct root but the call request.getContextPath() returns "/web"
Aren't they essentially the same call to the same object to the same method?
Any insight would be appreciated.
${pageContext.request.contextPath} : Returns the portion of the request URI that indicates the context of the request.
In fact, it is identical to request.getContextPath(), since ${pageContext.request} refers to the HttpServletRequest of the current request.
For example:
http://localhost:80/myProjectName/path/servlet
${pageContext.request.contextPath} returns /myProjectName
request.getServletPath() Returns the part of this request's URL that calls the servlet, e.g. /path/servlet
${pageContext.request.servletPath} returns /path/servlet
For this code try this:
<a id="home-left-menu-item" href="<%=request.getContextPath()%>/register.html">Register Now!</a>

hyperlink redirect to another JSP

I have a hyperlink for one of the column which looks like this.
<td align="ct"><a href="<%=getContext()%>/otp/taxView.do?call=first&taxId=<bean:write name="otping" property="taxNumber" />"><bean:write name="otping"
property="taxNumber" /></a>
</td>
Can I use the same to redirect to a different uri? When I google for redirect there are options to move action to controller and use sendRedirect and meta-refresh. Will the above work? or should I use a different method?
$(document).ready(function(){
$("a").click(function(e){
e.preventDefault();
window.location.href = 'Different uri'
});
});
Hope it helps.
This is referred as post-redirect-get pattern. You send POST to one uri, it performs action and then returns 'redirect' to the browser, which presents result page. This prevents re-posting when user is going through back/forward in history. This requires using respnse.sendRedirect(), as it looks like using Struts it can be defined via configuration.
Check here for more details:
post-redirect-get-prg-pattern-in-servlet-jsp
post-redirect-get-when-passing-data-to-the-form
Implement-Post-Redirect-Struts

JSP onload call servlet without scriptlets

I want that when my JSP is loaded to call a servlet. I have this link:
Homepage
But this way I have to click the link, I want to perform the calling automatically when the jsp is loaded.
On the other side I need to use no scriptlets. Does anyone have any idea how to do this?
Although its marked as resolved but I am editing my answer for future reference:
Apart from the javascript solution you can accomplish this with 2 more options using jsp tags:
Option1:
You can forward the request to the corresponding servlet.
Use jsp standard action jsp:forward, e.g.:
<jsp:forward page="ContentServlet?action=userContents" >
</jsp:forward>
You can replace your link with the above tag and the servlet will be called.
Option2:
you can redirect the request to your servlet using JSTL tags:
<c:redirect url="ContentServlet?action=userContents" />
Again you can replace your link with the above tag.
In Option1 browser's url will not change.
In Option 2 browser's url will change to "ContentServlet?action=userContents"
Hope it solves your problem.
Why don't you use JavaScript?
<script type="text/javascript">
function redirect(){
window.location = "/ContentServlet?action=userContents"
}
</script>
...
<body onLoad="redirect()">

How to get url path from jsp in Spring MVC framework

To remove the language toggle from the page view(Comfirmation Page)
I found this code but it doesn't work in Spring MVC
<c:if test="${!fn:contains(pageContext.request.servletPath,'/comfirmation')}">
//Other Code
</c:if>
My actual url is (ShoppingCart.jsp).
It is used when /viewCart.htm,/updateCart.htm,/Confirmation.htm,etc.
So, the user go to the /Confirmation.htm, it also redirect to the ShoppingCart.jsp but the url path in the browser is /Confirmation.htm.
I want to remove the language toggle when call the /Confirmation.htm in the above mention.
Finally, I got it. Here we go
<%
String url=request.getAttribute("javax.servlet.forward.servlet_path").toString();
if(url.equals("/Confirmation.htm")){
%>
//Language Toggle code
<% } %>
I decided to use this. Another way is that storing url path in session since front controller.
the pageContext.request.servletPath will give you the path of the jsp (and not the url your browser shows).
The request is forwarded to a controller, which returns a path to a view. The view ist called using a second internal request

Sending multiple parameters to servlets from either JSP or HTML

I need to send a particular parameters to Servlet from JSP page. E.g: if I click on the Facebook icon on the web page, then I should send "facebook" as parameter to my Servlet and my Servlet will respond according to the parameter received from JSP file or HTML file.
This is a very open ended question, but the easiest way is to specify parameters in a query string.
If you have the following servlet:
/mysite/messageServlet
Then you can send it parameters using the query string like so:
/mysite/messageServlet?param1=value1&param2=value2
Within the servlet, you could check your request for parameters using getParameter(name) if you know the name(s), or getParameterNames(). It's a little more involved, specifically with consideration to URL Encoding and statically placing these links, but this will get you started.
String message = request.getParameter("message");
if ("facebook".equals(message))
{
// do something
}
Storing links with multiple parameters in the querystring requires you to encode the URL for HTML because "&" is a reserved HTML entity.
Send Messages
Note that the & is &.
Just wrap the icon in a link with a query string like so
<img src="facebook.png" />
In the doGet() method of the servlet just get and handle it as follows
String name = request.getParameter("name");
if ("facebook".equals(name)) {
// Do your specific thing here.
}
See also:
Servlets info page
One way is to have hidden form variables in your jsp page that get populated on click.
<form action="post" ....>
<input type="hidden" id="hiddenVar" value="">
<a hfref="#" onclick="doSomething();">Facebook</a>
</form>
<script>
function doSomething() {
var hiddenVar= document.getElementById('hiddenVar');
hiddenVar.value = "facebook";
form.submit();
}
</script>
This gives you flexibility to control what gets passed to your servlet dynamically without having to embed urls in your href

Categories