在一个Servlet中处理多个请求方法

来源:互联网 发布:dns设置软件 编辑:程序博客网 时间:2024/06/05 14:49

1. 在一个Servlet中可以有多个请求处理方法!
2. 客户端发送请求时,必须多给出一个参数,用来说明要调用的方法
  请求处理方法的签名必须与service相同,即返回值和参数,以及声明的异常都相同!
3. 客户端必须传递一个参数!

package servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class AServlet extends HttpServlet {public void service(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {// TODO Auto-generated method stub/* * 1.获取参数,识别用户想请求的方法 */String methodName = req.getParameter("method");if(methodName.equals("addUser")) { addUser(req,res);}else if(methodName.equals("editUser")) { editUser(req,res);}else if(methodName.equals("deleteUser")) {deleteUser(req,res);}else if(methodName.equals("loadUser")) {loadUser(req,res);}}public void addUser(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("addUser()...");}public void editUser(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("editUser()...");}public void deleteUser(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("deleteUser()...");}public void loadUser(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("loadUser()...");}}

service方法的参数与用户想调用的方法的参数一致

http://localhost:8080/day0213_1/AServlet?method=deleteUser

但是每添加一个新方法,service中就需要多加一个else if语句,作以下改进:

public void service(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {// TODO Auto-generated method stub/* * 1.获取参数,识别用户想请求的方法 */String methodName = req.getParameter("method");if(methodName==null || methodName.isEmpty()){throw new RuntimeException("没有传递method参数");}/* * 得到方法名称,通过反射调用方法 *   得到方法名,通过方法名得到Method类的对象! */Class c=this.getClass();Method method=null;try {method =c.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);} catch (Exception e) {// TODO Auto-generated catch blockthrow new RuntimeException("您调用的方法"+methodName+"不存在!");} /* * 调用method表示的方法 */try {method.invoke(this, req,res);} catch (Exception e) {System.out.println("您调用的方法"+methodName+"内部抛出了异常");throw new RuntimeException (e);} }


0 0