关于SpringMVC获取页面参数的方法,以下示例
jsp页面,点击submi提交请求到后台,后台需要获取页面“用户名”与“密码”输入框中的值
<%@ 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>登陆页</h1>
<form action="SpringMVC/user/login" method="post">
用户名:<input type="text" name="uname"/>
密码:<input type="password" name="pwd">
<input type="submit" value="submit">
</form>
</body>
</html>
方法一.使用HttpServletRequest作为SpringMVC 控制器里面方法的参数,同Servlet中使用Request对象获取页面参数的方法一样
SpringMVC 控制器
package controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
/**
* 使用HttpServletRequest作为SpringMVC 控制器里面方法的参数
* @param request
* @return
*/
@RequestMapping("/login")
public String login(HttpServletRequest request){
String username = request.getParameter("uname");//同Servlet一样,获取页面属性名叫uname的值
String password = request.getParameter("pwd");//同Servlet一样,获取页面属性名叫pwd的值
return "/user/login";
}
}
方法二.通过SpringMVC Annotation注解机制,将前端页面参数传回后台
SpringMVC 控制器
package controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/user")
public class UserController {
/**
* 通过SpringMVC Annotation注解机制
* @RequestParam("uname")String username——获取页面属性名叫"uname"的值,用String类型接收,变量名叫username
* @param request
* @return
*/
@RequestMapping("/login")
public String login(@RequestParam("uname")String username,@RequestParam("pwd")String password){
return "/user/login";
}
}
方法三.使用JavaBean自动装配机制,创建一个User类,将页面参数作为一个User对象传回后台
Model类,属性名需与页面参数名一样
package model;
public class User {
private String uanme;
private String pwd;
public String getUanme() {
return uanme;
}
public void setUanme(String uanme) {
this.uanme = uanme;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import model.User;
@Controller
@RequestMapping("/user")
public class UserController {
/**
* 将页面参数作为一个JavaBean对象传回
* @param user
* @return
*/
@RequestMapping("/login")
public String login(User user){
return "/user/login";
}
}