JAVA重写servlet实现地址栏参数访问

大致功能是类似IndexServlet等Servlet方法去掉doGet,doPost地址栏通过?action=??实现访问具体方法

思路:编写AbstractServlet实现此功能,其他Servlet继承此类

package com.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AbstractServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1 当前是哪个Servlet类
		Class clazz=this.getClass();
		//System.out.println(clazz);
		//2、获取到Servlet类中要执行的方法名
		String methodName=req.getParameter("action");
		//System.out.println("方法名:"+methodName);
		//3、执行方法(反射)
		
		try {
			//创建一个类对象
			Object obj=clazz.newInstance();
			//根据方法名称获取指定的方法
			Method m=clazz.getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			//调用方法
			m.invoke(obj, req,resp);
			
		} catch (Exception e) {
			
			e.printStackTrace();
		} 
	}

}
package com.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class IndexServlet
 */
@WebServlet("/IndexServlet")
public class IndexServlet extends AbstractServlet {
    private static final long serialVersionUID = 1L;

    public IndexServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void index(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.sendRedirect("index.jsp");	
    }
    
    public void list(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.sendRedirect("list.jsp");	
    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.sendRedirect("login.jsp");	
    }
    public void add(HttpServletRequest request, HttpServletResponse response) {
        //
    }

}

 

你可能感兴趣的:(JavaWeb)