Spring MVC使用@RequestParam注解获取参数

创建Hello控制器类

package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class Hello {
	@RequestMapping("/show")
	public String show(@RequestParam("name")String userName) {
		System.out.println(userName);
		return "index";
	}
}

创建index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>




首页


	

Spring MVC

启动Tomcat并访问

Spring MVC使用@RequestParam注解获取参数_第1张图片

注意:如果参数被@RequestParam注解,那么默认情况下该参数不能为空,如果为空则系统会抛出异常。如果希望允许为空,那么要修改它的配置项required为 false。

package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class Hello {
	@RequestMapping("/show")
	public String show(@RequestParam(value="name",required=false)String userName) {
		System.out.println(userName);
		return "index";
	}
}

启动 Tomcat再次访问

Spring MVC使用@RequestParam注解获取参数_第2张图片

你可能感兴趣的:(spring,mvc)