catch块中声明的变量?

brgchamk  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(399)

我对jsp、javaservlets等不太熟悉。我遇到了一个问题,在这个问题中,我有一个jsp页面,它在scriptlet中包含一个try-catch块。我在try-catch块中定义了一些变量,我需要在html中访问这些变量。由于它位于try-catch块中,html页面无法访问这些变量及其成员变量。

<%
    Logger logger = Logger.getLogger("abcd.jsp");
    try{
        UserProfile u = su.getUserProfile(session,request);
        String rec_typestr = request.getParameter("rectype");;
        int rectype = Integer.parseInt(rec_typestr);
        ....
        ....
        //some more code
    }
    catch(NumberFormatException e) {
        logger.error("Error in the request: " + e.getMessage());
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid rectype passed in request");
        return;
    }
%>

<div id="testDiv1">
    <div class="testClass1">
        Private Views for <%=u.getFirstName() + " "%> <%=u.getLastName()%>
    </div>
    <div class="testClass2">
        <input type="button" value="Create" class="genericButton" onclick="displayLink('openSomePage.jsp?rectype=<%=rectype%>')" /> 
        <input type="button" value="Refresh" class="genericButton" onclick="perform1stTask()" /> 
            <input type="button" value="Print" class="genericButton" onclick="perform2ndTask()" /> 
            <input type="button" value="Export to Excel" class="genericButton" onclick="perform3rdTask(<%=u.getId()%>,'<%=someTestVariable%>', '<%=rec_typestr%>')" />
    </div>
</div>

现在变量u,rectypestr和rectypeif在try之外声明可以被html页面访问,但是我想在try中包含它们之后访问它们,因为其他一些验证对公共论坛是保密的。
因为如果捕获到异常,则返回错误页,并且不需要加载html内容,所以我需要一个解决方案,仅当try块在没有任何异常的情况下成功执行时才加载此html内容。

svmlkihl

svmlkihl1#

如果我了解您的要求,您可以按以下步骤操作:

<%
    Logger logger = Logger.getLogger("abcd.jsp");
    try{
        UserProfile u = su.getUserProfile(session,request);
        String rec_typestr = request.getParameter("rectype");;
        int rectype = Integer.parseInt(rec_typestr);
        ....
        ....
        //some more code
%>
        <div id="testDiv1">
            <div class="testClass1">
                Private Views for <%=u.getFirstName() + " "%> <%=u.getLastName()%>
            </div>
            <div class="testClass2">
                <input type="button" value="Create" class="genericButton" onclick="displayLink('openSomePage.jsp?rectype=<%=rectype%>')" /> 
                <input type="button" value="Refresh" class="genericButton" onclick="perform1stTask()" /> 
                    <input type="button" value="Print" class="genericButton" onclick="perform2ndTask()" /> 
                    <input type="button" value="Export to Excel" class="genericButton" onclick="perform3rdTask(<%=u.getId()%>,'<%=someTestVariable%>', '<%=rec_typestr%>')" />
            </div>
        </div>

<%        
    }
    catch(NumberFormatException e) {
        logger.error("Error in the request: " + e.getMessage());
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid rectype passed in request");
        return;
    }
%>

相关问题