Spring MVC之ModelAndView的使用

创建HelloWorldController

package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.po.User;
@Controller
public class HelloWorldController {
	@RequestMapping("/ModelAndViewTest")
	public ModelAndView ModelAndViewTest(ModelAndView mv) {
		User user=new User();
		user.setUserName("baixue");
		user.setPassWord("123456");
		//将user对象添加到ModelAndView
		mv.addObject("user", user);
		//设置要转发的页面
		mv.setViewName("success");
		return mv;
	}
}

创建User

package com.po;
public class User {
	private String userName;
	private String passWord;
	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;
	}	
}

创建index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>index</title>
</head>
<body>
	<a href="ModelAndViewTest">ModelAndViewTest</a>
</body>
</html>

创建success.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>success</title>
</head>
<body>
	用户名:${user.userName }
	<br>
	密码:${user.passWord }
</body>
</html>

启动Tomcat并访问index.jsp

点击【ModelAndViewTest】

猜你喜欢

转载自blog.csdn.net/dwenxue/article/details/81587034