String input string string Struts2

What is the best way to crop this line / where is the best place to place the crop code?

Let's say I have the following text box in my jsp:

<s:textfield label="First Name" name="person.firstname"/> 

Action class:

 public class BaseAction extends ActionSupport implements ServletRequestAware, SessionAware { private Person person; // Getters, setters and action logic } 

bean:

 public class Person implements Serializable { private String lastname; private String firstname; // Getters and setters } 

I can change the default setting in the bean, but this seems like a hack:

 public void setFirstname(String firstname) { this.firstname = firstname.trim(); } 

EDIT : I also saw this question: struts2 trim the entire line obtained from forms , where some also suggested that the “correct” method is to use an interceptor.

Why is the interceptor “correct”? What is changing the bean settings wrong?

+6
java string design struts2
source share
2 answers

The short answer is not the default, there is no built-in mechanism for this, and you either need to do this in your class of actions, or some java-script will do this for you.

Another possible way is to create an interceptor to do this with the possibility of an exception or something similar in a similar track.

I think Interceptor is a good way to do this, it is better to have such an interceptor with S2.

+3
source share

This can be done using Struts2 converters .

 public class TrimmingStringConverter extends StrutsTypeConverter { public Object convertFromString(Map ctx, String[] values, Class arg2) { if (values != null && values.length > 0) { return values[0].trim(); } return null; } public String convertToString(Map ctx, Object o) { if (o != null) { return o.toString(); } else { return null; } } public Object convertValue(Map context, Object o, Class toClass) { if (o == null) { return null; } else if (toClass == java.lang.String.class) { if (o instanceof String[]) { String[] os = (String[]) o; if (os.length > 0) { return os[0].trim(); } } return o.toString().trim(); } return super.convertValue(context, o, toClass); } } 

It must be registered in xwork-conversion.properties: java.lang.String = es.jogaco.webapp.TrimmingStringConverter

This will be used to enter all .

It will work if you have struts2 interceptors by default. Quoted from struts2 doc:

By default, the interception converter is included in struts-default.xml in the default stack

Plus it works for me in my struts2 application.

+6
source share

All Articles