Springmvc passes values to the page, view parser configuration, springmvc jump method

1. Passing values ​​to the page
How to bind parameters in response to jumps
First: Native way

	@RequestMapping("/form5")
public void form5(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException{
	req.setAttribute("message5", "tom");
	req.getRequestDispatcher("/jsp/model2.jsp").forward(req, resp);
}
第二种:ModelAndView方式
//使用ModelAndView对象
@RequestMapping("/form6")
public ModelAndView form6(){
	ModelAndView mv = new ModelAndView();
	mv.addObject("message6", "jack");
	mv.setViewName("/jsp/model2.jsp");
	return mv;
}
第三种:使用Model对象
	//使用Model对象 -- 【掌握】
@RequestMapping("/form7")
public String form7(Model model){
	model.addAttribute("message7", "james");
	return "/jsp/model2.jsp";
}
注意:
	在SpringMvc中默认跳转方式是转发:默认转发 ,因为1.可以共享request中的数据   2.可以转发到WEB-INF  3.效率要高一些
	这三种方式,数据默认都是绑定在request中

Second, the view parser In
actual projects, the returned data is usually handed over to the view parser for processing.
After the view parser is configured to parse the view and data, no matter what value is returned, it will automatically go through the view parser by default. The
configuration is as follows:

<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<!-- 前缀prefix:会自动在返回值前面加个上/ -->
	<property name="prefix" value="/"></property>
	<!-- 前缀suffix:会自动在返回值后面加个上.jsp -->
	<property name="suffix" value=".jsp"></property>
</bean>

3. Jump method
Difference:
Forward: one request, you can share the data of the request, the address bar will not change, you can not go to an external application
Redirect: more than this request, you can not share the data of the request, the address bar will change, you can
Forwarding and redirection in SpringMvc directed to external applications :
Forwarding:

  1. Default forwarding: will pass through the view resolver
@RequestMapping("form6")
		//默认转发,会经过视图解析器。
		public ModelAndView getResp5(){
			ModelAndView m=new ModelAndView();
			m.addObject("message6", "ModelAndView");
			m.setViewName("jsp/model2");
			return m;
		}
2.显示转发:forward:xxx
			不会经过视图解析器,一般不用。
@RequestMapping("form6")
		//显示转发forward,不会经过视图解析器。一般不会使用
		public ModelAndView getResp3(){
			ModelAndView m=new ModelAndView();
			m.addObject("message6", "ModelAndView");
			m.setViewName("forward:/jsp/model2.jsp");
			return m;
		}
	重定向:redirect:xxx
		不会经过视图解析器
@RequestMapping("form6")
		//redirect,不会经过视图解析器。
		public ModelAndView getResp4(){
			ModelAndView m=new ModelAndView();
			m.addObject("message6", "ModelAndView");
			m.setViewName("redirect:/jsp/model2.jsp");
			return m;
		}
Published 23 original articles · Like1 · Visits 170

Guess you like

Origin blog.csdn.net/weixin_45528650/article/details/105446584