文章目录
redirect:add.do
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ViewResolver {
/**
* 视图解析器
* @param returnValue controller方法的返回值
*/
public void process(Object returnValue, HttpServletRequest request,
HttpServletResponse response) {
String path=(String)returnValue;
try {
//判断是转发还是重定向
if (path.startsWith("redirect:")) { //重定向
response.sendRedirect(request.getContextPath()+"/"+path.split(":")[1]);
}else { //转发
request.getRequestDispatcher("/WEB-INF/"+path+".jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Scanner;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.reflect.Handler;
import cn.reflect.HandlerMapping;
import cn.reflect.ViewResolver;
import cn.utils.XMLUtils;
/**
* Servlet implementation class DispatcherServlet
*/
public class DispatcherServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
List<Object> beans;
try {
beans = XMLUtils.getBeans();// 获取xml配置文件中所有bean的对象
HandlerMapping handlerMapping = new HandlerMapping();
String uri = request.getRequestURI(); // 请求地址
String appName = request.getContextPath(); // 工程名
String path = uri.replace(appName, ""); // 获取注解的path
handlerMapping.init(beans); // 初始化
Handler handler = handlerMapping.getHandler(path); // 获取指定的Handler
Method method = handler.getMethod();
Object object = handler.getObject();
Class[] paramTypes = method.getParameterTypes(); // 获取方法中的参数类型
Object returnValue=null; //申明目标方法的返回值
// 如果调用的方法有参数
if (paramTypes.length > 0) {
Object[] args = new Object[paramTypes.length]; //创建参数列表
for (int i = 0; i < args.length; i++) {
Class cls = paramTypes[i];
// 判断类型是request或者response
if (cls == HttpServletRequest.class) {
args[i] = request;
} else if (cls == HttpServletResponse.class) {
args[i] = response;
}
}
returnValue=method.invoke(object, args);
} else {
returnValue=method.invoke(handler.getObject()); // 调用方法执行
}
//有返回值,要么转发,要么重定向
if (returnValue!=null) {
//通过视图解析器对象,处理转发或者重定向
ViewResolver viewResolver=new ViewResolver();
viewResolver.process(returnValue,request,response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}