springMVC--(講解3)數據處理

#1.傳入數據單個值(方式1)
沒有使用視圖解析器
controller代碼以下html

@RequestMapping(value="/hello",method= RequestMethod.GET)
	public String hello(String name) throws IOException, ServletException{
		System.out.println(name);
		return "index.jsp";
	}

請求代碼app

http://localhost:8080/ssm/hello?name=zhangsan

注意:請求的參數名(name)必須和接收參數(String name)對齊,不然接收不到。
#2.傳入數據單個值(方式2)
使用@RequestParam接收參數。
請求代碼同上
接收代碼改成以下jsp

@RequestMapping(value="/hello",method= RequestMethod.GET)
	public String hello(@RequestParam("name")String userName) throws IOException, ServletException{
		System.out.println(userName);
		return "index.jsp";
	}

#3.傳對象code

@RequestMapping(value="/hello",method= RequestMethod.GET)
	public String hello(User user) throws IOException, ServletException{
		System.out.println(user);
		return "index.jsp";
	}

User類以下htm

public class User implements Serializable{

	private static final long serialVersionUID = 1L;

	private Integer id;

        private String name;
}

傳參以下對象

http://localhost:8080/ssm/hello?name=zhangsan&id=1001

#4.數據展現到前臺(方式1:ModAndView)
使用視圖解析器io

@RequestMapping(value="/hello",method= RequestMethod.GET)
	public ModelAndView hello(User user) throws IOException, ServletException{
		
		ModelAndView mav = new ModelAndView();
		mav.addObject("user", user);
		mav.setViewName("hello");
		return mav;
	}

請求數據class

http://localhost:8080/ssm/hello?name=zhangsan&id=1001

hello.jsp請求

<html>
<body>
<h2>Hello World!</h2>
userId:${user.id}<br>
userName:${user.name}
</body>
</html>

結果im

Hello World!
userId:1001
userName:zhangsan

#5.數據展現到前臺(方式2:ModleMap)
不須要使用視圖解析器

@RequestMapping(value="/hello",method= RequestMethod.GET)
	public String hello(User user,ModelMap modlMap) throws IOException, ServletException{
		modlMap.addAttribute("user", user);
		return "index.jsp";
	}

請求數據

http://localhost:8080/ssm/hello?name=zhangsan&id=1001

index.jsp

<html>
<body>
<h2>Hello World!</h2>
userId:---  ${user.id}<br>
userName:---  ${user.name}
</body>
</html>

結果

Hello World!
userId:--- 1001
userName:--- zhangsan

ModelAndView與ModelMap的區別 1.前者須要視圖解析器,然後者不須要 。 2.前者能夠設值且指定跳轉的頁面,然後者只能設值。

相關文章
相關標籤/搜索