Spring MVC之ModelAndView分析

前台表单

<form class="form-horizontal" role="form" action="user/login" method="post">
账号:<input type="text" class="form-control" name="username" id="username">
密码:<input type="password" class="form-control" name="userpwd" id="userpwd">
<button type="submit" class="btn btn-default"> 登录</button>
</form>

controller

package com.music.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.music.model.User;
import com.music.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private User user;
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
   public ModelAndView login(String username,String userpwd,ModelAndView modelAndView) {
    Map<String,Object> map=new HashMap<>();
    map.put("username", username);
    map.put("userpwd", userpwd);
    User user=userService.selectByNameAndUserpwd(map);
    
    if (user!=null) {
        modelAndView.setViewName("success");字符串方式//视图在web-inf下面为success.jsp文件
        modelAndView.addAllObjects(map);
        return modelAndView ;
    }
    return modelAndView;
}
}
modelAndView.setViewName("/user/success");路径方式//视图在web-inf下的user文件夹下的success.jsp文件

 

 

mv.setViewName("redirect:/user/success.jsp");重定向方式//视图在web-inf下的user文件夹下的success.jsp

 

以上三种modelAndView.setViewName,都可以返回视图

如果想用ModelAndView返回,就public ModelAndView login(){}这样写方法

modelAndView.setViewName(“success”);跟return “success”一样,由视图解析跳转到你配置的页面,一般是   /success.jsp  这个页面

第二种

controller中的写法

package com.music.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.music.model.User;
import com.music.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private User user;
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
   public String login(String username,String userpwd) {
    Map<String,Object> map=new HashMap<>();
    map.put("username", username);
    map.put("userpwd", userpwd);
    User user=userService.selectByNameAndUserpwd(map);
    ModelAndView mv =new ModelAndView();
    if (user!=null) {
        mv.setViewName("success");
        return mv.getViewName() ;
    }
    return mv.getViewName();
}
}

这是返回的不是ModelAndView型的,但是可以把ModelAndView   new出来,直接使用。

 

主要针对新手上手代码。

    原文作者:Spring MVC
    原文地址: https://blog.csdn.net/mint6/article/details/77345631
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞