SpringMVC接受页面参数和传参到jsp的几种方法

来源:互联网 发布:淘宝 手机 描述 模板 编辑:程序博客网 时间:2024/05/24 06:49

一:spring mvc获取请求参数的几种方法

1.通过@Pathvariable的方法获取参数

package com.oracle.springmvc.control;import javax.servlet.http.HttpServletRequest;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;public class ParamsController {/**Spring向后台Controller传值的四种方法*//**1.使用HttpServletRequest获取*/@RequestMapping(value="/login")public String GetParam1(HttpServletRequest request){String username=request.getParameter("username");String password=request.getParameter("password");System.out.println(username+password);return "index";}/**2.使用@RequestParam获取页面参数*/@RequestMapping(value="/login",method=RequestMethod.POST)private String addUser(@RequestParam("username") String username,@RequestParam("password") String password){System.out.println("----------------username:"+username+"\t password:"+password);return "login";}/**3.占位符的形式在url传值,@PathVariable获取参数*/@RequestMapping(value="/login/{userid}")public String getUser(@PathVariable("userid") String userid){System.out.println("请求的userid为:"+userid);return "login";}/**4.自动注入bean的映射,但是这种需要新建一个bean类 *  * @RequestMapping("/login.do") public String login(User user) {   syso(user.getName());   syso(user.getPass());   *//**5.model对象获取*/@RequestMapping(value={"/index","/login"},method=RequestMethod.POST)public String login(@RequestParam("username") String username,@RequestParam("password") String password,Model model){if(username.equals("dabaojian")||(password.equals("123456"))){System.out.println("login success!");/**model对象向前台传参数的bean;前台jsp取值就直接${username}*/model.addAttribute("username", username);model.addAttribute("password", password);return "index";}else{System.out.println("login fail");return "login";}}}


jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><base href="<%=basePath%>"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body>欢迎登陆!<!-- action里面直接对应的就是在UserController里面的url的value值 --><form action="login" method="post"><input type="text" name="username" value="dabaojian"/><input type="password" name="password" value="123456"/><input type="submit" value="点击登录"/></form></body></html>