springmvc中接收页面参数传递的几种方式
程序员文章站
2022-07-15 11:11:38
...
基于maven,web项目:
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>springmvc-param</display-name>
<!-- 配置编码过滤器 -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name><!--前端控制器 -->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc.xml</param-value><!--在resource文件夹下 -->
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
mvc.xml
在src/main/resources目录下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<!-- IoC解析器 用于生成实体类,实例化对象,依赖对象,让我们专注于实现,而不是设计。
控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),
还有一种方式叫“依赖查找”(Dependency Lookup)。通过控制反转,对象在被创建的时候,由一个调控系统内所有对象的外界实体将其所依赖的对象的引用传递给它。也可以说,依赖被注入到对象中。 -->
<context:component-scan base-package="com.web" />
<!-- MVC解析器 -->
<mvc:annotation-driven />
<!-- 配置静态资源 -->
<!-- <mvc:default-servlet-handler/> -->
<mvc:resources location="/WEB-INF/css/" mapping="/**" /><!--/**用多层目录结构 -->
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
ParameterController.java
package com.web.controller;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.bean.ParamBean;
import com.bean.User;
@Controller
public class ParameterController {
@Autowired
private ServletContext servletContext;//全局变量
//Servlet API
@GetMapping("/test1")
public String test1(HttpServletRequest request,
HttpServletResponse response,
HttpSession session) {
String name = request.getParameter("name");//前端页面的参数 name
System.out.println(name);//浏览器访问网址: http://localhost:8888/springmvc-param/test1?name=zhangz& ?后面代表参数。&表示多个参数
request.setAttribute("name", name);
session.setAttribute("sessionName", name);
servletContext.setAttribute("appName", name);
return "result";//返回到/WEB-INF/views/result.jsp文件下,result代表文件名
}
/**
* 获取简单参数
* 注意:在开发中,参数列表中尽量不要使用基本数据类型,而是
* 使用包装类,防止null错误发生
* 传的参数的名称必须和参数列表中的名称一致,否则就获取不到值
*
* 如果想要实现参数的名称和方法参数列表中的名称不一致但又能接收到数据,
* 需要使用@RequestParam注解来实现
*
* @RequestParam注解的属性说明:
* 1、value/name:指定获取请求参数的名称
* 2、required:指定该参数是否为必须传的参数,默认为true
* 3、defaultValue:指定该参数没有传时的默认值是多少,只在required=false时有效
*/
@GetMapping("/test2")
public ModelAndView test2(@RequestParam(value="sname", required=false, defaultValue="lisi") String name, Integer age) {
System.out.println("name=" + name);
System.out.println("age=" + age);
return null;
}
/**
* 获取数组数据
* /test3?ids=1&ids=2&ids=3 /test3?ids=1,2,3
*/
@GetMapping("/test3")
public ModelAndView test3(int[] ids) {
System.out.println("ids=" + Arrays.toString(ids));
return null;
}
/**
* 获取List集合数据
* /test4?ids[0]=1&ids[1]=2&ids[2]=3
* /test3?ids=1&ids=2&ids=3 需用这种方法接收
*/
@GetMapping("/test4")
public ModelAndView test4(List<Integer> ids) { // 此种方式不能获取,要用获取对象的方式获取,对象里的参数是集合
//public ModelAndView test4(ParamBean pb) {
System.out.println("---------");
System.out.println(ids);
return null;
}
// 以对象的方式接收参数
@GetMapping("/test5")
public ModelAndView test5(User user) {
System.out.println("---------");
System.out.println("name=" + user.getName());
System.out.println("age=" + user.getAge());
return null;
}
// 接收RESTfull风格的参数
// test6?name=xx&age=yyy
// RESTfull test6/xx/yyy
@GetMapping("/test6/{name}/{age}")// 网址: http://localhost:8888/springmvc-param/test6/a/33
public ModelAndView test6(@PathVariable("name") String n, @PathVariable("age")int a) {
System.out.println("---------");
System.out.println("name=" + n);
System.out.println("age=" + a);
return null;
}
}
User.java
package com.bean;
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
ParamBean.java
package com.bean;
import java.util.ArrayList;
import java.util.List;
public class ParamBean {
private List<Integer> ids = new ArrayList<Integer>();
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
}
前端页面
result.jsp,在WEB-INF/views/下
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index</title>
<link rel="stylesheet" href="<%=request.getContextPath() %>/index.css" />
</head>
<body>
<span class="font">
request: ${requestScope.name}<br/>
session: ${sessionScope.sessionName}<br/>
${appName}<br/>
<%=request.getContextPath() %><!-- /springmvc-param --><br />
<%-- ${pageContext.request.contextPath} --%>
</span>
</body>
</html>
前端样式:
index.css 在WEB-INF/css/目录下
.font{
color : red;
font-size: 12px;
}
spring中注解方式:
@Controller 用在web层
@Service 用在service层
@Repository 用在dao层
@component 用在除了以上几层之外的类