Home > Back-end >  Grab String Value from Thymeleaf Form then Pass It From Controller to Service Class and Finally as @
Grab String Value from Thymeleaf Form then Pass It From Controller to Service Class and Finally as @

Time:10-22

In my Spring Boot Application, I have a HTML Thymeleaf form in which I grab a String Value from the user. I want to pass this value from my Controller Class, to my Service Class and finally in Repo Class. The latter has an @Query and the purpose of this whole implementation is to give users the ability to choose contents from my database based on their input. For example, I have records that vary in different dates. I want user to choose the date that their want and the proper records get displayed from my database.

I have trouble in my controller class in which I need somehow to connect my model and pass it as parameter in my service class. Then the latter should communicate with the Repo Class to execute the query in the @Query and return my results. Until now, all I am getting is null values.

What am I doing wrong???

CONTROLLER CLASS

package com.andrekreou.covid.gov.controller;

import com.andrekreou.covid.gov.model.Covid;
import com.andrekreou.covid.gov.service.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

@Controller
public class WelcomePageController {

    private final Service service;

    @Autowired
    public WelcomePageController(Service service) {
        this.service = service;
    }

    @Value("${welcome.message}")
    private String message;

    @GetMapping("/")
    public String main(Model model){
        model.addAttribute("message", message);
        return "welcome";
    }

    @GetMapping("/login")
    public String getLoginView() {
        return "login";
    }

    @GetMapping("/date/insert")
    public String getDateInsertView() {
        return "date-insert";
    }

    @GetMapping("/show-contents")
    public String showAllRates(HttpServletRequest request){
        request.setAttribute("covidcases", service.showAllCases());
        return "databasecontents";
    }

    @RequestMapping(value = "/dateInsertion", method = RequestMethod.POST)
    public String submit(@ModelAttribute("covid") Covid covid,
                         ModelMap model,
                         HttpServletRequest request) {

        model.addAttribute("referencedate", covid.getReferencedate());
        request.setAttribute("covidcases", service.showCases("referencedate"));
        return "databasecontents";
    }
}

SERVICE CLASS

package com.andrekreou.covid.gov.service;

import com.andrekreou.covid.gov.model.Covid;
import com.andrekreou.covid.gov.repository.CovidRepo;
import org.springframework.beans.factory.annotation.Autowired;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

@org.springframework.stereotype.Service
@Transactional
public class Service {

    private final CovidRepo covidRepo;

    @Autowired
    public Service(CovidRepo covidRepo) {
        this.covidRepo = covidRepo;
    }

    public List<Covid> showAllCases(){
        return new ArrayList<>(covidRepo.findAll());
    }

    public List<Covid> showCases(String referencedate){
        return new ArrayList<>(covidRepo.findByReferencedate(referencedate));
    }
}

REPO CLASS

package com.andrekreou.covid.gov.repository;

import com.andrekreou.covid.gov.model.Covid;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface CovidRepo
        extends JpaRepository<Covid,Integer> {

    @Query("select e from #{#entityName} e where e.referencedate = ?1")
    List<Covid> findByReferencedate(@Param("referencedate") String referencedate);
}

THYMELEAF VIEW

<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>login</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-/Y6pD6FV/Vv2HJnA6t vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet" crossorigin="anonymous">
    <style>
        body {
            background-color: #3e3e3e;
            color: white;
        }
    </style>
</head>
<body>
<div >
    <form  method="post" action="/dateInsertion" th:object="${covid}">
        <h2 >Please Choose The Date</h2>
        <p>
            <label for="referencedate" >Username</label>
            <input type="text" id="referencedate" name="referencedate"  placeholder="referencedate" required=""
                   autofocus="">
        </p>
        <button  type="submit">Set Date</button>
    </form>
</div>
</body>
</html>

CodePudding user response:

Thymeleaf is a rendering engine so it has no functionality it performs when you post something to your controller. which means basic form posting applies which in your case would be 1 field named referencedate

Asuming your covid entity has this as variable with valid setter method the error would be in this request.setAttribute("covidcases", service.showCases("referencedate")); line where it should be request.setAttribute("covidcases", service.showCases(covid.getReferencedate()));

If your covid entity does not include this parameter you have to either add it or seperatly add it to your controller function as a @RequestParam String referencedate

  • Related