Discuss / Java / index方法的疑惑,是因为路径根目录“/”的原因吗

index方法的疑惑,是因为路径根目录“/”的原因吗

Topic source

Best of Me

#1 Created at ... [Delete] [Delete and Lock User]

不太理解控制器首页index方法,为什么要创建实例HashMap<>再传入参数,其他方法可以直接用Map.of方法


	@GetMapping("/")

	public ModelAndView index(HttpSession session) {

		User user = (User) session.getAttribute(KEY_USER);

		Map<String, Object> model = new HashMap<>();

		if (user != null) {

			model.put("user", user);

		}

		return new ModelAndView("index.html", model);

//		return new ModelAndView("index.html", Map.of("user",user));//这样会报错java.lang.NullPointerException
	}

wbid_hasky

#2 Created at ... [Delete] [Delete and Lock User]

Map.of()方法的定义:

/**
 * Returns an unmodifiable map containing a single mapping. See Unmodifiable Maps for details.
 * Params: k1 – the mapping's key
           v1 – the mapping's value
 * Returns: a Map containing the specified mapping
 * Throws: NullPointerException – if the key or the value is null
 * Since: 9
 */
static <K, V> Map<K, V> of(K k1, V v1) {
    return new ImmutableCollections.Map1<>(k1, v1);
}

  • 1

Reply