标签:pos password schema pre text list cookie bin direct
本篇两个知识点
1.SpringMVC对ServletAPI的支持
2.SpingMVC对JSON的支持
示例(用户登录,存放cookie与session)
<body> <a href="${pageContext.request.contextPath }/user/ajax.do">测试ajax</a>
<form action="${pageContext.request.contextPath }/user/login.do" method="post"> <table> <tr> <td>用户名:</td> <td><input type="text" name="userName"/></td> </tr> <tr> <td>密码:</td> <td><input type="password" name="password"/></td> </tr> <tr> <td> <input type="submit" value="登录"/> </td> </tr> </table> </form>
package com.maya.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.maya.model.User; @Controller @RequestMapping("/user") public class UserController { @RequestMapping("/login")//SpringMVC对servletAPI的支持 public String login(HttpServletRequest request,HttpServletResponse response,User user){//user,SpringMVC的自动封装,在上一篇中已经讲过 Cookie c=new Cookie("user",user.getUserName()+"---"+user.getPassword()); c.setMaxAge(1*60);//设置cookie有效时长 HttpSession session=request.getSession();//获取session session.setAttribute("user", user); return "redirect:/student/list.do"; } @RequestMapping("/ajax")//SpringMVC对JSON的支持 public @ResponseBody User ajax(){ // @ResponseBody 这个注解的作用是将User自动转换成JSON对象 // @ResponseBody了解就可以了,通常开发时还是要用JSON.jar进行格式的转化 User user=new User("zhangsan","123"); return user;
} }
spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <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" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd"> <!-- 使用注解的包,包括子集 --> <context:component-scan base-package="com.maya"/> <!-- 注解驱动!,有了它才能用JSON的注解 --><!-- 相应的要引入mvc的命名空间 --> <mvc:annotation-driven/> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/" /><!-- 返回视图到这个目录下 --> <property name="suffix" value=".jsp"></property> </bean> </beans>
SpringMVC 控制器之对ServletAPI的支持与对JSON的支持
标签:pos password schema pre text list cookie bin direct
原文地址:http://www.cnblogs.com/AnswerTheQuestion/p/6686807.html