BaseServlet

码农软件 · 软件分类 · 常用工具包 · 2019-08-15 20:56:57

软件介绍

BaseServlet 是个类似 struts 的功能的小工具类,一个Servlet中可以有多个请求处理方法。

客户端发送请求时,必须多给出一个参数,用来说明要调用的方法,请求处理方法的返回值和参数须与service有相同,以及声明的异常都相同。

客户端必须传递名为method的参数。

    String name = request.getParameter("method");

    if (name == null || name.trim().isEmpty()) {
        throw new RuntimeException("你好,你没有输入方法参数");
    }

    Class c = this.getClass();
    Method method = null;
    try {
        method = c.getMethod(name, HttpServletRequest.class,
                HttpServletResponse.class);

    } catch (Exception e) {
        throw new RuntimeException("你好,你要调用的方法" + name + ",不存在");
    }
    try {
        String result = (String) method.invoke(this, request, response);
        /*
         * 获取请求处理方法执行后返回的字符串,它表示转发或重定向的路径! 帮它完成转发或重定向!
         */
        /*
         * 如果用户返回的是字符串为null,或为"",那么我们什么也不做!
         */

        if (result == null || result.trim().isEmpty()) {
            return;
        }
        /*
         * 查看返回的字符串中是否包含冒号,如果没有,表示转发 如果有,使用冒号分割字符串,得到前缀和后缀!
         * 其中前缀如果是f,表示转发,如果是r表示重定向,后缀就是要转发或重定向的路径了!
         */
        if (result.contains(":")) {
            int index = result.indexOf(":");// 获取冒号的位置
            // 使用冒号分割字符串,得到前缀和后缀
            String s = result.substring(0, index);// 截取出前缀,表示操作
            String path = result.substring(index + 1);// 截取出后缀,表示路径
            if (s.equalsIgnoreCase("r")) {// 如果前缀是r,那么重定向!
                response.sendRedirect(request.getContextPath() + path);//项目名+index.jsp组合成完整的路径
                //重定向要完整的路径,转发则不需要完整的路径只需要/index.jsp即可。
            } else if (s.equalsIgnoreCase("f")) {// 如果前缀是F,那么转发!
                request.getRequestDispatcher(path).forward(request,
                        response);
            } else {
                throw new RuntimeException("对不起,你要访问的方法版本不支持!");
            }
        } else {// 没有冒号,默认为转发!
            request.getRequestDispatcher(result).forward(request, response);

        }
    } catch (Exception e) {
        System.out.println("你好,你调用的方法,内部出现了异常");
        throw new RuntimeException(e);
    }
}
}

本文地址:https://codercto.com/soft/d/12448.html

Big Java Late Objects

Big Java Late Objects

Horstmann, Cay S. / 2012-2 / 896.00元

The introductory programming course is difficult. Many students fail to succeed or have trouble in the course because they don't understand the material and do not practice programming sufficiently. ......一起来看看 《Big Java Late Objects》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具