欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

第三章 Spring MVC Servlet API与Json的支持

程序员文章站 2022-04-07 21:18:05
...
Spring MVC 对 Servlet API 的支持:


	/**
	 * 将当前用户设置到cookie,使用Servlet API
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("----登录验证---");
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		Cookie cookie = new Cookie("user", userName + "-" + password);
		//cookie有效时间
		cookie.setMaxAge(1 * 60 * 60 * 24 * 7);
		User currentUser = new User(userName, password);
		response.addCookie(cookie);
		HttpSession session = request.getSession();
		session.setAttribute("currentUser", currentUser);
		return "redirect:/main.jsp";
	}




Spring MVC 对Json的支持:

1、添加命名空间


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">



2、增加标签


<!-- 支持对象与json的转换。 -->
<mvc:annotation-driven/> 




3、添加jackson jar

jackson-annotations-2.2.1.jar
jackson-core-2.2.1.jar
jackson-core-asl-1.8.8.jar
jackson-databind-2.2.1.jar
jackson-mapper-asl-1.8.8.jar
jackson-module-jaxb-annotations-2.2.1.jar



访问路径:
http://localhost:8080/SpringMvc0201/login.jsp
相关标签: spring mvc