Skip to content
Advertisement

How can I use more then one param in a spring boot rest Controller?

I want to achive the follwing URL to access my data with 2 params:

http://localhost:8080/contactnote?entryDate=2022-02-01?contactType=T

Both mappings with a single param is working:

@GetMapping(params ={"contactType"})
    public ResponseEntity<Collection<ContactNote>> findContactNotesWithEntryDateGreaterThan(@RequestParam(value = "contactType")  String contactType) {
        return new ResponseEntity<>(repository.findByContactType(contactType), HttpStatus.OK);
    }
    @GetMapping(params ={"entryDate"})
    public ResponseEntity<Collection<ContactNote>> findContactNotesWithDateTilGreaterThan(@RequestParam(value = "entryDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date entryDate) {
        return new ResponseEntity<>(repository.findByEntryDateGreaterThan(entryDate), HttpStatus.OK);

But when I try to combine them with two params it wont work, not one of them is usable.

@GetMapping(params ={"entryDate", "contactType"})
    public ResponseEntity<Collection<ContactNote>> findByEntryDateGreaterThanAndContactTypeWith(
            @RequestParam(value = "entryDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date entryDate,
            @RequestParam(value = "contactType") String contactType
    )

My reposiitory looks like this:

import de.bhm.zvoove.api.domain.ContactNote;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

@Repository
public interface ContactNoteRepository extends JpaRepository<ContactNote, Long> {
    List<ContactNote> findByContactType(String ContactType);
    List<ContactNote> findByEntryDateGreaterThanAndContactType(Date entryDate , String ContactType);

}

Advertisement

Answer

the URL you entered is invalid, double ?, you have to use & for the second parameter

correct one: http://localhost:8080/contactnote?entryDate=2022-02-01&contactType=T

this code work, use name instead value

@GetMapping(path= "/contactnote")
@ResponseBody
public String findByEntryDateGreaterThanAndContactTypeWith(
        @RequestParam(name = "entryDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date entryDate,
        @RequestParam(name = "contactType", required = false) String contactType) {

    return "Hello World";
}

enter image description here

9 People found this is helpful
Advertisement