BaseServlet简化Servlet

2020-12-14  本文已影响0人  Restart白蓝

一般使用场景在还没有MVC框架项目中,没得strus2 和spring mvc 等MVC框架使用,就当是基础复习。

一、创建一个base继承HttpServlet

package cn.com.servlet;
 
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 *
 *一个类多个请求处理方法,每个请求处理方法的原型与service相同!
 *原型 = 返回值类型 + 方法名称 + 参数列表
 */
public class BaseServlet extends HttpServlet {
        
        //重写Service方法
        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            /**
             * 1.获取method参数,它是用户想调用的方法
             * 2.把方法名称变成Method类的实例对象
             * 3.通过invoke()来调用这个方法
             */
            String methodName = request.getParameter("method");
            Method method = null;
            /**
             * 2.通过方法名称获取Method对象
             */
            try {
                method = this.getClass().getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                throw new RuntimeException("您要调用的方法:"+methodName+"它不存在!",e);
            } 
            
            /**
             * 3.通过method对象来调用它
             */
            try {
                method.invoke(this, request,response);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

二、其他类使用只需要继承

package servlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/user")
public class UserServlet extends BaseServlet {

    public void add(HttpServletRequest request, HttpServletResponse response){
        System.out.println("执行了添加方法");
    }

    public void update(HttpServletRequest request, HttpServletResponse response){
        System.out.println("执行了更新方法");
    }
}

三、请求地址

http://localhost:8080/user?method=add
上一篇 下一篇

猜你喜欢

热点阅读