Spring MVC学习笔记——给Controller传值
Posted tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring MVC学习笔记——给Controller传值相关的知识,希望对你有一定的参考价值。
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>
以上是关于Spring MVC学习笔记——给Controller传值的主要内容,如果未能解决你的问题,请参考以下文章
mybatis学习笔记一mybatis结合spring mvc配置
企业级信息系统开发学习笔记1.7 基于XML配置方式使用Spring MVC
Spring MVC 学习笔记 --- [SpringMVC的文件上传与拦截器,以及更新登录用户头像的简易案例]