SpringMVC前后端参数传递与接收

SpringMVC前后端参数传递与接收

前端JSP使用了JSTL语言与OGNL表单式,需要对其有一定的了解

(1)默认支持参数类型

使用下面的类进行接收,接收参数方法同Servlet中接收参数方法一致

HttpServletRequest request
HttpServletResponse response,
HttpSession session
//前端请求的url地址
@RequestMapping(value = "/parm/parm1.action")
    public ModelAndView parmTransport(HttpServletRequest request,
                                      HttpServletResponse response,
                                      HttpSession session){
        String name = request.getParameter("name");
        System.out.println(name);
        return null;
    }

(2)绑定简单类型

即前端传入的参数名与后端接收参数的方法名中的形参的name一致,可以直接接收参数

后端代码,前端使用input标签传参,确保input标签的name与后台接收参数的name一致

支持的类型如下:

整型:Integer、int

字符串:String

单精度:Float、float

双精度:Double、double

布尔类型:Boolean,Boolean

    
  @RequestMapping(value = "/parm/parm2.action")
    public ModelAndView parmTransport2(String name ){
        System.out.println(name);
        return null;
   }

(2)绑定简单类型---传入参数名与接收参数名不一致

即前端传入的参数名称与后端接收参数名称不一致,使用下面的注解可以实现数据匹配

@RequestParam

value属性表示前端传入的值,required表示是否为空,defaultValue 属性表示默认值

 //参数名不一致时
    @RequestMapping(value = "/parm/parm3.action")
    public ModelAndView parmTransport3(@RequestParam(value = "name2",required = true) String name ){
        System.out.println(name+);
        return null;
    }

(3)绑定POJO---实体类,解决多参数问题,且pojo可以嵌套,通过OGNL表达式赋值

后端代码

//绑定pojo类型,pojo包装pojo
    @RequestMapping(value = "/product/toEdit.action")
    public ModelAndView toEdit(Integer id){
        Product productById = productService.getProductById(id);  //根据id查找product实体
        ModelAndView modelAndView = new ModelAndView();
        Order order = new Order();                                //新建一个order实体,并赋值
        order.setId(55);
        productById.setOrder(order);                         //为product实体中的order实体赋值
        //item保持一致,与前端页面
        modelAndView.addObject("item",productById);
        modelAndView.setViewName("/static/editProduct.jsp");       //返回前端显示
        return modelAndView;
    }

前端代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<!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>修改商品信息</title>

</head>
<body> 
	
	<form id="itemForm"	action="${pageContext.request.contextPath }/product/updateProduct.action" method="post">
		<input type="hidden" name="id" value="${item.id}" /> 修改商品信息:
		<table width="100%" border=1>
			<tr>
				<td>商品名称</td>
				<td><input type="text" name="name" value="${item.name }" /></td>
			</tr>
			<tr>
				<td>商品价格</td>
				<td><input type="text" name="price" value="${item.price }" /></td>
			</tr>
			
			<tr>
				<td>商品生产日期</td>
				<td><input type="text" name="createTime"
					value="<fmt:formatDate value="${item.createTime}" pattern="yyyy-MM-dd HH:mm:ss"/>" /></td>
			</tr>

			<tr>
				<td>商品简介</td>
				<td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea>
				</td>
			</tr>

			<tr>
				<td>商品简介</td>
				<td><textarea rows="3" cols="30" name="order.id">${item.order.id}</textarea>
				</td>
			</tr>
			<tr>
				<td colspan="2" align="center"><input type="submit" value="提交" />
				</td>
			</tr>
		</table>

	</form>
</body>

</html>

(4)解决前端传入参数中文乱码问题-----WEB-ING下的web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--配置SpringMvc-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    </servlet>
       <servlet-mapping>
           <servlet-name>springmvc</servlet-name>
           <url-pattern>*.action</url-pattern>
       </servlet-mapping>

    <!--配置Spring容器创建-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!--解决乱码问题-->
    <filter>
        <filter-name>endocdingFilter</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>
    </filter>
    <filter-mapping>
        <filter-name>endocdingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

(5)自定义参数绑定-----日期格式转换

1:自定义converter转换器

package com.hxy.converter;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.core.convert.converter.Converter;


import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConverter implements Converter<String ,Date> {
    @Override
    public Date convert(String str) {
        Date date = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
        try {
            date = simpleDateFormat.parse( str );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }

}

2:SpringMVC.xml配置文件中配置转换器

  <!--配置转换器-->
    <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

    <bean name="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean name="converter" class="com.hxy.converter.DateConverter"></bean>
            </list>
        </property>
    </bean>

高级参数绑定

(1)绑定数组----前端批量传入数据到后台

前端代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
		 pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<!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>查询商品列表</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/product/bothDelete1.action" method="post">
	商品列表:
	<table width="100%" border=1>
		<tr>
			<td>选择</td>
			<td>商品名称</td>
			<td>商品价格</td>
			<td>生产日期</td>
			<td>商品描述</td>
			<td>操作</td>
		</tr>
		<c:forEach items="${productList }" var="item">
			<tr>
				<td><input type="checkbox" name="ids" value="${item.id }"></td>
				<td>${item.name }</td>
				<td>${item.price }</td>
				<td><fmt:formatDate value="${item.createTime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
				<td>${item.detail }</td>
				<td><a href="${pageContext.request.contextPath }/product/toEdit1.action?id=${item.id}">修改</a></td>

			</tr>
		</c:forEach>
		<tr>
			<td colspan="6"><input type="submit" value="批量删除"></td>
		</tr>

	</table>
</form>
</body>

</html>

后端代码:

 //获取前端传入的数组对象
    @RequestMapping(value = "/product/bothDelete.action")
    public ModelAndView bothDelete(Integer[] ids){
        for (Integer i :ids){
            System.out.println(i);
        }
        //模拟假数据测试
        List<Product> list = new ArrayList<Product>();
        list= productService.getProductList();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("productList",list);
        modelAndView.setViewName("/static/productList1.jsp");
        return modelAndView;
    }

用上述方法可以实现表单批量传入数据到后台

(2)绑定POJO的数组,List,一次传入多个对象

前端如何一次传递多个对象到后端,并且是以行传,即数据不能出现混乱

下面使用的方法就是使用自定义类,QueryVo,该类中有一个属性

是List<Product> productList

前端传入数据时使用{productList[i].属性}的方法来整体传入一个对象的参数

注意,前后端的productList要确保一致

同样,使用该方法也可以为数组赋值,即对象中包含数组

前端代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
		 pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<!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>查询商品列表</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/product/bothUpdate.action" method="post">
	商品列表:
	<table width="100%" border=1>
		<tr>
			<td>选择</td>
			<td>商品名称</td>
			<td>商品价格</td>
			<td>生产日期</td>
			<td>商品描述</td>
			<td>操作</td>
		</tr>
                //varStatus可以定义一个参数,并使用该参数的index属性,可以获取到foreach循环的次数
		<c:forEach items="${productList}" var="item" varStatus="s">
			<tr>
				<td><input type="checkbox" name="ids" value="${item.id }">
					<input type="hidden" name="productList[${s.index}].id" value="${item.id }">
				</td>
				<td><input type="text" name="productList[${s.index}].name" value="${item.name }"/></td>
				<td><input type="text" name="productList[${s.index}].price" value="${item.price}"/></td>
				<td><fmt:formatDate value="${item.createTime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
				<td>${item.detail }</td>
				<td><a href="${pageContext.request.contextPath }/product/toEdit1.action?id=${item.id}">修改</a></td>

			</tr>
		</c:forEach>
		<tr>
			<td colspan="6"><input type="submit" value="批量更新"></td>
		</tr>

	</table>
</form>
</body>

</html>

后端代码

//批量传入对象
    @RequestMapping(value = "/product/bothUpdate.action",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView bothupdate(QueryVo queryVo){
        for (Product i :queryVo.getProductList()){
            System.out.println(i);
        }
        //模拟假数据测试
        List<Product> list = new ArrayList<Product>();
        list= productService.getProductList();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("productList",list);
        modelAndView.setViewName("/static/productList2.jsp");
        return modelAndView;
    }

注解方法@RequestMapping

1:通过@RequestMapping注解可以定义不同处理器映射器

2:URL路径映射,一个方法可对应多个url

  @RequestMapping(value = {"/product/productList2.action","/productList2.action"})

3:@RequestMapping添加在类上面,访问时必须要加上类上的url地址


@Controller
@RequestMapping("/product/")
public class ProductController1 {
    @Autowired
    private ProductService productService;

    @RequestMapping(value = "productList1.action")
    public ModelAndView itemList(){
        List<Product> list = new ArrayList<Product>();
        list= productService.getProductList();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("productList",list);
        modelAndView.setViewName("/static/productList1.jsp");
        return modelAndView;
    }}

4:请求方法限定

@RequestMapping除了限制URL之外,还可以限定请求进来的方法

限定POST和Get都可以,如果没有根据指定请求方法,页面报405错误

@RequestMapping(value = "/product/bothUpdate.action",method = {RequestMethod.GET,RequestMethod.POST})

Struts2和SpringMvc的区别

(1)SpringMVC的入门是一个servlet即前端控制器而Struts2的入口是filter过滤器

(2)SpringMVC是基于方法开发(一个URL地址对应一个方法)

         请求的参数传递到方法的形参,可以设计为单例或者多例(建议单例)

         Struts2是基于类开发,传递的参数 是通过类的属性进行赋值的,只能设计为多例。

(3)Struts2采用 值栈 存储请求和响应的数据,通过OGNL存取数据;

         SpringMVC通过参数解析器将request请求内容解析,并给方法赋值

         请求数据和视图封装成ModeAndView对象

         最后又将ModeAndView中数据模型通过request域传输到页面上

         JSP视图解析器默认使用JSTL。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无名一小卒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值