1

I have a Dropdown multi selectbox to select 0..N states that I am passing to a Spring REST controller. In JQuery, the JSON looks like this : {"states":["California","Vermont"]}. When I am trying to get these values in the controller, I have only 1 state : states[]/California. Also, the states[] brackets makes me think I am missing something because that looks like an array name but the controller is expecting a Map. Any ideas ?

$(document).ready(function() { 
   $('select').change(function() {         
        var states = { states: $("#cstates").val()};     
        alert(JSON.stringify(states));
        $.ajax({
          type: "POST",
          url: "http://localhost:8080/api/campaign/stats",
          data: states,
          cache: false,
          success: function(data){
             $("#resultarea").text(data);
          }
        });

   }); 
});

Here is the REST controller code:

@Slf4j
@RestController
public class CampaignStatsRESTController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @PostMapping("/api/campaign/stats")
    public List<String> getSearchResultViaAjax(@RequestParam Map<String,String> allParams) {

        //All SQL query parameters
        for (Map.Entry<String, String> entry : allParams.entrySet()) {
            log.info(entry.getKey() + "/" + entry.getValue());
        }
        //Send query -- TO DO : Add parameters      
        return jdbcTemplate.query("select count(*) as cnt from [dbo].[LineOfBusiness1CampaignTempOutput]", (rs, rowNum) -> rs.getString("cnt"));                   
    }   
}

UPDATE 2 : As suggested :

    @PostMapping(path = "/api/campaign/stats",consumes = "application/json")
public List<String> getSearchResultViaAjax(@RequestBody Map<String, List<String>> allParams) {

Then I have use Data type and content type in the AJAX call

 $(document).ready(function() { 
   $('select').change(function() {       
        //var formData = JSON.stringify($("#cstates").serializeArray());
        var states = { states : $("#cstates").val(), zips : $("#czips").val()};

        //alert(JSON.stringify(states));
        $.ajax({
          type: "POST",
          url: "http://localhost:8080/api/campaign/stats",
          data: JSON.stringify(states),
          cache: false,
          success: function(data){
             $("#resultarea").text(data);
          },
          dataType: "json",
          contentType : "application/json"
        });

   }); 
});
1
  • It looks like you are doing a normal POST so the data is going to be turned into a queryString in the body. Given that the value of the states key is an array, that's slightly odd. I would suggest trying to JSON.stringify the array in the states object so that when the body is generated the value of states will be a json string. Your controller would then just have to parse it to turn it into an array again Commented Aug 30, 2019 at 15:36

1 Answer 1

2

Map<String, String> is not what you need. Your structure could be described rather by Map<String, List<String>>, unfortunately, it does not work in Spring :(

If you want to pass this info as a query parameter, and key 'states' is static, the best choice would be:

@PostMapping("/api/campaign/stats")
public List<String> getSearchResultViaAjax(@RequestParam List<String> states) {

and query:

 /api/campaign/stats?states=California,Vermont

If 'states' key is dynamic, I would pass it in request body:

@PostMapping("/api/campaign/stats")
public List<String> getSearchResultViaAjax(@RequestBody Map<String, List<String>> allParams) {
Sign up to request clarification or add additional context in comments.

3 Comments

States is dynamic so I would like to use @RequestBody but I get <br/> [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported] I was thinking maybe I need contentType: "application/json" in the JQuery but that didn't change anything.
@mkirouac can you convert it to JSON and use content-type=application/json? (like this: stackoverflow.com/questions/22195065/…)
Unfortunately, same error. Adding the new code below since would let me add it in comment section

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.