开发者

how to use "request" object within a function in 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_js开发者_JAVA百科p.java:12: cannot find symbol
symbol  : variable request
location: class org.apache.jsp.register_jsp
/*


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".


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜