标签:
1.修改HelloController.java
//RequestMapping表示用哪一个url来对应 @RequestMapping({"/hello","/"}) public String hello(@RequestParam("username") String username){ System.out.println("hello"); System.out.println(username); return "hello"; }
然后在浏览器中输入请求
http://localhost:8080/springmvc_hello/hello?username=abc
控制台可以看到传的值
但是使用了RequestParam,如果在请求中不传值的话,会报400错误,因为默认把参数作为了地址的一部分
2.第二种,把RequestParam删除
//RequestMapping表示用哪一个url来对应 @RequestMapping({"/hello","/"}) public String hello(String username){ System.out.println("hello"); System.out.println(username); return "hello"; }
这种可以不传值,不传值时候为null
把值传给视图
1.用Map来传值
HelloController.java文件
package org.common.controller; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { //RequestMapping表示用哪一个url来对应 @RequestMapping({"/hello","/"}) public String hello(String username,Map<String,Object> context){ System.out.println("hello"); context.put("username", username); System.out.println(username); return "hello"; } @RequestMapping("/welcome") public String welcome(){ System.out.println("welcome"); return "welcome"; } }
hello.jsp文件
<%@ 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>Insert title here</title> </head> <body> <h1>hello!! ${username}!!</h1> </body> </html>
2.用Model来传值
HelloController.java文件
package org.common.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { //RequestMapping表示用哪一个url来对应 @RequestMapping({"/hello","/"}) public String hello(String username,Model model){ System.out.println("hello"); model.addAttribute("username", username); //等于model.addAttribute("String",username); model.addAttribute(username); //model.addAttribute(new User());-->model.addAttribute("user",new User()); System.out.println(username); return "hello"; } @RequestMapping("/welcome") public String welcome(){ System.out.println("welcome"); return "welcome"; } }
hello.jsp
<%@ 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>Insert title here</title> </head> <body> <h1>hello!! ${username}!!</h1> ${string} </body> </html>
标签:
原文地址:http://www.cnblogs.com/tonglin0325/p/5515494.html