The code in dateaction. Java is as follows:
package com.itheima.action;import java.util.Date;public class DateAction {private Date time;public Date getTime() {return time;}public void setTime(Date time) {this.time = time;}public String execute() {return "success";}}
Struts2.xml:
<action name="dateAction" class="com.itheima.action.DateAction"><result name="success">/date.jsp</result></action>
Date. jsp:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
The Code is as follows:
Http: // localhost: 8080/struts2_itheima/dateaction? Time = 2011-01-04
Both the console and JSP can be output normally:
However, if you enter:
Http: // localhost: 8080/struts2_itheima/dateaction? Time = 20110104
The console outputs null and the webpage outputs
This is because of this input method. The time parameter is of the string type. An error occurred while calling the settime (date time) method. In this case, the private date time; value obtained is null.
However, jsp can output as is because the underlying layer of struts2 automatically obtains the parameter value as is output when the settime (date time) method fails.
To solve the preceding problem, create a custom type converter:
Datetypeconverter. Java:
Package COM. itheima. type. converter; import Java. text. parseexception; import Java. text. simpledateformat; import Java. util. date; import Java. util. map; import COM. opensymphony. xwork2.conversion. impl. defatypetypeconverter; public class datetypeconverter extends defatypetypeconverter {@ overridepublic object convertvalue (Map <string, Object> context, object value, class totype) {/* value: converted data, because struts2 needs to accept all request parameters, such as the check box totype: type to be converted */simpledateformat dateformat = new simpledateformat ("yyyymmdd"); If (totype = date. class) {/** because struts2 needs to accept all request parameters, such as the check box, a parameter name corresponds to multiple values. * The framework uses the getparamtervalues method to obtain the parameter values, this leads to the obtained String Array *, so the value is a string array */string [] STRs = (string []) value; Date time = NULL; try {time = dateformat. parse (STRs [0]);} catch (parseexception e) {e. printstacktrace (); throw new runtimeexception (E);} return time;} else if (totype = string. class) {date = (date) value; string time = dateformat. format (date); return time;} return NULL ;}}
Then create the DateAction-conversion.properties file under the package where dateaction is located, where dateaction is the action to convert the parameter type, other formats are fixed, that is: XXX-conversion.properties
The DateAction-conversion.properties content is as follows:
time=com.itheima.type.converter.DateTypeConverter
Project tree:
Customize the action parameter type converter in struts2