Struts2自定义类型转换器详解

需积分: 9 0 下载量 33 浏览量 更新于2024-08-18 收藏 477KB PPT 举报
"类型转换器小结-Struts2_PPT2" 在Struts2框架中,类型转换器扮演着至关重要的角色,它负责在客户端发送的字符串数据与服务器端的Java对象之间进行转换。默认情况下,Struts2提供的内置转换器能够满足大部分常见的类型转换需求,但有时候我们需要自定义转换器以适应特定的应用场景。 ### 2.1 类型转换 在传统的Web开发中,由于HTTP协议的限制,客户端提交的数据通常被转化为字符串,这与Java的强类型特性产生了冲突。例如,将用户输入的字符串转换为整型时,我们通常会使用`Integer.parseInt()`方法。然而,这种手动转换的方式不仅繁琐,而且容易出错。 ### 2.2 Struts2的类型转换机制 Struts2引入了强大的类型转换机制,它可以自动处理多种数据类型的转换,包括但不限于基本类型(如`boolean`、`char`、`int`等)、它们的封装类型以及对应的数组,还有`Date`、`String`数组和元素类型为`String`的`List`等。此外,Struts2还具备异常处理能力,能够在类型转换失败时提供适当的错误处理。 ### 2.3 自定义类型转换器 当默认的转换器无法满足需求时,开发者可以通过创建自定义类型转换器来扩展Struts2的功能。自定义转换器需要继承`StrutsTypeConverter`抽象类,并覆盖其中的两个关键方法: 1. `public Object convertFromString(Map context, String[] values, Class toClass)`:这个方法用于将接收到的字符串数组转换为目标类型。 2. `public String convertToString(Map context, Object o)`:此方法将Java对象转换回字符串,以便于回显或者存储。 在实现自定义转换器时,这两个方法都需要重写。 ### 自定义类型转换器的注册 注册自定义类型转换器有两种方式: - **局部类型转换器**:只对特定的Action生效。通过在Action所在的包内创建一个名为`Action类名-conversion.properties`的属性文件,其中键是Action属性名,值是转换器的全限定类名。 - **全局类型转换器**:适用于所有的Action。全局注册需要在类路径下的`struts-plugin.xml`或`struts.xml`配置文件中进行配置。 通过以上方式,我们可以根据项目需求灵活地扩展Struts2的类型转换功能,以实现更精确的数据绑定和验证,提高代码的可维护性和用户体验。

我用Spring5的aop应用时报这个错误Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from file [D:\ecliple\web5\WEB-INF\applicationContext.xml]; nested exception is java.nio.file.NoSuchFileException: WEB-INF\applicationContext.xml,他说我的applicationContext.xml文件不存在,可是我明明有这个文件,另外我的web.xml需要更改吗<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <context-param> <param-name>contextConfigLocation </param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <display-name>Struts2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/* </url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>

2023-05-30 上传