转载

Spring MVC中的DispatcherServlet的使用

 Servlet

自定义的 `Servlet` 继承 `HttpServlet` (Java 服务端组件,接收 HTTP 请求,调用业务逻辑,完成 HTTP 响应)

 

Servlet 生命周期(容器管理)

1. 实例化 - 构造器

 默认第一访问,可配置程序启动就初始化

2. 初始化 - init()

3. 运行 - service() 根据 HTTP 请求方法分发到一下方法中:

doGet()

doPost()

doPut()早期版本默认无效

doDelete() 早期版本默认无效

4. 销毁 - destory()

 

默认一个 Servlet 映射一个 URL 路径

/user--> UserServlet

/order--> OrderServlet

/dept--> DeptServlet

/staff` --> StaffServlet

/other--> OtherServlet

 


 

 


 


认识Spring MVC,这三张图很重要!!! 


现在让我们通过代码形式来认识Spring MVC中的DispatcherServlet。

工程目录:dao包中的和mapper包里以及repository包中的一样,不同的地方用不同的,作用都是一样的。


DispatchServlet.java

package com.newer.mvc.web;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.newer.mvc.web.controller.DeptController;
import com.newer.mvc.web.controller.StaffController;

/**
 *   /*匹配(拦截)所有的请求
 * @author Admin
 *
 */
@WebServlet(value = "/*", loadOnStartup = 1)
public class DispatcherServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	Map<String ,Class> urlMapping=new HashMap<>();
   
    public DispatcherServlet() {
        super();
       System.out.println("DispatcherServlet");
    }
    @Override
    public void init(ServletConfig config) throws ServletException {
    	
    	super.init(config);
    	
//    	方案一:早期凡是有xml配置文件的框架
//    	硬编码的映射关系
//    	读取url与控制器的映射关系
    	urlMapping.put("/mvc/staff", StaffController.class);
    	urlMapping.put("/mvc/dept", DeptController.class);
    	
    	
//    	方案二(反射+注解)
//    	自动,动态的加载映射关系
//    	实现方法:基于反射去扫描特定包(或整个工程)
//    	扫描包中所有的类,找到Controller注解
    	
    	
    	
    }

	
//	处理映射
	private void handlerMapping(HttpServletRequest request, HttpServletResponse response) throws IOException {
//		获得http请求头中的方法
		String method=request.getMethod();
//		请求路径
		String url=request.getRequestURI();
		
//		staff--->StaffController
//		映射
		if(urlMapping.keySet().contains(url)) {
			Class controllerClass=urlMapping.get(url);
			
//		反射调用控制器类默认构造方法实例化
		try {
			Object controller=	controllerClass.getDeclaredConstructor().newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
		
		String msg=String.format("%s:%s\n",method,url);
		System.out.printf(msg);
		
//		响应
		response.setContentType("application/json");
		response.getWriter().write(msg);
		
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		handlerMapping(request ,response);
	}





	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		handlerMapping(request ,response);
	}
	
	@Override
		protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		handlerMapping(req ,resp);
		}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		handlerMapping(req ,resp);
	}
	
}

 


Controller.java

package com.newer.mvc.web.controller;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Controller {

}

DeptController.java

package com.newer.mvc.web.controller;
/**
 * PoJO 简单的java对象:谁都不继承(不认干爹),谁都不实现
 * 
 * 
 * @author Admin
 *
 */

//注解标记了该POJO的特殊身份
@Controller
public class DeptController {

	public DeptController() {
		System.out.println("dept");
	}
}

StaffController.java

package com.newer.mvc.web.controller;
/**
 * PoJO 简单的java对象:谁都不继承(不认干爹),谁都不实现
 * 
 * 
 * @author Admin
 *
 */

@Controller
public class StaffController {

	public StaffController() {
		System.out.println("staff");
	}
}

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MVC</title>
</head>
<body>
	<h1>Spring Web MVC</h1>
</body>
</html>

运行程序:


 关于Spring  MVC中的DispatcherServlet的使用就到这里结束了,有问题的小伙伴欢迎留言!!!

正文到此结束
本文目录