#Spring JDBC

101 messages · Page 1 of 1 (latest)

tulip wren
#

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 ?

raven tulipBOT
#

This post has been reserved for your question.

Hey @tulip wren! 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.

serene surge
#

How did you add the image to your DB?

tulip wren
#

@serene surge

serene surge
tulip wren
#

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

serene surge
tulip wren
#

no it stores the bytes in database

serene surge
#

or does finderService.addUser() do that?

serene surge
tulip wren
serene surge
#

retrieving probably works somewhat similar to storing

tulip wren
#
        System.out.println("it passed the service layer");
        return finderUserImp.saveUser(finderUser);
    }```
serene surge
tulip wren
#

its the implemented class of dao interface

#

@serene surge

serene surge
tulip wren
#

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;
    }


    ```
serene surge
#

What does finderUser.getImage() return? A byte[]?

tulip wren
#

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;
    }```
serene surge
#

then you can probably use Spring JDBC to execute a SELECT statement

#

and that can get the image as a byte[]

tulip wren
#

u mean like this Select image from table where email = ?

#

@serene surge

serene surge
#

yes

tulip wren
serene surge
#

why convert it to a String?

tulip wren
#

bcz what the data is coming is in byte form and i want it to be a image !

serene surge
#

well images are binary data

#

i.e. bytes

serene surge
tulip wren
#

bro tell me what to do ? @serene surge

serene surge
#

Just use the byte[]?

#

byte[] seems fine to me

tulip wren
serene surge
#

What format do you want for the image?

tulip wren
#

JPEG or Png Anything

serene surge
#

it is a jpeg or png or whatever stored in a byte[]

tulip wren
serene surge
#

So what's the issue about that?

tulip wren
#

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 ?

serene surge
#

oh ok

tulip wren
#

yehh

serene surge
#

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

tulip wren
serene surge
tulip wren
#

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>```
serene surge
tulip wren
#

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

serene surge
#

and it isn't the empty string?

tulip wren
#
    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

serene surge
serene surge
tulip wren
#

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 ?

tulip wren
# serene surge Does it work?

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

serene surge
tulip wren
# serene surge 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

serene surge
tulip wren
tulip wren
#

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

serene surge
#

Does your program run twice?

tulip wren
#

now i have already closed it and closed the ecplise as well

#

and after that i got this

near relic
#

Try to restart your computer.

#

(if the tomcat run as a windows service you will have this problem after restart too)

near relic
#
     * 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}" />

serene surge
near relic
#

Yes, considerations?

serene surge
near relic
#

It is automagically gathered from url-parameter

serene surge
#

like the user can literally decide what user to get information about

#

(Also you didn't use annotations to tell Spring about that)

near relic
near relic
#

Xing publishes all profile-fotos, facebook, gulp, etc. all offer everyones profile photo.

serene surge
#

by default compilation doesn't include parameter names btw

serene surge
serene surge