how to pass javascript value to same jsp page

2.3k views Asked by At

I want to get page url from java script and check that url value to blow the script(inside same jsp page).

<script>
var currentUrl=window.location.href;
</script>

<c:when test="${fn:containsIgnoreCase(currentUrl, 'homepage') or fn:containsIgnoreCase(currentUrl, 'accountpage')}">

// need to do some operation for this purticular page only.
</c:when>

Please give me suggestion. Thanks in Advance, Muthu

3

There are 3 answers

1
Ritesh  Karwa On

try this:

<html>
    <script language="javascript" type="text/javascript">
    function call(){
    var name = "xyz";
    window.location.replace("a.jsp?name="+name);
    window.onload = function() {
       call();
    }
    </script>
    <%
    String name=request.getParameter("name");
    if(name!=null){
    out.println(name);
    }
    %>
 </html>
0
radimpe On

Why would you want to access the url from JavaScript if you have access to it via the request? Using the OriginatingRequest bean you can do the following:

<dsp:getvalueof bean="/OriginatingRequest.requestUri" var="requestUri" />

This will then allow you to do your check as follow:

<c:when test="${fn:containsIgnoreCase(requestUri, 'homepage') or fn:containsIgnoreCase(requestUri, 'accountpage')}">
    // need to do some operation for this particular page only.
</c:when>

This is the simplest way to satisfy your particular use-case above.

0
Vihung On

There are a number of problems with what you are trying to achieve.

The JavaScript code (inside the <script/> tag) is executed client-side, while the JSP EL code (in the <c:when/> tag and fn:containsIgnoreCase() function) is executed server side.

The two bits of code do not run in the same system. They do not have visibility of one another

The two bits of code are not run at the same time. The server-side code will be executed as the HTTP response is being generated by the server and the resultant HTML will be sent back to the browser. The browser will then execute the client-side code. So although your javascript code occurs before your JSP EL code in the JSP file, they will be executed at different times - the JSP EL code will be executed first (by the server), and then the JavaScript will be executed (by the browser)

Lastly and leastly, the languages are not the same. Even if the two bits of code were to be executed in the same system, EL is not JavaScript and JavaScript is not EL. A variable declared in one language in one block will not be visible in another language in another block.

You could write all the logic you need in one language (EL), and have it executed in the sequence you want all in the same system using the pageContext.request.requestURL or pageContext.request.requestURI object properties