Spring JDBC

I have added a image into My Database! But Now I don't know how to retrieve it from database and show it on my frontend. Can Anyone Help ?
66 Replies
JavaBot
JavaBot6mo ago
This post has been reserved for your question.
Hey @Danix! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
dan1st
dan1st6mo ago
How did you add the image to your DB?
Danix
DanixOP6mo ago
Using MultipartFile Library @dan1st | Daniel
dan1st
dan1st6mo ago
Can you show the relevant code?
Danix
DanixOP6mo ago
Yehh sure
@PostMapping("/registration")
public String registration(@Valid @ModelAttribute("finderUserPojo") MovieFinderUserPojo finderUserPojo,
BindingResult bindingResult, HttpSession httpSession, Model model,
@RequestParam("file") MultipartFile file) {

if (bindingResult.hasErrors()) {
System.out.println(bindingResult.getErrorCount());
return "register";
}

try {
String email = finderUserPojo.getEmail();

MovieFinderUser existingUser = finderUserImp.findByEmail(email);


if (existingUser != null && existingUser.getPassword().equals(finderUserPojo.getPassword())) {
return "registeredusers";
}

MovieFinderUser finderUser = new MovieFinderUser(finderUserPojo.getName(), finderUserPojo.getEmail(),
finderUserPojo.getPassword(), finderUserPojo.getFavouriteMovie(),
finderUserPojo.getFavouriteGenre(), file.getBytes() );

if (!file.isEmpty()) {
httpSession.setAttribute("User", finderUser);
finderService.addUser(finderUser);

// store the bytes somewhere
return "userregistered";

} else {
return "register";
}

}
catch(Exception e)
{
e.printStackTrace();
return "register";
}
}
@PostMapping("/registration")
public String registration(@Valid @ModelAttribute("finderUserPojo") MovieFinderUserPojo finderUserPojo,
BindingResult bindingResult, HttpSession httpSession, Model model,
@RequestParam("file") MultipartFile file) {

if (bindingResult.hasErrors()) {
System.out.println(bindingResult.getErrorCount());
return "register";
}

try {
String email = finderUserPojo.getEmail();

MovieFinderUser existingUser = finderUserImp.findByEmail(email);


if (existingUser != null && existingUser.getPassword().equals(finderUserPojo.getPassword())) {
return "registeredusers";
}

MovieFinderUser finderUser = new MovieFinderUser(finderUserPojo.getName(), finderUserPojo.getEmail(),
finderUserPojo.getPassword(), finderUserPojo.getFavouriteMovie(),
finderUserPojo.getFavouriteGenre(), file.getBytes() );

if (!file.isEmpty()) {
httpSession.setAttribute("User", finderUser);
finderService.addUser(finderUser);

// store the bytes somewhere
return "userregistered";

} else {
return "register";
}

}
catch(Exception e)
{
e.printStackTrace();
return "register";
}
}
Here is the controller @dan1st | Daniel
dan1st
dan1st6mo ago
That doesn't store the bytes anywhere, right?
Danix
DanixOP6mo ago
no it stores the bytes in database
dan1st
dan1st6mo ago
or does finderService.addUser() do that? How?
Danix
DanixOP6mo ago
from this
dan1st
dan1st6mo ago
retrieving probably works somewhat similar to storing
Danix
DanixOP6mo ago
public int addUser(MovieFinderUser finderUser) {
System.out.println("it passed the service layer");
return finderUserImp.saveUser(finderUser);
}
public int addUser(MovieFinderUser finderUser) {
System.out.println("it passed the service layer");
return finderUserImp.saveUser(finderUser);
}
dan1st
dan1st6mo ago
Now what's findUserImp?
Danix
DanixOP6mo ago
its the implemented class of dao interface @dan1st | Daniel
dan1st
dan1st6mo ago
Can you show that?
Danix
DanixOP6mo ago
package com.moviefindercontrollers.model;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class MovieFinderUserImp implements Dao {

@Autowired
private JdbcTemplate jdbcTemplate;


@Override
public int saveUser(MovieFinderUser finderUser) {
String query = "INSERT INTO moviefinderuser (name, email, passoword , favouriteMovie , favouriteGenre , image) VALUES (?, ?, ? , ?, ? , ?)";
int updatedLine = jdbcTemplate.update(query,finderUser.getName() , finderUser.getEmail(), finderUser.getPassword() , finderUser.getFavouriteMovie() , finderUser.getFavouriteGenre() , finderUser.getImage());
System.out.println("It Passed THe Repo layer");
return updatedLine;
}


@Override
public MovieFinderUser findByEmail(String email) {
String query = "SELECT * FROM moviefinderuser where email = ?";
MovieFinderUser finderUser = jdbcTemplate.queryForObject(query, new RowMapperObj() ,email );
return finderUser;
}



package com.moviefindercontrollers.model;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class MovieFinderUserImp implements Dao {

@Autowired
private JdbcTemplate jdbcTemplate;


@Override
public int saveUser(MovieFinderUser finderUser) {
String query = "INSERT INTO moviefinderuser (name, email, passoword , favouriteMovie , favouriteGenre , image) VALUES (?, ?, ? , ?, ? , ?)";
int updatedLine = jdbcTemplate.update(query,finderUser.getName() , finderUser.getEmail(), finderUser.getPassword() , finderUser.getFavouriteMovie() , finderUser.getFavouriteGenre() , finderUser.getImage());
System.out.println("It Passed THe Repo layer");
return updatedLine;
}


@Override
public MovieFinderUser findByEmail(String email) {
String query = "SELECT * FROM moviefinderuser where email = ?";
MovieFinderUser finderUser = jdbcTemplate.queryForObject(query, new RowMapperObj() ,email );
return finderUser;
}



dan1st
dan1st6mo ago
What does finderUser.getImage() return? A byte[]?
Danix
DanixOP6mo ago
Where ?
public class MovieFinderUser {

private String name;

private String email;

private String password;

private String favouriteMovie; // Changed from favoriteMovie

private String favouriteGenre; // Changed from favoriteGenre

private byte[] image;

public MovieFinderUser() {
}

public MovieFinderUser(String name, String email, String password, String favouriteMovie, String favouriteGenre , byte[] image) {
this.name = name;
this.email = email;
this.password = password;
this.favouriteMovie = favouriteMovie;
this.favouriteGenre = favouriteGenre;
this.image = image;
}

public byte[] getImage() {
return image;
}

public void setImage(byte[] image) {
this.image = image;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getFavouriteMovie() { // Changed from getFavoriteMovie
return favouriteMovie;
}

public void setFavouriteMovie(String favouriteMovie) { // Changed from setFavoriteMovie
this.favouriteMovie = favouriteMovie;
}

public String getFavouriteGenre() { // Changed from getFavoriteGenre
return favouriteGenre;
}

public void setFavouriteGenre(String favouriteGenre) { // Changed from setFavoriteGenre
this.favouriteGenre = favouriteGenre;
}
public class MovieFinderUser {

private String name;

private String email;

private String password;

private String favouriteMovie; // Changed from favoriteMovie

private String favouriteGenre; // Changed from favoriteGenre

private byte[] image;

public MovieFinderUser() {
}

public MovieFinderUser(String name, String email, String password, String favouriteMovie, String favouriteGenre , byte[] image) {
this.name = name;
this.email = email;
this.password = password;
this.favouriteMovie = favouriteMovie;
this.favouriteGenre = favouriteGenre;
this.image = image;
}

public byte[] getImage() {
return image;
}

public void setImage(byte[] image) {
this.image = image;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getFavouriteMovie() { // Changed from getFavoriteMovie
return favouriteMovie;
}

public void setFavouriteMovie(String favouriteMovie) { // Changed from setFavoriteMovie
this.favouriteMovie = favouriteMovie;
}

public String getFavouriteGenre() { // Changed from getFavoriteGenre
return favouriteGenre;
}

public void setFavouriteGenre(String favouriteGenre) { // Changed from setFavoriteGenre
this.favouriteGenre = favouriteGenre;
}
yehh yeeh
dan1st
dan1st6mo ago
then you can probably use Spring JDBC to execute a SELECT statement and that can get the image as a byte[]
Danix
DanixOP6mo ago
u mean like this
Select image from table where email = ?
Select image from table where email = ?
@dan1st | Daniel
dan1st
dan1st6mo ago
yes
Danix
DanixOP6mo ago
and then how to convert the byte into string for the proper image ?
dan1st
dan1st6mo ago
why convert it to a String?
Danix
DanixOP6mo ago
bcz what the data is coming is in byte form and i want it to be a image !
dan1st
dan1st6mo ago
well images are binary data i.e. bytes you are also using a byte[] here
Danix
DanixOP6mo ago
yehh bro tell me what to do ? @dan1st | Daniel
dan1st
dan1st6mo ago
Just use the byte[]? byte[] seems fine to me
Danix
DanixOP6mo ago
hmm like i succesfully getting the bytes of the image but now what to do to convert it from byte to a inage ? thats my question
dan1st
dan1st6mo ago
What format do you want for the image?
Danix
DanixOP6mo ago
JPEG or Png Anything
dan1st
dan1st6mo ago
it is a jpeg or png or whatever stored in a byte[]
Danix
DanixOP6mo ago
its a jpeg that was stored in byte []
dan1st
dan1st6mo ago
So what's the issue about that?
Danix
DanixOP6mo ago
i think u dont get my question i mean i succesfully decode the image to byte from my DB alright and now i want to show that image which i decode into byte in my jsp page then how could i do it ?
dan1st
dan1st6mo ago
oh ok
Danix
DanixOP6mo ago
yehh
dan1st
dan1st6mo ago
you could convert it to base64 and include it in the JSP or you could create another endpoints, one for getting the image and the JSP has a <img> loading the image from that endpoint
Danix
DanixOP6mo ago
i have to convert it into base64 in my controller or my jsp page
Danix
DanixOP6mo ago
Successfully decode it but getting this
<img src="data:image/jpeg;base64," alt="User Image">
<img src="data:image/jpeg;base64," alt="User Image">
in the img tag when checking it from devtools .. and the image is not there as well @dan1st | Daniel
Danix
DanixOP6mo ago
No description
Danix
DanixOP6mo ago
My Jsp
<div class="container">
<h1>User Profile</h1>

<c:if test="${not empty image}">
<img src="data:image/jpeg;base64,${image}" alt="User Image" />
</c:if>
<div class="container">
<h1>User Profile</h1>

<c:if test="${not empty image}">
<img src="data:image/jpeg;base64,${image}" alt="User Image" />
</c:if>
dan1st
dan1st6mo ago
is image the base64? string
Danix
DanixOP6mo ago
yehh
@PostMapping("/registration")
public String registration(@Valid @ModelAttribute("finderUserPojo") MovieFinderUserPojo finderUserPojo,
BindingResult bindingResult, HttpSession httpSession, Model model,
@RequestParam("file") MultipartFile file) {

if (bindingResult.hasErrors()) {
System.out.println(bindingResult.getErrorCount());
return "register";
}

try {
String email = finderUserPojo.getEmail();

MovieFinderUser existingUser = finderUserImp.findByEmail(email);


if (existingUser != null && existingUser.getPassword().equals(finderUserPojo.getPassword())) {
return "registeredusers";
}

byte[] image = file.getBytes();
String base64EncodedImage = Base64.getEncoder().encodeToString(image);

MovieFinderUser finderUser = new MovieFinderUser(finderUserPojo.getName(), finderUserPojo.getEmail(),
finderUserPojo.getPassword(), finderUserPojo.getFavouriteMovie(),
finderUserPojo.getFavouriteGenre(), base64EncodedImage.getBytes());



if (!file.isEmpty()) {
httpSession.setAttribute("User", finderUser);
httpSession.setAttribute("image", base64EncodedImage);
model.addAttribute("image", base64EncodedImage);
finderService.addUser(finderUser);

// store the bytes somewhere
return "userregistered";

} else {
return "register";
}

}
catch(Exception e)
{
e.printStackTrace();
return "register";
}
}
@PostMapping("/registration")
public String registration(@Valid @ModelAttribute("finderUserPojo") MovieFinderUserPojo finderUserPojo,
BindingResult bindingResult, HttpSession httpSession, Model model,
@RequestParam("file") MultipartFile file) {

if (bindingResult.hasErrors()) {
System.out.println(bindingResult.getErrorCount());
return "register";
}

try {
String email = finderUserPojo.getEmail();

MovieFinderUser existingUser = finderUserImp.findByEmail(email);


if (existingUser != null && existingUser.getPassword().equals(finderUserPojo.getPassword())) {
return "registeredusers";
}

byte[] image = file.getBytes();
String base64EncodedImage = Base64.getEncoder().encodeToString(image);

MovieFinderUser finderUser = new MovieFinderUser(finderUserPojo.getName(), finderUserPojo.getEmail(),
finderUserPojo.getPassword(), finderUserPojo.getFavouriteMovie(),
finderUserPojo.getFavouriteGenre(), base64EncodedImage.getBytes());



if (!file.isEmpty()) {
httpSession.setAttribute("User", finderUser);
httpSession.setAttribute("image", base64EncodedImage);
model.addAttribute("image", base64EncodedImage);
finderService.addUser(finderUser);

// store the bytes somewhere
return "userregistered";

} else {
return "register";
}

}
catch(Exception e)
{
e.printStackTrace();
return "register";
}
}
here is the controller
dan1st
dan1st6mo ago
and it isn't the empty string?
Danix
DanixOP6mo ago
@GetMapping("/profile")
public String profile(HttpSession session, Model model) {

if (session.getAttribute("isLoggedIn") == null) {
return "redirect:/login";
}

String email = (String) session.getAttribute("email");
MovieFinderUser userInfo = finderUserImp.findByEmail(email);
String image = (String) session.getAttribute("image");

session.setAttribute("image", image);
session.setAttribute("userInfo", userInfo);
model.addAttribute(userInfo);
model.addAttribute("image", image);

System.out.println(userInfo.toString());
return "profile";

}
@GetMapping("/profile")
public String profile(HttpSession session, Model model) {

if (session.getAttribute("isLoggedIn") == null) {
return "redirect:/login";
}

String email = (String) session.getAttribute("email");
MovieFinderUser userInfo = finderUserImp.findByEmail(email);
String image = (String) session.getAttribute("image");

session.setAttribute("image", image);
session.setAttribute("userInfo", userInfo);
model.addAttribute(userInfo);
model.addAttribute("image", image);

System.out.println(userInfo.toString());
return "profile";

}
the profile ok done i got it @dan1st | Daniel
dan1st
dan1st6mo ago
Can you try viewing image there using a debugger? Does it work?
Danix
DanixOP6mo ago
heyy i am getting one more doubt that like i want to fetch the third party API and i succesfully fetched it from restTemplate but how to convert the JSON into String Object can i use GSON library for it ? yehh i was retriving it in the wrong way ! i was retriving it in the register Controller where it was saving not in the loggedIn controller where the query is actually working :hidethepain:
dan1st
dan1st6mo ago
you can - or you could use something else
Danix
DanixOP6mo ago
This is what i have done
package com.moviefindercontrollers.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ApiService {


private static final String API_KEY = "private";
private static final String BASE_URL = "http:/private/";

@Autowired
private RestTemplate restTemplate;

public String fetchDataFromApi(String parameter) {
String url = BASE_URL + "?apikey=" + API_KEY + "&t=" + parameter + "&plot=full";

return restTemplate.getForObject(url, String.class);
}
}
package com.moviefindercontrollers.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ApiService {


private static final String API_KEY = "private";
private static final String BASE_URL = "http:/private/";

@Autowired
private RestTemplate restTemplate;

public String fetchDataFromApi(String parameter) {
String url = BASE_URL + "?apikey=" + API_KEY + "&t=" + parameter + "&plot=full";

return restTemplate.getForObject(url, String.class);
}
}
Service annotation is good for it or not and where could i use the GSON library at the same class or i can make the diferent class ? @dan1st | Daniel
dan1st
dan1st6mo ago
I think RESTTemplate can convert to objects if wanted
Danix
DanixOP6mo ago
do u have any doucmentation related to it
Danix
DanixOP6mo ago
Hey I Suddenly Starts to get this
Several ports (8005, 8080) required by Tomcat v9.0 Server at localhost are already in use. The server may already be running in another process, or a system process may be using the port. To start this server you will need to stop the other process or change the port number(s).
Several ports (8005, 8080) required by Tomcat v9.0 Server at localhost are already in use. The server may already be running in another process, or a system process may be using the port. To start this server you will need to stop the other process or change the port number(s).
@dan1st | Daniel
dan1st
dan1st6mo ago
Does your program run twice?
Danix
DanixOP6mo ago
now i have already closed it and closed the ecplise as well and after that i got this
Peter Rader
Peter Rader6mo ago
Try to restart your computer. (if the tomcat run as a windows service you will have this problem after restart too)
/**
* Respond to the request of the photo by the user's id.
*
* @param userId The url-parameter holding the user's id
* @param request The request will injected by spring, never <code>null</code>
* @return The photo or the answer that the photo in the browser's cache did not change
*/
@GetMapping("/profilePhoto.jpeg")
public ResponseEntity<byte[]> sendProfilePhotoToBrowser(@RequestParam("userId") long userId, HttpServletRequest request) {
var existingUser = finderUserImp.findById(userId);
byte[] decodedImage = Base64.getDecoder().decode(existingUser.getImage());
var dbEtag = "" + '"' + Objects.hash(decodedImage) + '"';
var browsersEtag = request.getHeader(HttpHeaders.IF_NONE_MATCH);

// do not send if browser already have the image
ResponseEntity<byte[]> result;
if (dbEtag.equals(browsersEtag)) {
result = new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
} else {
var headers = new HttpHeaders();
headers.setETag(dbEtag);
headers.setContentLength(decodedImage.length);

// the browser will correct it
headers.setContentType(MediaType.IMAGE_JPEG);
result = new ResponseEntity<>(decodedImage, headers, HttpStatus.OK);
}
return result;
}
/**
* Respond to the request of the photo by the user's id.
*
* @param userId The url-parameter holding the user's id
* @param request The request will injected by spring, never <code>null</code>
* @return The photo or the answer that the photo in the browser's cache did not change
*/
@GetMapping("/profilePhoto.jpeg")
public ResponseEntity<byte[]> sendProfilePhotoToBrowser(@RequestParam("userId") long userId, HttpServletRequest request) {
var existingUser = finderUserImp.findById(userId);
byte[] decodedImage = Base64.getDecoder().decode(existingUser.getImage());
var dbEtag = "" + '"' + Objects.hash(decodedImage) + '"';
var browsersEtag = request.getHeader(HttpHeaders.IF_NONE_MATCH);

// do not send if browser already have the image
ResponseEntity<byte[]> result;
if (dbEtag.equals(browsersEtag)) {
result = new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
} else {
var headers = new HttpHeaders();
headers.setETag(dbEtag);
headers.setContentLength(decodedImage.length);

// the browser will correct it
headers.setContentType(MediaType.IMAGE_JPEG);
result = new ResponseEntity<>(decodedImage, headers, HttpStatus.OK);
}
return result;
}
try this The jsp-part might look like this: <img src="profilePhoto.jpeg?userId=${user.id}" />
dan1st
dan1st6mo ago
A userId parameter to the GetMapping?
Peter Rader
Peter Rader6mo ago
Yes, considerations?
dan1st
dan1st6mo ago
How should Spring know what to put there?
Peter Rader
Peter Rader6mo ago
It is automagically gathered from url-parameter
dan1st
dan1st6mo ago
which sucks for security like the user can literally decide what user to get information about (Also you didn't use annotations to tell Spring about that)
Peter Rader
Peter Rader6mo ago
For url-parameters you dont need a annotation. What else annotation should I need? Neither part of the question nor common practice. Xing publishes all profile-fotos, facebook, gulp, etc. all offer everyones profile photo.
dan1st
dan1st6mo ago
@RequestParam by default compilation doesn't include parameter names btw these are normally erased/not included in the class file
Peter Rader
Peter Rader6mo ago
Good point.
dan1st
dan1st6mo ago
You did that in your code
JavaBot
JavaBot6mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Want results from more Discord servers?
Add your server