If we want to handle multiple requests in a servlet (such as adding and deleting news), it is simple to add a key-value pair to the action path of the JSP submission form, and then call the different methods according to different values after receiving them in the servlet.
JSP side
1 <form action= "Newsservlet?method=add" method= "POST" >2 <input type= "text" ... >3 <input type= "Submit". >4 </form>
Servlet side
1 String method = Request.getparameter ("method"); 2 if (Method.equals ("Add")) {3 // Handling Additions 4 }5 elseif(method.equals ("delete")) {6 // processing Delete 7 }
Now let's talk about using the reflection mechanism of Java to handle the business accordingly.
JSP side
<form action= "Add.newsservlet" method= "POST" > <input type= "text" ... > <input type= "Submit". > </form><form action= "delete.newsservlet" method= "POST" > <input type= "text" ... > <input type= "Submit". ></form>
Web. XML config servlet-mapping url-pattern as "*.newsservlet"
Servlet side
protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException { Req.setcharacterencoding ("UTF-8"); Resp.setcontenttype ("UTF-8"); String Servletpath = Req.getservletpath (); Remove the previous/and subsequent. Newsservlet in the servlet path, leaving only the middle request type string methodName = servletpath.substring (1); methodName = Methodname.substring (0, Methodname.length ()-12); System.out.println (methodName); try { //Use reflection to get information about the method of the corresponding request type methods = GetClass (). Getdeclaredmethod ( MethodName, Httpservletrequest.class,httpservletresponse.class);//Use reflection to invoke execution method Method.invoke (this, REQ,RESP);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}
Of course the servlet also corresponds to Add.newsservlet and delete.newsservlet to achieve the corresponding add (httpservletrequest req, HttpServletResponse resp), and delete (HttpServletRequest req, HttpServletResponse resp) methods.
Use the Java reflection mechanism to implement a servlet to handle multiple requests