YoungKimchi
YoungKimchi

Reputation: 37

How can I use jsp variables in another jsp file?

I have two jsp file, one is NewFile.jsp and another is index.jsp

I want to use variables(defined in index.jsp) in NewFile.jsp.

So I put this line in "NewFile.jsp":

<%@ include file = "index.jsp" %>

But page loaded HTTP Status 500 Internal Server Error and it said, :

org.apache.jasper.JasperException: 행 [13]에서 [/index.jsp]을(를) 처리하는 중 예외 발생

10:         out.println("can't access");
11:     }
12:     else {
13:         int age = Integer.parseInt(request.getParameter("age"));
14:         double height = Double.parseDouble(request.getParameter("height"));
15:         boolean sex = Boolean.parseBoolean(request.getParameter("female"));
16:         

It said : row [13] is wrong.(It is wrote in Korean but I think you can understand.)

and I have these lines in NewFile.jsp :

 function doAction(){
                    var req = createRequest();
                    if (req == null){
                        alert("실행이 되지 않는다!");
                        return ;
                    }
                    var hei = document.getElementById("height").value;
                    var ag = document.getElementById("age").value;
                    var fem = document.getElementById("female").checked;
                    req.open("GET", "index.jsp?female=" + encodeURI(fem) + "&age=" + encodeURI(ag) + "&height=" + encodeURI(hei));
                    req.setRequestHeader("User-Agent", "XMLHttpRequest");
                    req.onreadystatechange = function() {
                        if (this.readyState == 4 && this.status == 200){
                            var msg = document.getElementById('msg');
                            msg.innerHTML = this.responseText;
                        }
                    }
                    req.send();
                  }

    

I think it has an error while files interact in request.

And when I erase <%@ include file = "index.jsp" %>, it worked well (but not use index.jsp variables in NewFile.jsp).

But I don't know how to modify it.

How can I do to use variables defined in index.jsp in NewFile.jsp?

Upvotes: 1

Views: 1014

Answers (1)

lainatnavi
lainatnavi

Reputation: 1613

It's not clear from the description what you are trying to do. It seems that you got a null reference at line 13. If you pass the age as a request parameter than it does not make sense at all "sharing the variables".
Here's a working example which demonstrates how to share variables:

<!-- hello.jsp -->
<%
    String hi = "Hello from hello.jsp";
    request.setAttribute("hi", hi);
%>

<!-- index.jsp -->
<jsp:include page="hello.jsp"/>
<%=request.getAttribute("hi") %>

Keep in mind that the usage of JSP scriptlets is highly discoureged. Check this post for more in-depth details.

Upvotes: 1

Related Questions