Mistre83
Mistre83

Reputation: 2827

Spring REST - Construct link from Entity

I'm using Spring + JPA and i have mapped an entity as an Database View, where i got all fields.

Now i want add one field to this entity and return a link image based to another field (all image are stored in resource/images)

@Entity
@Table(name = "Release")
public class Release implements Serializable
{
  private String user;
  private String userImageLink; // This is what i need to implement

  @XmlElement
  @JsonProperty
  public String getUser(){
    return user;
  }
  public void setUser(String user) {
    this.user = user;
  }

  public String getUserImageLink(){
    String imageUrl = /*i need to access to resource/images and create the link
                       If i run on localhost should return: http://127.0.0.1:8080/resources/images..
                       In production coudl return: http://myServer.com/resources/images..     
                      */;
    return imageUrl;
  }
}
}

The question is: how i can create and return this url ?

MORE INFO

If the table have 3 entry: User1, User2, User3

In the userImageLink i should return:

http://myserver.com/resources/images/User1.jpg http://myserver.com/resources/images/User2.jpg

Isn't important if the image exists or not in resources/image, i just need to compose the url as additional parameter when i access to the Service that take the data from my "Release" @Entity

Upvotes: 1

Views: 205

Answers (3)

Maximilian Hils
Maximilian Hils

Reputation: 6770

https://stackoverflow.com/a/24122238/934719 provides a very simple solution to this problem which works without Autowiring etc:

public static String getContextParameter(String param){
    try {
        InitialContext initialContext = new InitialContext();
        Context environmentContext = (Context) initialContext.lookup("java:/comp/env");
        return (String) environmentContext.lookup(param);
    } catch (NamingException e) {
        e.printStackTrace();
    }
    return null;
}

Upvotes: 1

tmarwen
tmarwen

Reputation: 16354

You can use your application ServletContext to generate the URL to your images. This ServletContext cannot be accessed as a POJO into your JPA Entities but should be injected as a bean with the Spring container or you will end up with a null reference:

  • Autowire a static instance variable as a ServletContext in your entity:
@Entity
@Table(name = "Release")
public class Release implements Serializable
{
  @Transient
  private static ServletContext servletContext;

  @PostConstruct
  public void init() {
    log.info("Initializing ServletContext as [" +
                Release.servletContext + "]"); //Forces injection after bean construction.
  }

  @Autowired
  public void setServletContext(ServletContext servletContext) {
    Release.servletContext = servletContext; //Note the use of class name because that fiels hould be static thus shared by all instances.
  }
  //...
}
  • Use the injected ServletContext to retrieve your webapp context path and build your image URL accordingly:
@Entity
@Table(name = "Release")
public class Release implements Serializable
{
  //...
  public String getUserImageLink(){
    StringBuilder imageUrlBuilder = new StringBuilder(Release.servletContext.getContextPath())
        .append("/resources/images")
        .append(this.user);
    return imageUrlBuilder.toString();
  }
}

Remember to add annoation based bean scannig to recognize your servlet context bean and mark your Release class with @Component so it is scanned:

<beans>
  <!-- ... -->
  <context:component-scan base-package="package.of.Release" />
<beans>

Thanks to @Ravi Thapliyal for sharing the tip.

Upvotes: 2

Vipul Paralikar
Vipul Paralikar

Reputation: 1568

1) Mark userImageLink as @Transient because JPA will use all properties of the class, unless you specifically mark them with @Transient as shown below:

@Transient
private String userImageLink;

2) Once Release entity class is populated with DB values then assuming that httpservletrequest object is available:

StringBuilder baseURL = new StringBuilder();
baseURL.append(request.getRequestURL().toString().replace(request.getRequestURI(), ""));

baseURL.append("/resources/images/").append(release.getUser());

release.setUserImageLink(baseURL);

Upvotes: 1

Related Questions