https://kotlinlang.org logo
#spring
Title
u

Udit003

10/24/2018, 2:36 PM
I am using Spring MVC with kotlin. In one of my Controller methods, I want to redirect to a internal url if a particular condition is met, else I want to serve a json object. This is my current code (striped down version)
Copy code
fun serveRequest(response :HttpServletRes)  : ResponseObject?  {
    if(condition_satisfied) {
         response.status = HttpServletResponse.SC_MOVED_PERMANENTLY
            response.sendRedirect("/new_path")
            return null
    } else {
       return Responsebject()
   }
}
This gives me 2 problems : 1. even if the response status is explicitly set 301 , it returns 302 2. The code looks a bit "hacky" to me, getting a feeling that better code can be possible.
d

diesieben07

10/24/2018, 2:40 PM
Don't annotate the method as
ResponseBody
, make your return type
Any
(Spring does not actually care what the static type is), then you can return both
ResponseEntity<ResponseObject>
and a String (
redirect:/new_path
).
That's the best I can come up with with my somewhat limited Spring knowledge.
u

Udit003

10/24/2018, 2:42 PM
ohk, let me try. But this looks even more "hacky" to me.😁
d

diesieben07

10/24/2018, 2:57 PM
Spring's handler methods are a giant hack to work around the static type system 😛
u

Udit003

10/24/2018, 2:59 PM
Sorry, But I didn't understand what did you mean by it? 😋
d

diesieben07

10/24/2018, 2:59 PM
Well, you can put "whatever you want" in the method signature and you can return "whatever you want". Spring will build "magic handlers" around it to handle it all for you
u

Udit003

10/24/2018, 3:01 PM
Yess. Now I got it. But isn't it the cool part about spring-kotlin. You get compile type safety on top of that.
d

diesieben07

10/24/2018, 3:02 PM
well, no, not really. if you put something in the signature that spring does not recognize then yes, your code will compile, but spring will throw a runtime exception at you
u

Udit003

10/24/2018, 3:05 PM
But, I don't know any class of object that "spring can't handle". Can you give me an example.
d

diesieben07

10/24/2018, 3:08 PM
Well, okay, it will handle it, but the default behavior (just bind model attributes to it) is not always what you want
I'm not saying that this is not useful, it's just a workaround 🙂
u

Udit003

10/24/2018, 3:11 PM
Yup, agreed. Maybe because of this , I have a lot of data classes made only to create response object for api endpoints.
n

nfrankel

10/24/2018, 4:43 PM
regarding 301/302 i believe you cannot change the http status easily with sendRedirect if you want to use 302, you need to do it “manually” i’ve written about it using the java ee API https://blog.frankel.ch/refining-redirect-semantics-servlet-api/
2 Views