SpringMVC类型转换

SpringMVC框架不仅提供了强大的类型转换和格式化机制,而且开发者还可以方便的开发出自己的类型转换器和格式化转换器,完成字符串和各种数据类型之间的转换。
String,double,int 都可以转String
以下代码为开发者需要自己在servlet中尽心各类型转换,并对其封装成值对象。

input.jsp

input.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<base href="<%=basePath%>">
</head>
<body>
 <form action="input" method="post">
     商品名称:<input type="text" name="goodsname"/><br>
     商品价格:<input type="text" name="goodsprice"/><br>
     商品数量:<input type="text" name="goodsnumber"/><br>
     <input type="submit" value="提交"/>
    </form>
</body>
</html>

showgoods.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>
    您创建的商品信息如下:<br>
  <!-- 使用EL表达式取出model中goods的信息 -->
    商品名为:${goods.goodsname }, 
    商品价格为:${goods.goodsprice },
    商品数量为:${goods.goodsnumber }。
</body>
</html>

控制类
GoodsCongtroller

@Controller
public class GoodsController {
 @RequestMapping("/input")
 public String add(GoodsModel gm,Model model) {
  double total = gm.getGoodsprice()*gm.getGoodsnumber();
  System.out.println(total);
  
  model.addAttribute("goods",gm);
return "showGoods";  
 }
}

页面收集到的数据提交到addGoods的Servlet(AddGoodsServlet类),该Servlet将这些请求信息封装成一个Goods类的值对象

public class GoodsModel {
 private String goodsname;
 private double goodsprice;
 private int goodsnumber;
 public String getGoodsname() {
  return goodsname;
 }
 public void setGoodsname(String goodsname) {
  this.goodsname = goodsname;
 }
 public double getGoodsprice() {
  return goodsprice;
 }
 public void setGoodsprice(double goodsprice) {
  this.goodsprice = goodsprice;
 }
 public int getGoodsnumber() {
  return goodsnumber;
 }
 public void setGoodsnumber(int goodsnumber) {
  this.goodsnumber = goodsnumber;
 }
}

对库SpringMVC框架来说,他必须将请求参数转换成值对象类里个属性对象的数据类型------这就是类型转换的意义。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值