封装BaseServlet类

封装BaseServlet类的目的是简化servlet的代码的繁重。

  private static final long serialVersionUID = 1L;
serialVersionUID作用:
相当于java类的身份证。主要用于版本控制。
serialVersionUID作用是序列化时保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性。
序列化时为了保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性。
package cn.mingliang.base.servlet;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.*;


public abstract class BaseServlet extends HttpServlet {
   
    private static final long serialVersionUID = 1L;
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/htmm;charset=utf-8");
        // 获得用户传递的参数
        String method = request.getParameter("method");
        // 判断用户是否传递参数,若没有传递参数则报错
        if (method == null || method.trim().isEmpty()) {
            System.out.println("hahah");
            throw new RuntimeException("请传递参数");
        }
        // 通过反射获得传递参数对应的方法
        // 若没有用户所传递参数对应的方法,则报错
        Method methodd = null;
        try {
            methodd = this.getClass().getMethod(method,
                    HttpServletRequest.class, HttpServletResponse.class);


        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            throw new RuntimeException("你没有创建该方法");
        }


        // 调用用户传递参数所对应的方法,并传入request、response
        // 若有方法内部有错误,则报错


        // 获得调用方法所返回的值,若无值则无操作,若为前缀为f或没有前缀则默认转发
        // 若为r则重定向
        // 若为其他 则报错
        try {
            String result = (String) methodd.invoke(this, request, response);
            if (result == null || result.trim().isEmpty()) {
                return;
            }
            //indexOf是获取括号里的符号的索引
            int index = result.indexOf(":");
            //截取字符串
            String prefix = result.substring(0, index);
            String path = result.substring(index + 1);
            if (result.contains(":")) {
                //equalsIgnoreCase是否包含,忽略大小写
                if (prefix.equalsIgnoreCase("r")) {
                    response.sendRedirect(request.getContextPath() + path);
                } else if (prefix.equalsIgnoreCase("f")) {
                    request.getRequestDispatcher(path).forward(request,
                            response);
                } else {
                    throw new RuntimeException("此版本暂不支持此方法");
                }
            } else {
                request.getRequestDispatcher(path).forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("内部抛出异常");
            throw new RuntimeException(e);
        }
    }
}

然后创建servlet类继承BaseServlet,在servlet类中就是这样写的

然后请求路径为

猜你喜欢

转载自www.cnblogs.com/fantongxue/p/11002040.html