【原创】JavaEE中关于Servlet的封装,欢迎大家提出建议
package com.system.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;
/**
* 完成对任意用户的请求进行处理的Servlet的封装
* 1、更新,删除,新增操作。
* 2、能够实现一个Servlet处理多种请求方式,简化在doGet方法中出现的大量if语句
* 3、方便后期维护
*
* 实现封装的思想:Java反射技术,来完成对Servlet的再一次封装
* @AuThor Administrator
*f:xxxx 转发
*r:xxxx 重定向
*/
@SuppressWarnings("serial")
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String v = request.getParameter("v");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
Method method ;
try {
method = getClass().getMethod(v, HttpServletRequest.class,HttpServletResponse.class);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
throw new RuntimeException("此方法"+v+"不存在",e);
}
//找到方法,则请求调用
try {
String result = (String)method.invoke(this, request,response);
if(result != null && !result.trim().isEmpty()){
int index = result.indexOf(":");
String param = result.substring(0, index);
String path = result.substring(index+1);
if(param.equals("f")){
request.getRequestDispatcher(path).forward(request, response);
}else if(param.equals("r")){//redirect重定向
response.sendRedirect(path);
}
}
} catch (Exception e) {
throw new RuntimeException("方法执行失败", e);
}
}
}
官方封装::
public class BaseServlet extends HttpServlet {
@Override
publicvoid service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//处理乱码
String methodName = request.getParameter("method");
if(methodName==null || methodName.trim().length()==0){
methodName="index";
}
Class clazz = this.getClass();//获得我们请求的Servlet的字节码(包裹)
try {
Methodmethod = clazz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);//获得
String Path = (String)method.invoke(this, request,response); //执行.path="/jsp/XXX.jsp"
if(Path!=null){
request.getRequestDispatcher(Path).forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("msg", "路径错误");
request.getRequestDispatcher("/jsp/msg.jsp").forward(request, response);
}
}
}
楼主那个也是很可以的 赞,虽然现在都是用框架了,但是最本质的还是不能忘记 我个人感觉这样在一步结合设计模式中的模板设计模式进一步封装较好。如:在调用方法之前的使用先做什么操作,后期可以对数据库的事务提交。在子类中做实现 而且在调用方法时需要做一层判断,增加代码的严谨性
看不懂,我是不是该加油了?
页:
[1]