Struts2 学习笔记19 类型转换 Part1

来源:互联网 发布:地理空间数据云平台 编辑:程序博客网 时间:2024/05/01 11:37

  现在来说一说类型转换,提到类型转换其实我们之前早已经用过了,在url传递参数的时候,我们传递过来的参数其实都是String类型的,在显示的时候都自动转换了,像这种简单的转换很好理解,我们要说的是,转换为那些相对不简单的类型。首先我们建立一个小项目。


TestAction.java

package com.tfj.action;import java.util.Date;import java.util.List;import java.util.Map;import com.opensymphony.xwork2.ActionSupport;public class TestAction extends ActionSupport{private int age;private String name;private Date d;List<String> interests;Map<String,String> user;public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Date getD() {return d;}public void setD(Date d) {this.d = d;}public List<String> getInterests() {return interests;}public void setInterests(List<String> interests) {this.interests = interests;}public Map<String, String> getUser() {return user;}public void setUser(Map<String, String> user) {this.user = user;}@Overridepublic String execute() throws Exception {return SUCCESS;}}
index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@taglib uri="/struts-tags" prefix="s" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>   age:<s:property value="age"/><br/>   name:<s:property value="name"/><br/>   date:<s:property value="d"/><br/>   <s:date name="d" format="yyyy/MM/dd HH:mm:ss"/><br/>   interests:<s:property value="interests"/><br/>   user:<s:property value="user"/><br/>  </body></html>
  对于age和name变量,在参数传递的部分已经说过了,只要注意是这里的struts2完成了一个转换。

  第一个要说的是Date变量,我们传进来date的值看看能不能显示。

访问http://localhost:8080/Struts2_3700_type_conversion/test?d=1991-11-11 这里我们传递了参数d=1991-11-11




这里得到了显示,在struts2中有格式化date的标签<s:date name="d" format="yyyy/MM/dd HH:mm:ss"/> 这样就把date格式化打印了出来。

对于List也是直接传递,就可以如(http://localhost:8080/Struts2_3700_type_conversion/test?interests=math&interests=english)。


对于Map需要这样(http://localhost:8080/Struts2_3700_type_conversion/test?user['a']=usera&user['b']=userb

特别说明:在使用集合的传参的时候一定要使用泛型。

原创粉丝点击