0

I often want to refine posted data before use it, for example

public class Song() {
  public String[] tags;
  public String csvTags;

  public void setTagsWithCsv() {
    // this one should be more complicated for handling real data
    this.tags = csvTags.split(",");
  }
}

In this case, I have to call setTagsWithCsv method inside the method of the controller class.

@RequestMapping(value = "/song/create", method = POST)
public String createSong(Song song) {
  song.setTagsWithCsv();

  songService.create(song); // some code like this will come here
  ...
}

Is there any way to call the method with an annotation like '@PostConstruct'? The method should be called after a post request.

Sanghyun Lee
  • 21,644
  • 19
  • 100
  • 126

1 Answers1

1

Maybe you just provided a bad example, but If your Song is in a form of POJO, you do it on a call to setCsvTags

public class Song {
  private String[] tags;
  private String csvTags;

  public void setCsvTags(String csvTags) {
     this.csvTags = csvTags;
     this.tags = csvTags.split(",");
  }

  public void setTags(String[] tags) {
     this.tags == tags;
     String newCsvTags = Arrays.toString(tags);
     this.csvTags = newCsvTags.substring(1, newCsvTags.length() - 1); // get rid of []
  }
}

or make a method, without keeping explicit tags array

public class Song {

  private String csvTags;

  public void getTags() {
     return csvTags.split(",");
  }

}

Otherwise, there is no standard way of doing this, you can play with request interception before reaching your Controller, but I think it would be just a waste of time.

mavarazy
  • 7,562
  • 1
  • 34
  • 60