梦相随1006

版权归 梦相随1006 所有,未经 https://www.cnblogs.com/xin1006 作者许可,严禁转载

导航

自定义BaseServlet利用反射

比较完美一点的BaseServlet

package com.yangwei.mvc.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;

/**
 * 这个BaseServlet类不需要在web.xml中进行配置
 */
public class BaseServlet extends HttpServlet {
    
    private static final long serialVersionUID = 1L;
    /**
     * 所有的Servlet请求都会被service()方法拦截
     */
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //传递过来用户的操作名(add,list,update等)即可
        String mm=request.getParameter("operate");
        Method method=this.getClass().getMethod(mm, HttpServletRequest.class,HttpServletResponse.class);
        String rel=method.invoke(this, request,response);
        String redirStr="redirect:";
        if(rel.startsWith(redirStr)){
            //客户端跳转
            response.sendRedirect(rel.substring(redirStr.length()));
        }else{
            //将服务器端的跳转转移到这里统一执行
            request.getRequestDispatcher("/WEB-INF/"+rel).forward(request,response);
        }
        
    }

}

我们的具体Servlet继承BaseServlet即可

package com.yangwei.mvc.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.yangwei.mvc.model.User;

/**
 * 我们具体的Servlet继承BaseServlet
 * 各个方法的返回值说明我们要跳转到的页面
 */
public class MyServlet extends BaseServlet {
    
    public String add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("add method");
        //对于客户端跳转,我们用redirect:标识
        return "redirect:my/add.jsp";
    }
    public String update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("update method");
        //服务器端的跳转
        return "my/update.jsp";
    }
    public String delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("delete method");
        //服务器端的跳转
        return "my/delete.jsp";
    }
}

如果在把方法名与返回值映射到配置文件中,就是一个简易的struts2了

posted on 2013-09-24 14:25  梦相随1006  阅读(766)  评论(0编辑  收藏  举报