Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use "request" object within a function in jsp

Tags:

jsp

    <%
    String fname=request.getParameter("fname");
    String username=getVal("lname");
%>
<%!
    private String getVal(String param){
        return request.getParameter("fname");

}
%>
/*

--err



org.apache.jasper.JasperException: PWC6033: Error in Javac compilation for JSP

PWC6197: An error occurred at line: 5 in the jsp file: /register.jsp
PWC6199: Generated servlet error:
string:///register_jsp.java:12: cannot find symbol
symbol  : variable request
location: class org.apache.jsp.register_jsp
/*
like image 903
Jabir Ahmed Avatar asked Aug 24 '11 06:08

Jabir Ahmed


2 Answers

JSP goes through a JSP compiler which will convert the JSP page into a servlet, autogenerating the java code.

The JSP directives instructs the JSP compiler where to put what. Everything that is inside <% %> (called JSP scriptlets) will be put inside the service() method of the generated servlet. Everything inside <%! %> (called JSP declarations) will become part of the actual class of the generated servlet, so your getVal() will become an instance method.

The standard request (and session and pageContext etc) object instances are defined inside the service() method so they are, in effect, ONLY available inside JSP scriptlet sections.

If you are running on Tomcat, for instance, you can look at the actual generated Java code for your JSP pages if you look inside the "work" directory in the Tomcat installation. Might be interesting, if not get a better picture about what is happening "under the hood".

like image 81
pap Avatar answered Nov 18 '22 12:11

pap


request is accessible inside the scriptlet expressions, because it's an argument of the method in which these expressions are evaluated (_jspService). But if you want it to be available in your own methods, you must declare it as an argument:

<%
    String fname = request.getParameter("fname");
    String username = getVal("lname", request);
%>
<%!
    private String getVal(String param, HttpServletRequest request) {
        return request.getParameter("fname");
    }
%>

Note that you shouldn't be using scriptlets and getting request parameters in JSPs in the first place. JSPs should be used to generate markup. Do your processing in a servlet/action, prepare the data to be displayed by the JSP by creating and populating beans in the request scope, and then dispatch to a JSP, which should use JSP EL, the JSTL and other custom tags exclusively.

like image 16
JB Nizet Avatar answered Nov 18 '22 11:11

JB Nizet