简体   繁体   中英

Java Spring App - RequestParam mapped as my own object

I want to have this kind of link:

mydom.com/path?param=x& &otherParam=... &otherParam=...

I was thinking to map that sort as an object(Foo) which hold 2 values

public void path(@RequestParam(value = "sort", required = false)Foo sort)

public class Foo{

    private String field;
    private boolean asc;

    //constructor & getters & setters

}

Explanation:

I want to have a parameter which hold exact 2 values(first is field which is sort and other if it's ascending or descending. One String and other Boolean.

It is possible and how?

You can simply accept the String[] . Eg below:

@GetMapping("/")
public String[] path(@RequestParam("sort") String[] sort) {
    return sort;
}

Hit /?sort=abc,def and you will get ["abc","def"] as the response.

Or you can split the param value. In both cases, you will have to parse the second element to boolean .

Or see this answer

Quick and dirty way

class Foo {
    String fieldName;
    Boolean sort;
    @JsonIgnore
    String[] sortParam;
    public void setSortParam(String[] sortParam) throws Exception {
        if(sortParam.length != 2) throw new Exception("");
        this.fieldName = sortParam[0];
        this.sort = Boolean.valueOf(sortParam[1]);
        this.sortParam = sortParam;
    }
    // generate the getters/setters except setSortParam
}

Now you can use:

@GetMapping("/")
public Foo something(Foo object) {
    return object;
}

The following solution should work as you required:

I want to have a parameter which hold exact 2 values(first is field which is sort and other if it's ascending or descending. One String and other Boolean.

First implement your data holding class, eg Foo:

public class Foo {

   private String field;
   private Boolean asc;

   // add getters/setters 
}

Then implement and configure a custom Spring `HandlerMethodArgumentResolver' implementation class:

public class FooParamResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return Foo.class.isAssignableFrom(parameter.getParameterType())
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        // this is the place where you handle the query params
        // and add them to your Foo instance
        HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest();

        // this is your part ;) 
        String field = // call method to determine field value...
        Boolean asc = // call method to determine asc value
        Foo foo = new Foo();
        foo.setField(field);
        foo.setAsc(asc);
        return foo;
    }
}

In the end, register your custom handler:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new FooParamsHandler());
    }
}

Now the following controller method should do the job:

// don't forget your controller methods annotations, e.g. @GetMapping(path="/yourPath")
public void someMethodName(Foo foo) {
   // do whatever with foo... 
}

Well, you can read the request param sort as a list of strings and create your object using the first and second element in that list

public void path(@RequestParam(value = "sort", required = false)List<String> sort) {
   Foo sortObj = new Foo(sort.get(0),sort.get(1));
}

You can refer to this link It has examples in both ways: 1. Send two different params - String and Boolean 2. Send the object

https://lankydan.dev/2017/03/11/passing-data-transfer-objects-with-get-in-spring-boot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM