这几天在学Java Web,一直在思考Servlet重用的问题,就用java的反射机制实现自定义的简易版BaseServlet;

 

该方式有点像struts2 利用映射获取前端的参数。有兴趣的同学可以自行添加别的类的判断

直接上代码,映射方式被我封装成了一个BaseServlet

BaseServlet.java

public class BaseServlet extends HttpServlet{
    private HttpServletRequest req;
    private HttpServletResponse resp;
    
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        this.req = req;
        this.resp = resp;
        
        // 获取用户请求的方法名
        String mName = req.getParameter("method");
        
        try {
            // 根据用户请求的方法获取用户指定的方法
            Method method = this.getClass().getMethod(mName, null);// 调用用户指定的方法并得到返回数据
              method.invoke(this, null);
            
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    
    // 自定义方法1
    public void login() throws IOException{
         System.out.println("login");
    }
    
    // 自定义方法2
    public void logout() throws IOException{
        System.out.println("logout");
    }
}

web.xml配置

<servlet>
     <servlet-name>bs</servlet-name>
     <servlet-class>com.blk.action.BaseServlet</servlet-class>
 </servlet>
 
 <servlet-mapping>
     <servlet-name>bs</servlet-name>
     <url-pattern>/bs</url-pattern>
 </servlet-mapping>

访问方法

地址栏访问http://localhost:8080/项目名/bs?method=方法名      

 // 访问自定义方法一
  <a href="项目名/bs?method=login">
 // 访问自定义方法二
 <a href="项目名/bs?method=logout">

 

posted on 2016-08-06 11:07  ice_ghost  阅读(349)  评论(0编辑  收藏  举报