好友
阅读权限10
听众
最后登录1970-1-1
|
轩辕龙琊
发表于 2018-2-22 17:46
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);
}
}
}
|
|
发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。 |
|
|
|
|