SpringMVC对ServletAPI的支持和JSON格式的转换
Posted wo卜配
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringMVC对ServletAPI的支持和JSON格式的转换相关的知识,希望对你有一定的参考价值。
package com.hongcong.controller; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; 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.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.hongcong.model.UserModel; @Controller @RequestMapping("/user") public class LoginController { @RequestMapping("/list") public ModelAndView list(){ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("/login/list"); return modelAndView; } @RequestMapping("/login")
//方法的参数可以直接获取HttpServletRequest和HttpServletResponse public String login(HttpServletRequest request,HttpServletResponse response)throws Exception{ String userName = request.getParameter("userName"); String passWord = request.getParameter("passWord"); //cookie中放入中文时需要进行特殊处理 String cookieStr = userName + "-" + passWord; String encode = URLEncoder.encode(cookieStr, "UTF-8"); Cookie cookie = new Cookie("user",encode); cookie.setMaxAge(60*30); response.addCookie(cookie); HttpSession session = request.getSession(); session.setAttribute("userModel", new UserModel(userName,passWord)); return "redirect:/user/list.do"; } @RequestMapping("/Ajax")
//实体类转换为json格式的注解,springMVC.xml需要配置 @ResponseBody public List<UserModel> JsonTest(){ List<UserModel> list = new ArrayList<UserModel>(); list.add(new UserModel("小夏","1234")); list.add(new UserModel("小红","111111")); return list; } }
以上是关于SpringMVC对ServletAPI的支持和JSON格式的转换的主要内容,如果未能解决你的问题,请参考以下文章