• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

BaseServlet

开发技术 开发技术 3小时前 3次浏览

通过反射调用方法,以简化Servlet数量。

class BashServlet

package com.demo.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/* as superclass for all sub-class*/
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req,
                           HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        try {
            String key = req.getParameter("key");
            Class<? extends BaseServlet> clazz = this.getClass();
            // key is the method name
            Method method = clazz.getMethod(key, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

XServlet

package com.demo.servlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/x")
public class XServlet extends BaseServlet{

    public void methodA(HttpServletRequest request,
                           HttpServletResponse response)throws  Exception{
           // some codes
    }

}

测试

you can use this url to test http message.
url path: contextname/servletname?key=methodname
此处就是:contextname/x?key=methodA。


程序员灯塔
转载请注明原文链接:BaseServlet
喜欢 (0)