[java] How do I pass JavaScript values to Scriptlet in JSP?

Can anyone tell me how to pass JavaScript values to Scriptlet in JSP?

This question is related to java javascript jsp scriptlet

The answer is


You cannot do that but you can do the opposite:

In your jsp you can:

String name = "John Allepe";    
request.setAttribute("CustomerName", name);

Access the variable in the js:

var name = "<%= request.getAttribute("CustomerName") %>";
alert(name);

If you are saying you wanna pass javascript value from one jsp to another in javascript then use URLRewriting technique to pass javascript variable to next jsp file and access that in next jsp in request object.

Other wise you can't do it.


I can provide two ways,

a.jsp,

<html>
    <script language="javascript" type="text/javascript">
        function call(){
            var name = "xyz";
            window.location.replace("a.jsp?name="+name);
        }
    </script>
    <input type="button" value="Get" onclick='call()'>
    <%
        String name=request.getParameter("name");
        if(name!=null){
            out.println(name);
        }
    %>
</html>

b.jsp,

<script>
    var v="xyz";
</script>
<% 
    String st="<script>document.writeln(v)</script>";
    out.println("value="+st); 
%>

This is for other people landing here. First of all you need a servlet. I used a @POST request. Now in your jsp file you have two ways to do this:

  1. The complicated way with AJAX, in case you are new to jsp: You need to do a post with the javascript var that you want to use in you java class and use JSP to call your java function from inside your request:

    $(document).ready(function() {
        var sendVar = "hello";
        $('#domId').click(function (e)
        {                               
            $.ajax({
                type: "post",
                url: "/", //or whatever your url is
                data: "var=" + sendVar ,
                success: function(){      
                        console.log("success: " + sendVar );                            
                      <% 
                          String received= request.getParameter("var");
    
                          if(received == null || received.isEmpty()){
                              received = "some default value";
                          }
                          MyJavaClass.processJSvar(received); 
                      %>;                            
    
                }
            });
        });
    
    });
    
  2. The easy way just with JSP:

    <form id="myform" method="post" action="http://localhost:port/index.jsp">
         <input type="hidden" name="inputName" value=""/>
                   <% 
                          String pg = request.getParameter("inputName");
    
                          if(pg == null || pg.isEmpty()){
                              pg = "some default value";
                          }
                          DatasyncMain.changeToPage(pg); 
                      %>;     
    </form>
    

Of course in this case you still have to load the input value from JS (so far I haven't figured out another way to load it).


I've interpreted this question as:

"Can anyone tell me how to pass values for JavaScript for use in a JSP?"

If that's the case, this HTML file would pass a server-calculated variable to a JavaScript in a JSP.

<html>
    <body>
        <script type="text/javascript">
            var serverInfo = "<%=getServletContext().getServerInfo()%>";
            alert("Server information " + serverInfo);
        </script>
    </body>
</html>

Its not possible as you are expecting. But you can do something like this. Pass the your java script value to the servlet/controller, do your processing and then pass this value to the jsp page by putting it into some object's as your requirement. Then you can use this value as you want.


simple, you can't!

JSP is server side, javascript is client side meaning at the time the javascript is evaluated there is no more 'jsp code'.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jsp

Difference between request.getSession() and request.getSession(true) A child container failed during start java.util.concurrent.ExecutionException The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path Using if-else in JSP Passing parameters from jsp to Spring Controller method how to fix Cannot call sendRedirect() after the response has been committed? How to include js and CSS in JSP with spring MVC How to create an alert message in jsp page after submit process is complete getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever? How to pass the values from one jsp page to another jsp without submit button?

Examples related to scriptlet

Using if-else in JSP How do I pass JavaScript values to Scriptlet in JSP? I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error How can I avoid Java code in JSP files, using JSP 2?