• BaseServlet优化Servlet,实现类似struts2的一些简单效果


    package cn.itcast.web.servlet;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    public class AServlet extends BaseServlet {
        
        
        private static final long serialVersionUID = 1L;
    
    
        /*@Override
        public void service(HttpServletRequest req, HttpServletResponse res)
                throws ServletException, IOException {
            
             * 1、获取参数,用来说明要调用的方法
             * 2、然后判断是哪个方法执行
             
            String methodName=req.getParameter("method");
            
            if(methodName == null || methodName.trim().isEmpty()){
                throw new RuntimeException("您没有传递method参数,无法确定要调用的方法");
            }
    //        if(methodName.equals("addUser")){
    //            addUser(req,res);
    //        }else if(methodName.equals("eidtUser")){
    //            editUser(req,res);
    //        }else if(methodName.equals("deleteUser")){
    //            deleteUser(req,res);
    //        }
            
             * 我们发现这样的代码不好复用
             * 1、我们可以通过方法名称,使用反射调用呢?
             *         需要得到class,然后调用它的方法进行查询
             *         我们查询的是当前类的方法
             
            
            Class c=this.getClass();
            Method method=null;
            try{
                method=c.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            }catch(Exception e){
                throw new RuntimeException("您要调用的方法"+methodName+"(HttpServletRequest,HttpServletResponse) 不存在");
            }
            
             * 调用method
             
            try {
                method.invoke(this, req,res);
            } catch (Exception e) {
                System.out.println("您调用的方法"+methodName+"(HttpServletRequest,HttpServletResponse) 内部抛出了异常");
                throw new RuntimeException(e);
            }
            
        }*/
        public void addUser(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println("addUser()...");
            throw new IOException("测试一下");
        }
    
        public void editUser(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println("editUser()...");
        }
        
        public void findAll(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println("findAllUser()...");
        }
        
        public void deleteUser(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println("deleteUser()...");
        }
    
    }
    /**
     * 我们发现这样复用性还是不够理想,我们可以抽象出一个弗雷给别人继承
     */
    package cn.itcast.web.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;
    
    @SuppressWarnings({"rawtypes","unchecked"})
    public class BaseServlet extends HttpServlet {
    
        private static final long serialVersionUID = 1L;
        
        @Override
        public void service(HttpServletRequest req, HttpServletResponse res)
                throws ServletException, IOException {
            
            String methodName=req.getParameter("method");
            if(methodName == null || methodName.trim().isEmpty()){
                throw new RuntimeException("您没有传递method参数,无法确定要调用的方法");
            }
            Class c=this.getClass();
            Method method=null;
            try{
                method=c.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            }catch(Exception e){
                throw new RuntimeException("您要调用的方法"+methodName+"(HttpServletRequest,HttpServletResponse) 不存在");
            }
            String text=null;//获取返回值
            try {
                text=(String) method.invoke(this, req,res);
                /*
                 *获取请求处理方法后返回的字符串,它表示转发或者重定向的路径 
                 *如果返回值中不包含“:”,表示使用默认方式:转发
                 *如果返回值中包含“:”,将字符串通过“:”截取为两部分,前一部分表示标识,f代表转发,r代表重定向
                 *如果返回的字符串是null或者"",我们什么也不干
                 */
            } catch (Exception e) {
                System.out.println("您调用的方法"+methodName+"(HttpServletRequest,HttpServletResponse) 内部抛出了异常");
                throw new RuntimeException(e);
            }
            if(text==null || text.trim().isEmpty()) return;
            if(!text.contains(":")){
                req.getRequestDispatcher(text).forward(req, res);
            }else{
                int index=text.indexOf(":");
                String bz=text.substring(0, index);
                String path=text.substring(index+1);
                if(bz.equalsIgnoreCase("r")){
                    res.sendRedirect(path);
                }else if(bz.equalsIgnoreCase("f")){
                    req.getRequestDispatcher(path).forward(req, res);
                }else{
                    throw new RuntimeException("您的指定:"+bz+"暂时没有开通此业务");
                }
            }
            
        }
        /**
         * 我们在Servlet中实现重定向和转发感觉有点麻烦,我们希望抽象出来再BaseServlet中处理
         * request.getRequestDispatcher("xxx").forward(request,response)
         * response.sendRedirect("xxx")
         */
    
    }
    package cn.itcast.web.servlet;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    
    public class BServlet extends BaseServlet {
        
        private static final long serialVersionUID = 1L;
        
        public String fun1(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException{
            //return "forward:/index.jsp";
            System.out.println("fun1()...");
            return "f:/index.jsp";
        }
        public String fun2(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException{
            //return "redirect:/index.jsp";
            System.out.println("fun2()...");
            return "r:"+req.getContextPath()+"/index.jsp";
        }
        public String fun3(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException{
            System.out.println("fun3()...");
            return "/index.jsp";
        }
        public String fun4(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException{
            System.out.println("fun4()...");
            return null;
        }
        public String fun5(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException{
            System.out.println("fun3()...");
            return "d:/index.jsp";
        }
    }

    BaseServlet
    1.我们希望在一个Servlet中可以有多个请求处理方法
    2、客户端发送请求时,必须多给出一个参数,用来说明要调用的方法
    3、参数名遵守约定
    4、希望帮助简化重定向和转发,利用返回值
    domain:User
    dao:UserDao
    service:UserService
    servlet:UserServlet

    void init(ServletConfig config)
    void destory()
    void service(ServletRequest,ServletResponse)throws IOException,ServletException{
    在这里让它去调用其他方法!
    要求:用户发出请求时,必须给出一个参数

  • 相关阅读:
    上古神器之Vim编辑器
    Git
    Git
    php之IP
    PHP常见错误汇总
    Redis教程(Windows)
    如何使用RSS
    (转)Spring Boot干货系列:(三)启动原理解析
    (转)Maven创建webapp项目无法修改web版本的问题
    (转)图文详解MyEclipse中新建Maven webapp项目的步骤
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/5717735.html
Copyright © 2020-2023  润新知