读取 web.xml 配置

原创
2020/07/02 21:53
阅读数 63
package com.ajaxjs.web;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import java.util.function.Function;

import javax.servlet.FilterConfig;
import javax.servlet.ServletConfig;

import org.junit.Test;

public class TestWebXml {
	/**
	 * 遍历注解的配置,需要什么类,收集起来,放到一个 hash 之中, Servlet 或 Filter 通用
	 * 
	 * @param emu
	 * @param getValue
	 * @return Map
	 */
	public static Map<String, String> emu2map(Enumeration<String> emu, Function<String, String> getValue) {
		Map<String, String> map = new HashMap<>();

		while (emu.hasMoreElements()) {
			String key = emu.nextElement();
			String value = getValue.apply(key);

			map.put(key, value);
		}

		return map;
	}

	/**
	 * 将过滤器的配置转换为 Map
	 * 
	 * @param config 过滤器配置
	 * @return 过滤器配置的 Map 结构
	 */
	public static Map<String, String> initFilterConfig2Map(FilterConfig config) {
		return emu2map(config.getInitParameterNames(), key -> config.getInitParameter(key));
	}

	/**
	 * 将 Servlet 的配置转换为 Map
	 * 
	 * @param config Servlet 配置
	 * @return Servlet 配置的 Map 结构
	 */
	public static Map<String, String> initServletConfig2Map(ServletConfig config) {
		return emu2map(config.getInitParameterNames(), key -> config.getInitParameter(key));
	}

	@Test
	public void testInitFilterConfig2Map() {
		FilterConfig config = mock(FilterConfig.class);
		// 模拟注解
		Vector<String> v = new Vector<>();
		v.addElement("urlPatterns");
		when(config.getInitParameterNames()).thenReturn(v.elements());
		when(config.getInitParameter("urlPatterns")).thenReturn("/service/*");

		Map<String, String> map = initFilterConfig2Map(config);
		assertEquals("/service/*", map.get("urlPatterns"));
	}

	@Test
	public void testInitServletConfig2Map() {
		ServletConfig config = mock(ServletConfig.class);
		// 模拟注解
		Vector<String> v = new Vector<>();
		v.addElement("urlPatterns");
		when(config.getInitParameterNames()).thenReturn(v.elements());
		when(config.getInitParameter("urlPatterns")).thenReturn("/service/*");

		Map<String, String> map = initServletConfig2Map(config);
		assertEquals("/service/*", map.get("urlPatterns"));
	}

	@Test
	public void test() {
		FilterConfig filterConfig = mock(FilterConfig.class);
		String packageName = "com.ajaxjs";

		// 模拟 web.xml
		Vector<String> v = new Vector<>();
		v.addElement("controller");
		when(filterConfig.getInitParameter("controller")).thenReturn(packageName);

		Enumeration<String> e = v.elements();
		when(filterConfig.getInitParameterNames()).thenReturn(e);

		Map<String, String> map = initFilterConfig2Map(filterConfig);
		System.out.println(map);
		assertNotNull(map);
	}
}
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部