可以使用Model,Map,ModelMap,ModelAndView,四种方式都可以,一般使用Model,且数据保存在request域中,若想保存在session中,[email protected]
package com.song.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;
/**
* 向页面回显数据
*
* Map
* ModelMap
* Model
* ModelAndView
* 四种方式都可以,一般就用Model了
* 回显之后,数据保存在哪个作用域中? 放在request域中
*
* [email protected],里面写上需要的attributeName,就可以将该值放在session域中
* 其中,types和value都写上表示session中可以存储名字为value值的参数,以及类型为Integer的参数(慎用types,很容易把很多不必要的数据放入session)
*
* @author Song X.
* @date 2020/03/15
*/
@Controller
@SessionAttributes(value = "message", types = Integer.class)
public class OutputController {
@RequestMapping("/output1")
public String output(Map<String, String> map){
map.put("msg", "hello");
return "success";
}
@RequestMapping("/output2")
public String output2(Model model){
model.addAttribute("msg", "hello");
return "success";
}
@RequestMapping("/output3")
public String output3(ModelMap modelMap){
modelMap.addAttribute("msg", "hello");
return "success";
}
@RequestMapping("/output4")
public ModelAndView output4(){
ModelAndView mv = new ModelAndView();
mv.setViewName("success");
mv.addObject("msg", "hello");
return mv;
}
@RequestMapping("/output5")
public String outputInSession(Model model){
model.addAttribute("message", "hello");
return "success";
}
}
转发和重定向在servlet时比较麻烦,现在很简单,简单到都不用写注解
package com.song.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;
/**
* @author Song X.
* @date 2020/03/15
*/
@Controller
public class OutputController {
@RequestMapping("/forward1")
public String forward1(){
System.out.println(1);
return "forward:/success.jsp";
}
@RequestMapping("/forward2")
public String forward2(){
System.out.println(2);
return "forward:forward1";
}
@RequestMapping("/redirect1")
public String redirect(){
System.out.println("redirect");
return "redirect:/success.jsp";
}
@RequestMapping("/redirect2")
public String redirect2(){
System.out.println("redirect2");
return "redirect:/redirect1";
}
}
需要注意的是这里的success页面与web目录同级,也就是与index.jsp页面同级
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/20574.html