ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

BaseServlet

2021-06-11 02:04:07  阅读:15  来源: 互联网

标签:BaseServlet http class key import servlet javax


通过反射调用方法,以简化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,http,class,key,import,servlet,javax
来源: https://www.cnblogs.com/1river/p/14873541.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有