Struts2学习笔记(4) - OGNL

通过OGNL实现表单数据的获取,并自动类型转换,以及编写自定义类型转换器

1.自定义类型 User.java

public class User {
  private String name;
  private Map pets;

  ...
  Setter and Getter
  ...
}


public class Pet {
  private name;

  ...
  Getter and Setter
  ...
}


2.编写自定义类型转换器

//  StrutsTypeConverter由org.apache.struts2.util.*提供,它主要提供convertFromString()和convertFromString()方法,用于将字符串转化成类以及将类转化成字符串
public class PetConverter extends StrutsTypeConverter{

  //  context参数是一个 action context,values是由表单提供的输入参数,toClass在API中的解释为 "the class to convert to "作用暂时未知
  public Object convertFromString(Map context, String[] values,Class toClass) {
    Pet pet = new Pet();
    pet.setName(values[0]);
    return pet;
  }

  public String convertToString(Map context, Object o) {
    Pet pet = (Pet)o;
    String name = pet.getName();
    return name;
  }
}


3.编写表单action类 OGNLAction.java

pulbic class OGNLAction extends ActionSupport {
  public String execute() {
    
    //  通过ActionContext获得该线程的session
    ActionContext ac = ActionContet.getContext();
    Map session = ac.getSession();
    
    //  将user存入session.以供结果页面使用
    session.put("user", user);
  
    return SUCCESS;
  }

  private User user;
  ...
  Getter and Setter
  ...
}


4.在action类的properties文件中配置自定义类型转换器

OGNLAction.properties
//  指定User的pets属性使用自定义转换器
User.pets = com.vea.converter.PetConverter


5.编写信息输入页面 FillForm.jsp
<%@ page language="java" contentType="text/html; UTF-8"  pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

...
<body>
  <s:form action="OGNLAction" >
    <s:textfield name="user.name" label="UserName" />
    <s:textfield name="user.pets['pet1'].name" label="Pet1Name" />
    <s:textfield name="user.pets['pet2'].name" label="Pet2Name" />
    <s:submit />
  </s:form>
</body>
...


6.配置struts.xml

<constant name="struts.devMode" value="true" />

<package name"ognl" namespace="/" extends="struts-default" >
  <action name="FillForm" >
    <result>/FillForm.jsp</result>
  </action>

  <action name="PetConverter" class="con.vea.converter.PetConverter" >
    <result>/Result.jsp</result>
    <result name="input">/FillForm.jsp</result>
  </action>
</package>
...

你可能感兴趣的:(java,apache,jsp,xml,struts)