servlet反射,模拟struts的action控制跳转

通常我们一个servlet控制一个请求,这个是常规操作。一般初学者基本都是这么做的,而实际开发中,我们似乎是不能这样操作,实际开发中我们会有很多请求过来,那是不是应该定义很多个servlet呢?这样对于系统的开发是很不利的,那么我们有没有其他的操作方式呢,答案是肯定的。

首先定义一个BaseServlet

package com.enson.base;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

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

public class BaseServlet extends HttpServlet {

	public BaseServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); 
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			request.setCharacterEncoding("utf-8");
			process(request, response);
		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	}

	@SuppressWarnings("unchecked")
	public void process(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		<span style="color:#FF0000;">String action = request.getParameter("flag");</span>//此时servlet的方法执行交给了前端请求控制,根据flag的值,确定需要执行的方法
		try {
			<strong><span style="color:#FF0000;">Class clz = this.getClass();//执行反射即可
			Method method = clz.getDeclaredMethod(action,
					HttpServletRequest.class, HttpServletResponse.class);
			method.invoke(this, request, response);</span></strong>
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void init() throws ServletException {
	}
}


你可能感兴趣的:(exception,String,前端,servlet,struts)