Composing URL in JSP - java

Lets say my current URL is:
/app.jsp?filter=10&sort=name.
I have a pagination component in JSP which should contain links like:
/app.jsp?filter=10&sort=name&page=xxx.
How do I create valid URLs in JSP by adding new parameters to current URL? I dont want use Java code in JSP, nor end up with URLs like:
/app.jsp?filter=10&sort=name&?&page=xxx, or /app.jsp?&page=xxx, etc.

Ok, I found answer. First problem is that I have to preserve all current parameters in URL and change only page parameter. To do this I have to iterate over all current parameters and add those I don't want to change to URL. Then I added parameters I want to either change or add. So I ended up with solution like this:
<c:url var="nextUrl" value="">
<c:forEach items="${param}" var="entry">
<c:if test="${entry.key != 'page'}">
<c:param name="${entry.key}" value="${entry.value}" />
</c:if>
</c:forEach>
<c:param name="page" value="${some calculation}" />
</c:url>
This will create nice and clean URL independent of page parameter in request. Bonus to this approach is that URL can be just anything.

<c:url var="myURL" value="/app.jsp">
<c:param name="filter" value="10"/>
<c:param name="sort" value="name"/>
</c:url>
To show the url you can do something like this
Your URL Text

To construct a new URL based on the current URL, you first need to get the current URL from the request object. To access the request object in a JSP use pageContext implicit object defined by the JSP expression language:
${pageContext.request.requestURL}
Here is the simple example of constructing URL in a JSP page:
test.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Testing URL construction</h1>
<c:choose>
<c:when test="${pageContext.request.queryString != null}">
Go to page xxx
</c:when>
<c:otherwise>
Go to page xxx
</c:otherwise>
</c:choose>
</body>
</html>
This solution allows you to construct URLs depending on whether the current URL already contains some query string or not. So you respectively append either
?${pageContext.request.queryString}&page=xxx
or just
?page=xxx
to the current URL.
JSTL and the Expression Language were used to implement checking for a query string. And we used getRequestURL() method to obtain the current URL.

Related

how to output what i type in a textbox using jsp

<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<form:form
action="/hospital/login.html"
method="post">
User name: <form:input name="un" path="username"/> <br/>
password: <form:password path="password"/><br/>
<c:out value="${ un }" />
</form:form>
i dont want to use any scriplets since i am programming a servlet using spring mvc, but i want to display simultaneously what i type inside the textbox.
If you want to take some action simultaneously, without posting the form, then you will be needing client side scripting with Javascript.
A very simple and pure Javascript way to achieve what you want is as below.
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<form:form
action="/hospital/login.html"
method="post">
User name: <form:input name="un" path="username" onkeyUp="javascript:sync()" /> <br/>
password: <form:password path="password"/><br/>
<span id='outLabel'></span>
</form:form>
<script type="text/javascript">
function sync()
{
var textbox = document.getElementsByName('un')[0];
var label = document.getElementById('outLabel');
label.textContent = textBox.value;
}
</script>
You can play with JSFiddle example of client side part here.
You can improve this in multiple ways: using id for form:input, using jquery to selecting dom elements more easily, including javascript part from a js file are all things you should consider for a better design.

Cannot get the parameters in the server

I got a problem when I try to get parameters from the request, I got nothing but NULL.
The JSP file is like this:
<%# page contentType="text/html; charset=UTF-8" %>
<%# taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%# taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%# taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html:html locale="true">
<head>
<META HTTP-EQUIV="pragma" CONTENT="no-cache">
<META HTTP-EQUIV="cache-control" CONTENT="no-cache">
<META HTTP-EQUIV="expires" CONTENT="0">
<META HTTP-EQUIV="Content-Type" content="text/html; charset=UTF-8">
<META HTTP-EQUIV="Content-Script-Type" content="text/javascript">
<META HTTP-EQUIV="Content-Style-Type" content="text/css">
<link rel="stylesheet" type="text/css" href="css/base.css">
<title>Menu</title>
<SCRIPT language="JavaScript">
<!--
function nextPage(url) {
location.replace(url);
}
function setUrl(url) {
document.forms[0].url.value = url;
}
//-->
</SCRIPT>
</head>
<body tabindex="-1">
<%-- ページ・ボディ --%>
<html:form action="/select.do?apl500_p=1" method="post" target="_self" >
<html:hidden property="url" value ="" />
<table style="width:100%;" border="0">
<tr>
<td style="width:100%;text-align:center">
<font size="5" color="#000000">
<B>Menu</B></font>
</td>
<td style="text-align:right">
<html:submit property="submit_logout" value="Logout" tabindex="-1"/>
</td>
</tr>
</table>
<hr><br>
<div align="center" style="width:90%;height:482px;overflow:auto;margin-left:40px;">
<table border="0">
<tr>
<td style="width:100%;text-align:center">
<html:submit property="btn1" value="アプリケーション1" onclick="setUrl('/aplXXX')" style="width:400px;height=150px;font-size:14pt;"/>
</td>
</tr>
<tr>
<td style="width:100%;text-align:center">
<html:submit property="btn2" value="新共通認証システム(ローカル環境用)テスト" onclick="setUrl('/authTest')" style="width:400px;height=150px;font-size:14pt;"/>
</td>
</tr>
</table>
</div>
<%-- ページ・フッダー --%>
<%# include file="/WEB-INF/jsp/footer.inc" %>
</html:form>
</body>
</html:html>
<% out.flush(); %>
When I used "request.getParameterNames()", I can only get the "apl500_p" parameter, I cannot get the "url" parameter. I used the tomcat7.0.41, but if I use the tomcat5.5.36,it's Ok.
I don't know why. Is there something wrong with tomcat7.0.41?
I used Fiddler2 and I'm sure that the "url" parameter was sent to the server.
Based on the discussion that you had, I suspect that the parameter url is NULL because the character encoding used by the browser is different from the character encoding used by the server.
Before the browser sends a parameter to the server, it URL-encodes the parameter. This encoding method encodes certain characters (e.g, Japanese characters) using percent encoding. Percent encoding method works by first converting the character into bytes, based on the specified character set. After that, it encodes these bytes into a sequence of hexadecimal digits, prefixed by "%" character. This character set is what I mean by character encoding used by the browser.
The server then decodes the retrieved parameter back into its original form. It does this by first decoding the sequence of hexadecimal digits into a sequence bytes. After that, it convert each bytes into a character, based on the specified character set. The problem here is that the server needs to use the same character set as the one used by the browser. It is often that the request does not carry information about the character set used by the browser, causing the server to make a best effort guess. If the guess is incorrect, the decoding process fails silently, and NULL is returned, which is what happened in your case.
Different web servers have different ways to make the guess. Web server may look at the Content-Type header, Content-Language header, Accept header, Accept Language header, configuration file, and so on.
As I am not familiar with both Tomcat versions, I am not able to pin point exactly how to fix the problem. But, you can start by studying how Tomcat figure out the character encoding. In WebSphere Application Server, there is a configuration file that can be modified to specify the default character encoding used by the server.
The parameter apl500_p is not NULL because the URL-encoded-form of 1 is also 1. The server does not have any problem decoding it back.
Try to remove the apl500_p=1 in the form action value
action="/select.do"
This way it will pass all your form elements to the servlet. Adding parameters to the form action prevents this. If you need your apl500_p value, I suggest you make another hidden field like:
<html:hidden property="apl500_p" value ="1" />

Can we redirect one jsp page to another jsp page

I want to open a jsp page without accessing my servlete code. i.e. I neither have to input my url in (action="url") my jsp code nor have to access my Servlete code.
<form id="main" method="post" name="main" action="dpRegPost" onsubmit="return validate();">
Can anyone help me in this?
You can add javascript to your jsp file
<script type="text/javascript">
window.location.href = "www.google.com";
</script>
or using jsp
<%
response.sendRedirect("www.google.com");
%>
You can also try this
<jsp:forward page = "abc.jsp" />
Use jstl taglibrary in your current jsp page.Make available the taglibrary using below code
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Use Following code in jsp to redirect
<c:redirect url="/xxx.jsp"/>
Try this:
<form id="main" method="post" name="main" action="" onsubmit="redirect(this);">
<input type="submit" name="submit"/>
</form>
function redirect(elem){
elem.setAttribute("action","somepage.jsp");
elem.submit();
}
You can also call page directly with:
<jsp:redirect page="xyz.jsp" />
use the following code to redirect on another page in js...
$('#abc_id').click(function() {
updateSubContent("abc.jsp");
});

get current url of context

I want to get the current URL of my website.
Not the context, not the ports, not the scheme or the protocol. Only the relative url.
For example:
https://www.myurl.com/context/relative/url/site.mvc
I want to have:
/relative/url/site.mvc
${pageContext.request.contextPath} gives me: /context/
${pageContext.request.requestURL} gives me https://www.myurl.com/context/WEB-INF/tiles/relative/url/site/center.jsp
Thats where the site is located in my directory.
But I want the relative path of the website... without Javascript!
So, you want the base URL? You can get it in a servlet as follows:
String url = request.getRequestURL().toString();
String baseURL = url.substring(0, url.length() - request.getRequestURI().length()) + request.getContextPath() + "/";
// ...
Or in a JSP, as , with little help of JSTL:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="url">${req.requestURL}</c:set>
<c:set var="uri" value="${req.requestURI}" />
...
<head>
<base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/" />
</head>
Note that this does not include the port number when it's already the default port number, such as 80. The java.net.URL doesn't take this into account.
See also:
Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP
jsp file:
request.getAttribute("javax.servlet.forward.request_uri")
Thank you #jmail.
Your statement brought me on the right track. But I did not want the base url, but the solution would be this:
<c:set var="currentUrl" value="${pageContext.request.request.getAttribute('javax.servlet.forward.request_uri')}"/>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<c:forEach items="${paramValues}" var="paramItem">
<c:set var="urlParams" value="${urlParams}&${paramItem.key}=${paramItem.value[0]}"/>
</c:forEach>
<c:set var="urlParams" value="${fn:substring(urlParams, 1, fn:length(urlParams))}" />
<c:set var="relativeUrl" value="${fn:substring(currentUrl, fn:length(contextPath), fn:length(currentUrl))}?${urlParams}" />
You forgot the parameters, and your version extracted the base, instead of the relative path!

Why my included JSP file won't get processed correctly?

I am trying (and learning) to build a java web framework, and in the process of developing its' code generator based on the content of the database. In the view making process, I stumble in a difficulty, which I don't know how to solve it.
Firstly, I want all the pages to be created using the following index.jsp :
<body>
<%# include file="header.jsp" %>
<hr/>
<%# include file="body.jsp" %>
<hr/>
<%# include file="footer.jsp" %>
</body>
And, in the body.jsp, I want it to be like this :
<jsp:include page="${application_modul}" %>
Where application_modul is an attribute defined in its' controller this way :
request.setAttribute("application_modul","user_account\\view_user_account.jsp");
It can find the file correctly, but the processed jsp is not what I expected. Here :
<c:forEach items="[application.models.UserAccountModel#18a49e0, application.models.UserAccountModel#1f82982]" var="item" varStatus="status" >
<tr>
....
You can see the items attribute of jstl forEach, got its variable name (toString())...
Any Idea what the problem is????
I hope I describe my problem correctly
Many thanks!
PS :
I already create a quick fix for this, but not what I want it though. In the generated view_user_account.jsp, I do it like this :
<body>
<%# include file="header.jsp" %>
<hr/>
<c:forEach items="${row}" var="item" varStatus="status" >
<tr>
....
<hr/>
<%# include file="footer.jsp" %>
</body>
You can see that I create the whole file here...
EDITED:
PS : ${row} is an ArrayList populated with data from certain table
So, to summarize your problem in a single sentence, JSTL tags are not been parsed and they end up plain in generated HTML output?
You need to declare JSTL taglib in top of the JSP page where you're using JSTL tags to get them to run. For the JSTL core taglib, that'll be
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
I am not sure but, Try this...
index.jsp
<jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />

Categories