I am new to jsp, java servlets etc. I am stuck upon a problem where in I have a jsp page and it contains a try-catch block in the scriptlet. I have defined a few variables inside that try-catch block which i need to access in the HTML. Since it's inside the try-catch block the html page can't access those variables and their member variables.
<%
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>
Now variables u, rectype_str and rectype if declared outside try can be accessed by the html page but i want to access them after including them in try due to some other validations which are confidential for public forum.
Since if the exception is caught then the error page is returned and the html content doesn't need to load, I want a solution to load this html content only when try block was successfully executed without any exceptions.
If I have understood your requirement, you can do it as follows:
<%
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;
}
%>