您的位置:首页 > 编程语言 > Java开发

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

2017-06-12 13:51 459 查看
一、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);
User currentUser = new User(userName,password);
response.addCookie(cookie);
HttpSession session = request.getSession();
session.setAttribute("currentUser", currentUser);
return "redirect:/main.jsp";
}

}
这里使用了cookie来保存用户信息,这个在记住密码功能中常用。里面设置了cookie的实效为7天。这里使用了session来保存用户信息,方便在各个页面取值。
这个实例中直接演示的是用户登录成功后,保存cookie和session,最后重定向到main.jsp页面。

3.写登录页面login.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="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>
</body>
</html>

这里的两个输入控件的name属性的值可以不与User类中对应的值相同,因为这里使用的是Servlet传值。当使用自动注入值的话,name属性的值必须与User类中对应的属性名相同。当点击提交的时候会跳转到UserController中的login方法中进行cookie保存和session保存,最后重定向到main.jsp页面。
4.写main.jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
Main.jsp ${currentUser.userName }
</body>
</html>

这里在session中取出用户名这个值。
5.运行程序:



点击登录:



这里跳转到了main.jsp页面,并从session中取到了值。

二、SpringMVC对JSON的支持

前边都是普通应用的开发,当前台页面使用EasyUi框架,全部都是使用ajax交互的,数据是json形式传递的。看一下SpringMvc对json的支持:

SpringMvc可以把对象自动转换成JSON格式。

1.修改配置文件为:

<?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"
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">

<!-- 使用注解的包,包括子集 -->
<context:component-scan base-package="com.test"/>

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

<!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp"></property>
</bean>

</beans>这里添加了<mvc:annotation-driven/>配置,并添加了相应的命名空间,这样的话才会支持把对象直接转化成JSON数据。
2.要想使用注解方式的话,还得添加Jackson jar包:



3.UserController层添加测试方法:

@RequestMapping("/ajax")
public @ResponseBody User ajax(){
User user = new User("张三", "123");
return user;
}
这里使用了@ResponseBody注解,这样的话就会自动把user对象
4.修改login.jsp页面,添加一个测试代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="user/ajax.do">测试aj
4000
ax</a>
<form action="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>
</body>
</html>
5.运行程序:



点击测试ajax超链接:



可以看到这里返回了user对象的json数据。

上面使用的返回json数据的代码只是演示用,简单的还是可以使用这种方式的,复杂的比如涉及到json的过滤啥的,使用这个就不好了。实际开发的时候如果底层使用的是hibernate啥的涉及到对象级联,使用这种方式的话就比较难处理。这里要使用最原始的方式:

package com.test.util;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

public class ResponseUtil {

public static void write(HttpServletResponse response,Object o)throws Exception{
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println(o.toString());
out.flush();
out.close();
}
}
后台返回json类型的时候,调用ResponseUtil.write()方法即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息