servlet+Java反射机制实现mvc模式

2021-07-12 22:06

阅读:636

YPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

标签:ast   direct   名称   exce   exception   list   color   servlet   htm   

一,servlet基类,BaseController类继承HttpServlet,实现了doGET和doPost方法,相当于springmvc的dispacterservlet,我们只需要在web.xml注册一个BaseController即可。

BaseController.ava

package com.easygo.controller;

import java.io.IOException;
import java.util.Properties;

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

public class BaseController extends HttpServlet {
    
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    //调用properties 配置文件
    private  Properties  properties=new Properties();
    //字符编码集合
    private String charset="utf-8";
    
    @Override
    public void init(ServletConfig config) throws ServletException {
          
        //获取初始化的  参数  key  value
     String  configname=config.getInitParameter("configname");
    
    try {
        //自动加载配置文件
        properties.load(this.getClass().getClassLoader().getResourceAsStream(configname));
        
          //通过配置文件获取到字符编码集
      String tmp=    properties.getProperty("charset");
        if(tmp!=null){
            charset=tmp;
        }
    
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取失败!");
        }
    
    }
    
    

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {
        //设置字符编码集
        req.setCharacterEncoding(charset);    
        resp.setCharacterEncoding(charset);    
        
        //获取到  uri
        String act=      req.getRequestURI();
        // System.out.println(act);
        //      /MVCController/  user .do   
        // user  --- 找到Config文件的com.uplooking.action.UserAction
        act=act.substring(act.lastIndexOf("/")+1,act.lastIndexOf(".do"));
        // 获取类路径  System.out.println(act); 
        String classPath= properties.getProperty(act);
        // System.out.println(classPath);
        
        if(classPath==null||classPath.equals("")){
            resp.setContentType("text/html");
            resp.getWriter().println("没有您要访问的路径!");
            return;
        }
        
        
        //进行反射调用   
        Class    iActionClass =Class.forName(classPath);
        
        //反向实例
        IAction   iAction=(IAction) iActionClass.newInstance();
        
        //交给 子方法进行处理    处理完之后  只要 返回   String  request response
        //封装返回值 
        String result= iAction.execute(req, resp);
        System.out.println("返回值="+result);
        
        //有返回值的时候
        if(result!=null&&!"".equals(result)){
        
      /*        1 默认转发    return  "index.jsp";
              2 重定向        return  "@red_index.jsp"
               3json   return  "@json_{XXXXXX}"*/
            if(result.contains("@red_")){
                //重定向
                resp.sendRedirect(result.split("_")[1]);
            }else if(result.contains("@json_")){
                resp.setContentType("text/html");
                resp.getWriter().println(result.split("_")[1]);
                resp.getWriter().close();
            }else{
                req.getRequestDispatcher(result).forward(req, resp);
            }
            
        
        
        }else{
            //没有返回值的时候
            resp.setContentType("text/html");
            resp.getWriter().println("没有返回值!");
            return;
        }
        
        
        } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
        
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    
    
}

---------------------------------------------------------------------------------------------------------------------------------

web.xml配置:
MVCControllerBaseControllerclass>com.easygo.controller.BaseControllerclass>
         confignameActionConfig.properties0BaseController*.doindex.htmlindex.htmindex.jspdefault.htmldefault.htmdefault.jsp
 ---------------------------------------------------------------------------------------------------------------------------------
IAction接口,Action类实现IAction接口
package com.easygo.action;

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

import com.easygo.controller.IAction;

public class BookAction implements IAction{

    @Override
    public String execute(HttpServletRequest req, HttpServletResponse resp) {
        
        System.out.println("BookAction");
        return "@red_index.jsp";
    }

}
 ---------------------------------------------------------------------------------------------------------------------------------
ActionConfig.properties,key代表URL请求的名称,以.do为后缀,value是改类的全类名,用于反射。
charset=utf-8
#user.do
user=com.easygo.action.UserAction
#book.do
book=com.easygo.action.BookAction
json=com.easygo.action.JsonAction

 ---------------------------------------------------------------------------------------------------------------------------------
UserAction.java类,原理与springMVC的RequestMapping注解下的方法一样,用于数据返回和页面跳转。

package com.easygo.action;

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

import com.easygo.controller.IAction;

public class UserAction  implements IAction {

    @Override
    public String execute(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserAction");
        return "index.jsp";
    }
    
    
/*
 *   BaseController.java  把  HttpServletRequest req, HttpServletResponse resp
 *   通过反射 交给指定的类的 方法去处理 
 *   
 *             |
 *              |
 *   
 *          处理逻辑方法
 *   
 *   处理完之后        转发
 *            重定向
 *            json
 *            
 *      String   X指向   _   访问的页面/数据    
 *             |
 *             |
 *             |
 *      这个String --BaseController   
 *   
 *     @Override
    public String execute(HttpServletRequest req, HttpServletResponse resp) {
        // TODO Auto-generated method stub
        return null;
    }
    
    */

}
 ---------------------------------------------------------------------------------------------------------------------------------
JsonAction.java用于json数据的返回。
package com.easygo.action;

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

import com.easygo.controller.IAction;

public class JsonAction implements IAction{

    @Override
    public String execute(HttpServletRequest req, HttpServletResponse resp) {
        
        System.out.println("JsonAction");
        return "@json_{asdsadsadsadsadad}";
    }

}
 ---------------------------------------------------------------------------------------------------------------------------------
index.jsp

    pageEncoding="utf-8"%>Insert title here
          
     index.jsp         
          


 ---------------------------------------------------------------------------------------------------------------------------------
indexX.jsp


    pageEncoding="ISO-8859-1"%>



Insert title here
user.do


 ---------------------------------------------------------------------------------------------------------------------------------
测试:
运行indexX.jsp(tomcat8.0)
点击:user.do直接跳转到index.jsp
URL:http://localhost:8088/MVCController/user.do
具体代码:链接: https://pan.baidu.com/s/1spMCZ0hAn_FLAZb1OG5-Pw 密码: 77zi

 

servlet+Java反射机制实现mvc模式

标签:ast   direct   名称   exce   exception   list   color   servlet   htm   

原文地址:https://www.cnblogs.com/mature1021/p/9543729.html


评论


亲,登录后才可以留言!