#Spring JDBC
101 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @tulip wren! Please use
/closeor theClose Postbutton 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.
How did you add the image to your DB?
Using MultipartFile Library
@serene surge
Can you show the relevant code?
Yehh sure
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
@serene surge
That doesn't store the bytes anywhere, right?
no it stores the bytes in database
or does finderService.addUser() do that?
How?
from this
retrieving probably works somewhat similar to storing
System.out.println("it passed the service layer");
return finderUserImp.saveUser(finderUser);
}```
Now what's findUserImp?
Can you show that?
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;
}
```
What does finderUser.getImage() return? A byte[]?
Where ?
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
then you can probably use Spring JDBC to execute a SELECT statement
and that can get the image as a byte[]
yes
and then how to convert the byte into string for the proper image ?
why convert it to a String?
bcz what the data is coming is in byte form and i want it to be a image !
you are also using a byte[] here
yehh
bro tell me what to do ? @serene surge
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
What format do you want for the image?
JPEG or Png Anything
it is a jpeg or png or whatever stored in a byte[]
its a jpeg that was stored in byte []
So what's the issue about that?
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 ?
oh ok
yehh
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
i have to convert it into base64 in my controller or my jsp page
declaration: module: java.base, package: java.util, class: Base64, class: Encoder
Successfully decode it but getting this <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
@serene surge
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>```
is image the base64? string
yehh
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
and it isn't the empty string?
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 @serene surge
Can you try viewing image there using a debugger?
Does it work?
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 
you can - or you could use something else
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);
}
}
?
@serene surge
I think RESTTemplate can convert to objects if wanted
do u have any doucmentation related to it
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).
@serene surge
Does your program run twice?
now i have already closed it and closed the ecplise as well
and after that i got this
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;
}
``` try this
The jsp-part might look like this: <img src="profilePhoto.jpeg?userId=${user.id}" />
A userId parameter to the GetMapping?
Yes, considerations?
How should Spring know what to put there?
It is automagically gathered from url-parameter
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)
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.
@RequestParam
by default compilation doesn't include parameter names btw
these are normally erased/not included in the class file
Good point.
You did that in your code