美文网首页
JavaWeb编程实战宝典(8)___第8章 Struts2的类

JavaWeb编程实战宝典(8)___第8章 Struts2的类

作者: 岁月静好浅笑安然 | 来源:发表于2019-11-06 14:59 被阅读0次

第8章 Struts2的类型转换

8.1 为什么要进行类型转换

8.1.1 了解客户端和服务端之间的数据处理过程

8.1.2 了解传统的类型转换

UserBean.java

    public class UserBean{
        private String name;
        private String password;
        private int age;
        private Date birthday;
        ...省略getter和setter方法
        
    }

Register继承HttpServlet

    public class Register extends HttpServlet {
        public void service(HttpServletRequset request,HttpServletResponse  response){
        
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out=response.getWriter();
        try{
            String name=request.getParameter("name");
            String password=request.getParameter("password");
            String ageStr=request.getParameter("age");
            String birthdayStr=request.getParameter("birthday");
            //对age请求参数值进行类型转换
            int age=Integet.parseInt(ageStr);
            //定义格式化日期类
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-DD");
            Date birthday=format.parse(birthdayStr);
            UserBean userBean=new UserBean();
            userBean.setName(name);
            userBean.setPassword(password);
            userBean.setAge(age);
            userBean.setBirthday(birthday);
            ...省略打印输出
        }catch(Exception  e){
        }
        }
    }

8.2 使用Struts2 类型转换器

8.2.1 了解Struts2内建的类型转换器

Struts2自带的类型转换器支持如下的几种类型

  • boolean和Boolean
  • char和Character
  • int和Integer
  • float/Float
  • long/Long
  • double/Douboe
  • Date
  • 数组
  • 集合

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
     <%@ taglib prefix="s" uri="/struts-tags"%>
<!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>
</head>
<body>
    <s:form action="type_conversion" >
    <!-- 对应products属性 -->
        <s:textarea label="产品1" name="products"/>
        <s:textarea label="产品2" name="products"/>
        <s:textarea label="产品3" name="products"/>
        <!-- 对应numbers属性 -->
        <s:textarea label="数字1" name="numbers"/>
        <s:textarea label="数字2" name="numbers"/>
        <s:textarea label="数字3" name="numbers"/>
        <!-- 对应collections属性 -->
        <s:textarea label="集合1" name="collections"/>
        <s:textarea label="集合2" name="collections"/>
        <s:textarea label="集合3" name="collections"/>
        <s:submit value="登录"/>  
    </s:form>
</body>
</html>

TypeConversionAction.java

    public class TypeConversionAction implements Action {
    private String [] products=new String[3];
    private int [] numbers=new int [3];
    private List<Integer> collections;
    
    public String[] getProducts() {
        return products;
    }

    public void setProducts(String[] products) {
        this.products = products;
    }

    public int[] getNumbers() {
        return numbers;
    }

    public void setNumbers(int[] numbers) {
        this.numbers = numbers;
    }

    public List<Integer> getCollections() {
        return collections;
    }

    public void setCollections(List<Integer> collections) {
        this.collections = collections;
    }

    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        return SUCCESS;
    }

}

success.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
     <%@ taglib prefix="s" uri="/struts-tags"%>
<!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>
</head>
<body>
<b>产品</b><br>
<s:property value="products[0]"/>
<s:property value="products[1]"/>
<s:property value="products[2]"/><p/>
<b>数字</b><br>
<s:property value="numbers[0]"/>
<s:property value="numbers[1]"/>
<s:property value="numbers[2]"/><p/>
<b>集合</b><br>
<s:property value="collections[0]"/>
<s:property value="collections[1]"/>
<s:property value="collections[2]"/><p/>
</body>
</html>

struts.xml

web.xml

8.2.2 实例:基于OGNL的类型转换器

8.2.3 配置全局类型转换器

Product.java

public class Product {
    private String name;
    private float price;
    private int count;
    ...省略setter和getter
}

ProductAction.java

public class ProductAction implements Action {
    private Product product1;
    private Product product2;
    public Product getProduct1() {
        return product1;
    }
    public void setProduct1(Product product1) {
        this.product1 = product1;
    }
    public Product getProduct2() {
        return product2;
    }
    public void setProduct2(Product product2) {
        this.product2 = product2;
    }
    @Override
    public String execute() throws Exception {
        return SUCCESS;
    }

}

ProductConverter.java
此处只是为了解析输入的属性(用逗号分隔的) 如自行车,1003.5,20

public class ProductConverter extends DefaultTypeConverter{

    @Override
    public Object convertValue(Map context, Object value, Class toType) {
        if(value==Product.class){
            String [] params=(String[]) value;
            Product product=new Product();
            String[] productValues = params[0].split(",");
            product.setName(productValues[0].trim());
            product.setPrice(Float.parseFloat(productValues[1].trim()));
            product.setCount(Integer.parseInt(productValues[2].trim()));
            return product;
            
        }else if(value==String.class){
            
            Product p=(Product) value;
            return p.getName()+","+p.getPrice()+p.getCount();
        }
        return null;
    }
    

}

xwork-conversion.properties文件和ProductAction.java同一个目录

com.hwp.Product=com.hwp.ProductConverter

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
     <%@ taglib prefix="s" uri="/struts-tags"%>
<!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>
</head>
<body>
    <s:form action="products">
    <s:textarea label="产品1" name="product1"></s:textarea>
    <s:textarea label="产品2" name="product2"></s:textarea>
    <s:submit value="登录"/>
    </s:form>
</body>
</html>

show.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
     <%@ taglib prefix="s" uri="/struts-tags"%>
<!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>
</head>
<body>
<b>产品1</b><p/>
名称:<s:property value="product1.name"/><br>
价格:<s:property value="product1.price"/><br>
数量:<s:property value="product1.count"/><p/>
<b>产品2</b><p/>
名称:<s:property value="product2.name"/><br>
价格:<s:property value="product2.price"/><br>
数量:<s:property value="product2.count"/><br>
</body>
</html>

web.xml

struts.xml

此demo运行起来,输入后跳转获取不到属性值,还没查到原因

8.2.4 实例:实现基于Struts2的类型转换器

8.2.5 实例:实现数组类型转换器

8.2.6 实例:实现集合类型转换器

8.3 实例:使用OGNL表达式进行类型转换

8.4 Struts对Collection和Map的支持

8.4.1 指定集合元素的类型

ProductsAction.java

public class ProductAction implements Action{
    private List myProductList;
    private List myProductMap;
    ...省略setter和getter方法
    public String execute() throws Exception{
    return SUCCESS;
    }
}

在ProductsAction.java所在目录,建立一个ProductsAction-conversion.properties

如果是List类型

    Element_xxx=对象类型

如果是Map类型

    Key_xxx=对象类型
    Element_xxx=对象类型

其中xxx变量Action类对象的属性名字,此处的实例代码

# 配置List
Element_myProductList=com.hwp.Product
# 配置Map
Key_myProductMap=java.lang.String
Element_myProductMap=com.hwp.Product

8.4.2 掌握Set和索引属性

8.5 掌握类型转换的错误处理

相关文章

网友评论

      本文标题:JavaWeb编程实战宝典(8)___第8章 Struts2的类

      本文链接:https://www.haomeiwen.com/subject/plpubctx.html