SpringMvc对 Servlet API的支持

用SpringMVC是一个很强大的框架,官网上给的工作原理图如下:
SpringMvc对 Servlet API的支持_第1张图片

mvc有很多深入的技术,这里我们来聊一下SpringMvc对servlet API的支持
来实现登录页面,浏览器缓存Cookie
1,控制层:

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.java1234.model.User;

@Controller
@RequestMapping("/user")
public class UserController {

	@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);
		//调用addCookie
		response.addCookie(cookie);
		HttpSession session=request.getSession();
		session.setAttribute("currentUser", currentUser);
		//登录完重定向
		return "redirect:/main.jsp";
	}
	
}

2,实体层:

package com.java1234.model;
public class User {

	private int id;
	private String userName;
	private String password;


	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	public User(String userName, String password) {
		super();
		this.userName = userName;
		this.password = password;
	}

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

}

3,前端页面:
login.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>




Insert title here


测试ajax
用户名:
密码:

main.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>




Insert title here


Main.jsp  ${currentUser.userName }


最终实现:
这里写图片描述
对应的cookie
这里写图片描述

你可能感兴趣的:(java框架)