SpringMVC 返回ModelAndView对象

来源:互联网 发布:淘宝宝贝手机端连接 编辑:程序博客网 时间:2024/05/16 17:50

SpringMVC  返回ModelAndView对象

在控制器类中,处理客户端请求后,可以把需要响应到页面的数据和视图名字都封装到一个ModelAndView对象中,然后直接返回这个ModelAndView对象。在控制器类中需要引入的包为: org.springframework.web.servlet.ModelAndView


下面是示例代码:登录案例,登录成功跳转到show页面,失败返回login页面。

1.login.jsp(登录页面)

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><%String path = request.getContextPath();String basepath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><base href="<%=basepath%>" /><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title></title></head><body><h2>login.jsp登录界面</h2><form action="uc/islogin" method="post">用户名:<input type="text" name="loginname" value="lisi"><br />密码:<input type="text" name="loginpwd" value="123"><br /><!-- 登录失败提示的信息 --><c:if test="${msg!=null }">${msg }<br /></c:if><input type="submit" value="登录" /></form></body></html>


2、控制器类 UserController

package cn.sz.hcq.control;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.servlet.ModelAndView;import cn.sz.hcq.pojo.Users;@Controller@RequestMapping("uc")public class UserController {// 处理登录的控制器@RequestMapping(value = "islogin", method = RequestMethod.POST)public ModelAndView checkLogin(Users users) {ModelAndView mav = new ModelAndView();if (users.getLoginname().equals("lisi")&& users.getLoginpwd().equals("123")) {users.setRealname("李四");// 返回的数据mav.addObject("users", users);// 跳转的页面mav.setViewName("show");} else {mav.addObject("msg", "用户名或者密码错误");// 跳转的页面mav.setViewName("login");}return mav;}}


3、登录成功show页面

<%@ 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></title></head><body><h2>show页面</h2>登录成功啦: 用户的真实姓名:${users.realname }</body></html>



原创粉丝点击