package com.framework;
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;
public class ActionServlet extends HttpServlet {
String actionPackage="";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
System.out.println("===进入 "+this.getClass().getName());
String url = request.getRequestURI();
String actionName = "";
String methodName = "";
try{
System.out.println("===请求是: "+ url);
actionName = url.substring(url.lastIndexOf('/')+1, url.lastIndexOf('.'));
System.out.println("===类名是: "+ actionName);
methodName = url.substring(url.lastIndexOf('.')+1);
System.out.println("===方法是: "+methodName);
}catch(Exception e){
throw new ActionException("===不合法的url:["+url+"]/t"+e.getMessage(),e.getCause());
}
Object action = findAction(actionName);
System.out.println("/t===获得Action:"+ action);
Method method = findMethod(action,methodName);
System.out.println("/t===获得方法:"+method);
//调用 javaBean
ActionForward returnValue = (ActionForward)method.invoke(action, request,response);
if(null == returnValue) throw new ActionException("===["+actionName+"]的["+methodName+"]没有返回值!");
System.out.println("/t===跳转的url:"+returnValue.getContent());
//负责 跳转
if(returnValue.getType()==ActionForward.redirect_true){
response.sendRedirect(request.getContextPath()+returnValue.getContent());
}else if(returnValue.getType() == ActionForward.redirect_false){
request.getRequestDispatcher(returnValue.getContent()).forward(request, response);
}else{
response.getWriter().print(returnValue.getContent());
}
}catch (Exception e) {
e.printStackTrace();
}
}//doGet()
private Object findAction(String acName)throws Exception{
Object action = null;
String actionPath = actionPackage+"."+acName;
try{
Class clz = Class.forName(actionPath);//加载类 //UsersAction action;
action = clz.newInstance(); //action = new UsersAction();
}catch(Exception e){
throw new ActionException("===给定的路径["+actionPath+"]不能得到类实例/t"+e.getMessage(),e.getCause());
}
return action;
}//findAction()
private Method findMethod(Object action,String mdName) throws Exception{
Method md = null;
try{
md = action.getClass().getMethod(mdName, HttpServletRequest.class,HttpServletResponse.class);
}catch(Exception e){
throw new ActionException("===类型["+action.getClass()+"]不那得到["+mdName+"(HttpServletRequest,HttpServletResponse)]方法/t"+e.getMessage(),e.getCause());
}
return md;
}//findMethod()
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
@Override
public void init() throws ServletException {
this.actionPackage = this.getInitParameter("actionpackage");
}
}
一个servlet类反射相应实现servlet功能的普通类
最新推荐文章于 2023-12-05 19:53:04 发布