Dropwizard - how to do a server side redirect from a view?

跟風遠走 提交于 2019-12-01 01:12:29

问题


I'm new to Drop Wizard, and would like to redirect from a server side view to another url in my app.

Does DropWizard wrap up this common task somehow?

e.g.

@GET
public View getView(@Context HttpServletRequest req)
{
     View view = new View();

     if (somethingBad)
     {
         // code here to redirect to another url, eg /bad_data
     }
     else
     {
          return view;
     }
}

回答1:


Here's a simple code example that actually does the redirect using a WebApplicationException. So you could put this in your view, or in your resource, and just throw it whenever.

URI uri2 = UriBuilder.fromUri(url).build();
Response response = Response.seeOther(uri2).build();
throw new WebApplicationException(response);

You can also just make your resource return either a view, or a redirect response:

@GET
public Object getView(@Context HttpServletRequest req)
{
     if (somethingBad())
     {
         URI uri = UriBuilder.fromUri("/somewhere_else").build();
         return Response.seeOther(uri).build();
     }

     return new View();
}



回答2:


Dropwizard is using Jersey 1.x. In Jersey you can throw a WebApplicationException to redirect a user.

Also see the answer here: https://stackoverflow.com/a/599131/360594



来源:https://stackoverflow.com/questions/20709386/dropwizard-how-to-do-a-server-side-redirect-from-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!