Jump in Servlet
When I wrote an announcement system today, I wrote a servlet jump and found several exceptions:
1. In the form Form on the JSP page, you must determine the data to be obtained,
For example, String title = request. getparameter ("title ");
If (title. Equals ("") {}<===============> instead of IF (Title = ""){}
2. An illegalstateexception or a null pointer exception occurs;
3. Error: cannot forward after response has been committed
(Because I am in the IF ------ else code: So the current exception occurs .)
Solution: Add a return to request. getrequestdispatcher (errorjsp). Forward (request, response;
Based on the above situation, you can use another method: (The following is all my code)
Public class adminpublishgonggaoservlet extends httpservlet {
Private Static string errorjsp = "/admin/gonggaoerror. jsp ";
Private Static string successjsp = "/admin/publishsuccess. jsp ";
Protected void doget (httpservletrequest request,
Httpservletresponse response) throws servletexception, ioexception {
Requestdispatcher rdsp = NULL;
Response. setcharacterencoding ("GBK ");
String title = request. getparameter ("title ");
String content = request. getparameter ("content ");
String manager = (string) request. getsession (). getattribute ("adminuserna ");
If (title. Equals ("")){
String MSG = "title cannot be blank ";
Request. setattribute ("gonggaomsg", MSG );
Request. getrequestdispatcher (errorjsp). Forward (request, response );
Rdsp = request. getrequestdispatcher (errorjsp); // do not submit it first
}
If (content. Equals ("")){
String MSG = "announcement content cannot be blank ";
Request. setattribute ("gonggaomsg", MSG );
Rdsp = request. getrequestdispatcher (errorjsp );
}
If (content. Length () & gt; 500 ){
String MSG = "Please keep the announcement content within 500 words! ";
Request. setattribute ("gonggaomsg", MSG );
Rdsp = request. getrequestdispatcher (errorjsp );
}
Gonggaobean gonggao = new gonggaobean (title, content, manager );
Try {
Addgonggaobpo. addgonggao (gonggao );
String MSG = "your announcement has been published successfully! ";
Request. setattribute ("gonggaomsg", MSG );
Rdsp = request. getrequestdispatcher (successjsp );
} Catch (exception e ){
String MSG = "sorry, system error. Please wait! ";
Request. setattribute ("gonggaomsg", MSG );
Rdsp = request. getrequestdispatcher (errorjsp );
} Finally {
If (rdsp! = NULL ){
Rdsp. Forward (request, response); // submit only here
}
}
}
Protected void dopost (httpservletrequest request,
Httpservletresponse response) throws servletexception, ioexception {
Doget (request, response );
}
}
However, the Code in try will be executed only after submission. This is not the case.
So the code can only be like this:
If (title. Equals ("")){
String MSG = "title cannot be blank ";
Request. setattribute ("gonggaomsg", MSG );
Request. getrequestdispatcher (errorjsp). Forward (request, response );
Return; // return is important here;
}