BaseServlet请求处理

BaseServlet 是项目中所有servlet的父类,作用是为了让一个servlet可以同时处理多个请求候,每一个需求就要创建一个servlet,这样会显得很臃肿,所以就用到BaseServlet;采用的是反射的技术。

BaseServlet就应运而生了,它作为一个项目中所有servlet的基类,(个人感觉该类属于设计模式中的前端控制器,类似SpringMVC的DispatcherServlet),其中并没有任何的业务逻辑,只负责将请求处理后分发到不同的servlet进行不同的处理。

BaseServlet类只重写了service方法所以我只贴出service方法的代码

 void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {   
 //下面这个if语句可以不用看,这里用到了我项目中另一个类:GetRequest,该类继承了HttpRequestWrapper,将request进行了包装,主要是防止乱码    if(((HttpServletRequest)request).getMethod().equalsIgnoreCase("get")) {    
    if(!(request instanceof GetRequest)) {      
      request = new GetRequest((HttpServletRequest)request);     
   }    
} else {  
((HttpServletRequest)request).setCharacterEncoding("utf-8");  
  } //设置response的返回数据格式以及字符编码    response.setContentType("text/html;charset=UTF-8"); 
//在这里获取前台传来的method参数    
String methodName = ((HttpServletRequest)request).getParameter("method");    
/** Method类,是java反射机制使用到的一个类     * API对该类的解释是:提供关于类或接口上单独某个方法(以及如何访问该方法)的信息。     * 看到这里是不是有点清楚BaseServlet是怎么调用方法的了?     * 这里先定义了一个Method的引用,遵循编写代码的规范原则,在try-catch外定义引用,块内实现     */ 
Method method = null;    
 try {
/* 这行代码的意思是实例化一个以methodName命名,以HttpServletRequest对象和HttpServletResponse对象做参数的方法         * 大家都知道this指的是调用当前方法的类的对象         * 所以不要想当然的认为this指的是BaseServlet对象,而是继承自BaseServlet的、与你请求的url相匹配的Servlet         * 这个Servlet当然由你自己实现         */        
method = this.getClass().getMethod(methodName, new Class[]{HttpServletRequest.class, HttpServletResponse.class});    
} catch (Exception var10) {//你自定义的servlet中没有对应的方法时,处理异常。        
throw new RuntimeException("您要调用的方法:" + methodName + "它不存在!", var10);    }     try {//这行代码表示调用了刚才实例化的Method对象所对应的方法,并用e接收方法的返回值        String e = (String)method.invoke(this, new Object[]{request, response}); 
//对e进行一些必要的判断        
if(e != null && !e.trim().isEmpty()) {/* 这里需要解释一下返回字符串的构成             * 可以直接返回要跳转的视图名,这样将会跳转到对应视图             * 若返回视图名的字符串前指定了转发的方式,如:f:list.jsp 或 r:list.jsp             * 那么下面语句会判断使用何种方式转发视图             */ 
int index = e.indexOf(":");
if(index == -1) {//没有指定视图的转发方式 ((HttpServletRequest)request).getRequestDispatcher(e).forward((ServletRequest)request, response);            
} else {                
String start = e.substring(0, index);                String path = e.substring(index + 1);                
if(start.equals("f")) {                   
//如果指定了f,则使用forward方式跳转 ((HttpServletRequest)request).getRequestDispatcher(path).forward((ServletRequest)request, response);                
} else if(start.equals("r")) {                   
//如果指定了r,则使用redirect方式重定向 response.sendRedirect(((HttpServletRequest)request).getContextPath() + path);                }          
  }      
  }    
 } catch (Exception var9) {        
throw new RuntimeException(var9);    }}

代码的执行流程如上。总结一下:

该方法中使用了反射机制来调用方法,不论你的Servlet中有多少方法,这段代码都不需要改变,只需要你提供方法名和参数列表就可以完成调用。若有别的domain类添加,只需要将对应的Servlet继承该类即可,不需要额外的代码。 继承后你只需要关心自己的逻辑即可,不用关心怎样被调用。

  <servlet>
    <servlet-name>DoServlet</servlet-name>
    <servlet-class>com.platform.core.web.DoServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>DoMyServlet</servlet-name>
    <servlet-class>com.cnten.platform.core.web.DevlpServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DoMyServlet</servlet-name>
    <url-pattern>/DoMyServlet</url-pattern>
  </servlet-mapping>
import java.net.URLDecoder;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import com.platform.core.ActionExecutor;
import com.platform.core.AppMgr;
import com.platform.core.Metadata.Func;
import com.platform.core.Metadata.FuncFactory;
import com.platform.core.base.Bean;
import com.platform.core.exception.CoreException;
import com.platform.core.exception.NoLoginException;
import com.platform.core.log.vo.LogRecord;
import com.platform.util.CommonUtils;
import com.platform.util.JsonUtils;

/**
 * DoServlet
 */
public class DoServlet extends BaseServlet {
    private static final long serialVersionUID = 1L;

    /**
     * {@inheritDoc} * @return Object
     * @throws Exception
     */
    protected Object doAct() throws Exception {
        HttpServletRequest request = Request.getInst();
        String uri = request.getRequestURI();
        String[] fa = uri.substring(uri.lastIndexOf("/") + 1).split("\\.");
        if (fa.length > 2 && fa[0].length() > 0 && fa[1].length() > 0) {
            String func = URLDecoder.decode(fa[0], "utf-8");
            String act = fa[1];
            String encode = param("encode");
            String menuCode = param("menuCode");
            Bean paramBean = JsonUtils.transferToBean(URLDecoder.decode(param("data"), "utf-8"));
            String param;
            Enumeration<?> paramEnum = request.getParameterNames();
            while (paramEnum.hasMoreElements()) {
                param = (String) paramEnum.nextElement();
                if (!param.equals("data")) {
                    String[] params = request.getParameterValues(param);
                    if(!CommonUtils.isNullOrEmptys(params) && params.length > 1){
                    	for(int i = 0; i < params.length; i++){
                    		params[i] = URLDecoder.decode(params[i], "utf-8");
                    	}
                    }
                    if("no".equals(encode)){
                    	paramBean.set(param, !CommonUtils.isNullOrEmptys(params) && params.length > 1 ? params
                                : request.getParameter(param));
                    }else {
                    	paramBean.set(param, !CommonUtils.isNullOrEmptys(params) && params.length > 1 ? params
                                : URLDecoder.decode(request.getParameter(param),"utf-8"));
                    }
                }
            };
            AppMgr.setThreadVar("paramBean", paramBean);
            AppMgr.setThreadVar("LogInfo", new LogRecord(paramBean, func, act));
           // IFunc funcEntity = FuncFactory.getInstance().getFunc(func);
            AppMgr.setThreadVar("menuCode", menuCode);
            Func funcEntity = FuncFactory.getInstance().getFunc(func);
            if (funcEntity.isSessionRequest() ) {
                // 判断用户是否已经登录
                if (Request.curUser() == null) {
                    throw new NoLoginException();
                }
//                if(((Func)funcEntity).isLimitFunc() && !UserUtils.isFuncRole(Request.curUser().getCode(), func)){
//                    throw new TipException("对不起,您没有查看此功能的权限!");
//                }
            }
            return new ActionExecutor().doAct(func, act, paramBean);
        } else {
            throw new CoreException("无效的请求:" + request.getRequestURI());
        }
    }
}
// Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://kpdus.tripod.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi space 
// Source File Name:   DevlpServlet.java


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

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

import com.platform.core.AppMgr;

// Referenced classes of package com.cnten.platform.core.web:
//			BaseServlet, Request, Response

public class DevlpServlet extends BaseServlet
{
	
	private static final long serialVersionUID = 5082792295659765681L;
	/**
	 *	给className 指定一个默认文件夹,在DevlpFiles.properties中配置
	 **/
	private static String FilesName=new String();
	@Override
	public void init() throws ServletException { 
		try { 
//			String path = System.getProperty("path");
			String path = AppMgr.getInstance().var("WEBINFPATH").toString();
//			String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
			path=path.substring(0, path.indexOf("classes"));// 获取WEB-INFO的路径
			InputStream input=new FileInputStream(new File(path+"DevlpFiles.properties"));
			Properties p = new Properties();
		    p.load(input);  
		    FilesName=p.getProperty("FilesName").toString(); 		
		} catch (FileNotFoundException e) { 
			e.printStackTrace();
		} catch (IOException e) { 
			e.printStackTrace();
		} 
		
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		this.doPost(request, response);

	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		request.setCharacterEncoding("UTF-8");
		Request.setInst(request);
		Response.setInst(response);
		Object methodName = request.getParameter("methodName");
		Object className  = request.getParameter("className");
		if (null != methodName && null != className) {
			try {
				// ============执行方法======================================
				String[] pkgNameArr = FilesName.split(",");
				Class<?> cls = null;
				Object data = null;
				for(int i = 0; i < pkgNameArr.length; i++) {
					System.out.println(pkgNameArr[i]+"."+className.toString());
					try {
						cls = Class.forName(pkgNameArr[i]+"."+className.toString()); // 加载类 
						Method mf = cls.getMethod(methodName.toString()); // 加载方法
						data = mf.invoke(cls.newInstance()); // 执行方法
						break;
					} catch (ClassNotFoundException e) {
						continue;
					}
				}
				// ============是否页面跳转====================================
				String forWard = request.getParameter("forWard");
				if (null != forWard) {
					if(forWard.equals("isFile")){
						System.out.println("");
					}else{
						//转发
						Request.getInst().getRequestDispatcher(forWard.toString()).forward(Request.getInst(), Response.getInst());
					}
				} else {
					//JSON输出
					writeResult(data);
				} 
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (ServletException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			}
		}
	}


//	public DevlpServlet()
//	{
//	}
//	
//	/**
//	 *	给className 指定一个默认文件夹,在DevlpFiles.properties中配置
//	 **/
//	private static String FilesName=new String();
//	@Override
//	public void init() throws ServletException { 
//		try { 
//			String path = this.getClass().getResource("").toURI().getPath();
//			path=path.substring(0, path.indexOf("classes"));//获取WEB-INFO的路径
//			InputStream input=new FileInputStream(new File(path+"DevlpFiles.properties"));
//			Properties p = new Properties();
//		    p.load(input); 
//		    //p.load( Request.getInst().getSession().getServletContext()
//		     //	.getResourceAsStream(path+"DevlpFiles.properties")); 
//		    FilesName=p.getProperty("FilesName").toString(); 		
//		} catch (FileNotFoundException e) { 
//			e.printStackTrace();
//		} catch (IOException e) { 
//			e.printStackTrace();
//		} catch (URISyntaxException e) { 
//			e.printStackTrace();
//		}
//		
//		
//	}
//	@Override
//	public void doGet(HttpServletRequest request, HttpServletResponse response)
//			throws IOException {
//		this.doPost(request, response);
//
//	}
//
//	@Override
//	public void doPost(HttpServletRequest request, HttpServletResponse response)
//			throws IOException {
//		request.setCharacterEncoding("UTF-8");
//		Request.setInst(request);
//		Response.setInst(response);
//		Object methodName = request.getParameter("methodName");
//		Object className  = request.getParameter("className");
//		if (null != methodName && null != className) {
//			try {
//				// ============执行方法======================================
				Class cls = Class.forName(FilesName+"."+className.toString()); // 加载类
// 			
//				Class cls =null; 
//				if("com.cnten.platform.core.cache.ModelCacheManager".equals(className)){
//					cls= Class.forName(className.toString()); // 加载类	
//				}else{
//					cls= Class.forName(FilesName+"."+className.toString()); // 加载类
//				}
//				Method mf = cls.getMethod(methodName.toString());// 加载方法
//				Object data = mf.invoke(cls.newInstance()); 	 // 执行方法
//				// ============是否页面跳转====================================
//				String forWard = request.getParameter("forWard");
//				if (null != forWard) {
//					//转发
//					Request.getInst().getRequestDispatcher(forWard.toString()).forward(Request.getInst(), Response.getInst());
//				} else {
//					//JSON输出
//					writeResult(data);
//				} 
//			} catch (IllegalAccessException e) {
//				e.printStackTrace();
//			} catch (SecurityException e) {
//				e.printStackTrace();
//			} catch (NoSuchMethodException e) {
//				e.printStackTrace();
//			} catch (IllegalArgumentException e) {
//				e.printStackTrace();
//			} catch (InvocationTargetException e) {
//				e.printStackTrace();
//			} catch (ClassNotFoundException e) {
//				e.printStackTrace();
//			} catch (ServletException e) {
//				e.printStackTrace();
//			} catch (InstantiationException e) {
//				e.printStackTrace();
//			}
//		}
//	}

	
	
//	public void doGet(HttpServletRequest request, HttpServletResponse response)
//		throws IOException
//	{
//		doPost(request, response);
//	}

//	public void doPost(HttpServletRequest request, HttpServletResponse response)
//		throws IOException
//	{
//		request.setCharacterEncoding("UTF-8");
//		Request.setInst(request);
//		Response.setInst(response);
//		Object methodName = request.getParameter("methodName");
//		Object className = request.getParameter("className");
//		if (methodName != null && className != null)
//			try
//			{
//				Class cls = Class.forName(className.toString());
//				Method mf = cls.getMethod(methodName.toString(), new Class[0]);
//				Object data = mf.invoke(cls.newInstance(), new Object[0]);
//				String forWard = request.getParameter("forWard");
//				if (forWard != null)
//					Request.getInst().getRequestDispatcher(forWard.toString()).forward(Request.getInst(), Response.getInst());
//				else
//					super.writeResult(data);
//			}
//			catch (IllegalAccessException e)
//			{
//				e.printStackTrace();
//			}
//			catch (SecurityException e)
//			{
//				e.printStackTrace();
//			}
//			catch (NoSuchMethodException e)
//			{
//				e.printStackTrace();
//			}
//			catch (IllegalArgumentException e)
//			{
//				e.printStackTrace();
//			}
//			catch (InvocationTargetException e)
//			{
//				e.printStackTrace();
//			}
//			catch (ClassNotFoundException e)
//			{
//				e.printStackTrace();
//			}
//			catch (ServletException e)
//			{
//				e.printStackTrace();
//			}
//			catch (InstantiationException e)
//			{
//				e.printStackTrace();
//			}
//	}
}
var strUrl = Leopard.getContextPath() +
		"/DoMyServlet?className=ExcelPoiAction&methodName=createExcel&btnCode=empdata&forWard=isFile&namesalt="+namesalt+"&func="+_func
	    +"&pbean="+encodeURI(encodeURI(strwhere))+"&btnCode"+empexcel;
		var ifm;
		if (document.getElementById("empexcel_iframe") == undefined) {
			ifm = document.createElement("IFRAME");
			ifm.setAttribute("id", "empexcel_iframe");
			ifm.setAttribute("name", "empexcel_iframe");
			ifm.style.height = "0";
			ifm.style.width = "0";
			ifm.style.display = "block";
			ifm.src = "";
			document.body.appendChild(ifm);
			document.getElementById("empexcel_iframe").attachEvent(
					"onload",
					function() {
						window.frames['empexcel'].document.getElementById("empexcel").click();
					});
		} else {				ifm = document.getElementById("empexcel_iframe");			}
		ifm.src = strUrl; 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wespten

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值