J2EE系列之SpringMVC学习笔记(四)--SpringMVC控制器

本文介绍了SpringMVC如何集成ServletAPI实现用户登录并保存cookie与session,以及SpringMVC对JSON的支持。通过一个登录实例展示了使用ServletAPI处理cookie和session的过程,同时讲解了SpringMvc如何将对象自动转换为JSON格式,包括配置修改、Jackson库的引入以及在UserController中的测试方法。此外,文章还讨论了在复杂场景下使用原生方式处理JSON的必要性。
摘要由CSDN通过智能技术生成

一、SpringMVC对ServletAPI的支持

之前的博客中使用到的都是使用SpringMVC转发对象和视图,没有用到ServletAPI。但是当工程中需要保存cookie的时候,就必须要使用ServletAPI了。下面讲一个登录实例。

1.在上一篇博客工程示例的基础上,新建类:

package com.test.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;
	}
	
	
}

2.新建控制层:UserController:

package com.test.controller;

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.test.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.setMaxAge(1*60*60*24*7)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值