码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-08-27 21:55:36      阅读:193      评论:0      收藏:0      [点我收藏+]

标签: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配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>MVCController</display-name>
  
  
  <servlet>
         <servlet-name>BaseController</servlet-name>
           <servlet-class>com.easygo.controller.BaseController</servlet-class>
         <init-param>
            <param-name>configname</param-name>
            <param-value>ActionConfig.properties</param-value>
         </init-param>
         <load-on-startup>0</load-on-startup>
  </servlet>
  
  <servlet-mapping>
     <servlet-name>BaseController</servlet-name>
     <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
  
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>
 ---------------------------------------------------------------------------------------------------------------------------------
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
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
          
     index.jsp         
          
</body>
</html>
 ---------------------------------------------------------------------------------------------------------------------------------
indexX.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="user.do">user.do</a>
</body>
</html>
 ---------------------------------------------------------------------------------------------------------------------------------
测试:
运行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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!