Re-direct if validation fails in JSP
I am grabbing some data from a page using the code below:
int clientId = Integer.parseInt(request.getParameter("clientId"));
I have tried surrounding it with try/catch and then redirecting in the catch block using response.sendRedirect("page.jsp");
but the page does not re-direct, it seems to want to finish the whole script (which in turn throws more errors because the initial variables aren't valid!). Am I missin开发者_JAVA百科g something basic here?
Read your server logs. My cents on that it's cluttered with IllegalStateException
s. See also this answer for more detail.
Don't abuse the JSP as a page controller. Since JSP is by itself part of the response, you cannot change it from inside the JSP anymore (OK, there are hacks/workarounds, but you don't want to use hacks/workarounds). To control the request/response, you should be using a servlet. Create a servlet, let it listen on a certain URL, let the form submit to that URL, let the servlet execute all the Java code which you have had in the JSP and finally control the response destination.
You can find a Hello World example in our Servlets wiki page. It also covers basic validation.
You are perhaps missing a return
statement (although I don't see your code):
response.sendRedirect(..);
return;
If you simply call sendRedirect(..)
this will set the Location
http header, and an http status, but will not affect the flow of the current method, and it will continue.
You need to make sure all of your scriptlet logic on the JSP page is conditional depending on the existence of "clientId", so your catch block will probably need to go down to the bottom of the JSP page. Keep in mind that the JSP page is compiled into a servlet, so you still need to make sure the code can compile. In general, I would strongly recommend you put this logic inside a separate class (e.g., a controller kind of class) and minimize the amount of scriptlet code on your JSP page. Just hard to maintain otherwise.
If this doesn't clear things up for you, pls post your entire JSP code so that we can pinpoint where to advise.
精彩评论