BaseServlet的抽取

在开发中,对页面的请求要创建对个servlet来进行处理,一个servlet只能处理一个请求,这样要创建多个servlet,不利于开发和以后程序的维护,我们可以对同一个模块进行合并创建一个servlet即可,比如登录模块,商品模块,订单模块等等.只需要他们继承BaseServlet,并在前台页面传递所调用的方法名即可.


package cn.itcast.stroe.utils;


import java.io.IOException;

import java.lang.reflect.InvocationTargetException;

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 BaseServlet extends HttpServlet{


@Override

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

request.setCharacterEncoding("utf-8");

//1、获取方法名

String methodName = request.getParameter("methodName");

//2、获取当前运行类的class对象

Class clazz = this.getClass();

//3、动态获取方法对象

if(methodName!=null&&!"".equals(methodName)){

try {

Method method = clazz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);

//执行

String path = (String) method.invoke(this, request,response);

//判断 是否需要请求转发 

if(path!=null&&!"".equals(path)){

//请求转发

request.getRequestDispatcher(path).forward(request, response);

return;

}

} catch (NoSuchMethodException e) {

e.printStackTrace();

System.out.println("你需要的方法不存在");

} catch (SecurityException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (IllegalArgumentException e) {

e.printStackTrace();

} catch (InvocationTargetException e) {

e.printStackTrace();

}

}

}


}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章