Response.seeOther returns blank screen - java

I need to redirect to a specific external url in my jersey web service
and I am using this method:
public static Response redirectTo(String path) {
URI uri;
try {
uri = new URI(path);
return Response.seeOther(uri).build();
} catch (URISyntaxException e) {
e.printStackTrace();
return null;
}
}
But it navigates to a white screen page and not to stackoverflow.com.
Why is it happening and how to fix it?
This method is called inside this method
#GET
#Path("/login")
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response login(#Context UriInfo info, #Context HttpServletRequest request) {
...
String url = "http://stackoverflow.com";
redirectTo(url);
}
the url of login method is called when triggering an event from AppDirect (via browser)

I ended up in adding the #Context HttpServletResponse res parameter to my method and calling this method res.sendRedirect(urlApp);
This is working as expected.

Related

How to code restcontroller for google actions?

I wish to code the Rest Controller in spring-boot for my webhook. I am creating a google action, with simple actions.
This is a boilerplate: https://github.com/actions-on-google/dialogflow-webhook-boilerplate-java/blob/master/src/main/java/com/example/ActionsServlet.java.
I want to do the same, only in spring-boot. I want to manipulate JSON body as input, but not sure how to do this.
#RestController
public class indexController extends HttpServlet {
#Autowired
private App actionsApp;
//handle all incoming requests to URI "/"
// #GetMapping("/")
// public String sayHello() {
// return "Hi there, this is a Spring Boot application";}
private static final Logger LOG = LoggerFactory.getLogger(MyActionsApp.class);
//handles post requests at URI /googleservice
#PostMapping(path = "/", consumes = "application/json", produces = "application/json")
public ResponseEntity<String> getPost(#RequestBody String payload,
#RequestHeader String header, HttpServletResponse response) throws IOException {
//Not sure what to do here.
System.out.println(jsonData);
return ResponseEntity.ok(HttpStatus.OK);
try {
//writeResponse(response, jsonResponse);
//String med request body og object that has all request header entries
String jsonResponse = actionsApp.handleRequest(body, listAllHeaders(header)).get();
return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
} catch (
InterruptedException e) {
System.out.println("Something wrong happened, interupted");
} catch (
ExecutionException e) {
System.out.println("Something wrong happened, execution error");
}
}
First, there is an error in your code. There might be a wrong "return" before your function logic.
return ResponseEntity.ok(HttpStatus.OK);
Second, as you are using Spring Framework, and you use "#RequestBody String payload" in the method, the Spring Framework will take the request body and set it to payload. If you set payload as a specific type. The framework will deserialize the body to it.
Finally, you can directly use payload in your code. The value of it would be the request body.
If you want to decode the json string. You can use org.json library.
JSONObject obj = new JSONObject(payload);
String name = obj.optString("name");
The code will get the value of name in the json.

How can i restrict the request from the unauthorized users (url's)?

Here my problem is that in my spring project totally 3 Jsp pages are available.
home page
register page
register success full page
When i type url for the home page in a browser, i am getting home page.and inside one hyperlink is available to register data. automatically when i click on that link it will go to the register page.then after it will go to the register success full page.
So finally my problem is that when i gave home page url in browser, homepage comes and also if i give register page url it will go to the register page with out touches the home page. but actually i want to access the register page through home page.
Use a token like JWT, set the token on access through Home page. Use a MVC Interceptor or a Filter and check that the token is present in the request before presenting the register page . If token not present redirect to home page.
Spring Security allows user's to access the url's as per authorization.
You can specify, which user has access to which url, if the user is not authorized then redirect to home page or just say access denied.
Please refer the spring security doc.it might help you.
You can simply create an authentication filter and specify on which methods you need to call this filter, for example, you want only an authorised user to access the downloadDoc api. Here is the sample code for this:
#WebFilter(urlPatterns = { "/getDocs", "/downloadDoc", "/updateStatus", "/submitApplication", "/login", "/logout",
/*"/requestDocuments", "/sendEmailRequest"*/"/getAllApplication", "/getApplicationDetails",
"/getAccountDetails" })
public class AuthenticationFilter implements Filter {
private static Logger logger = Logger.getLogger(AuthenticationFilter.class);
#Autowired
private UserVerificationService userVerificationService;
#Override
public void destroy() {
// TODO Auto-generated method stub
}
#Override
public void doFilter(ServletRequest arg0, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
logger.info("checking token in filter");
HttpServletRequest request = (HttpServletRequest) arg0;
if (!request.getMethod().equalsIgnoreCase("OPTIONS")) {
DocVerificationRequestWrapper myRequestWrapper = new DocVerificationRequestWrapper(request);
String body = myRequestWrapper.getBody();
String serviceName = request.getServletPath();
logger.info("serviceName = " + serviceName);
Token token = null;
try {
JSONObject jsonObj = new JSONObject(body);
logger.info(jsonObj);
if (jsonObj != null) {
JSONObject tokenObj = (JSONObject) jsonObj.get("token");
Gson gson = new Gson();
token = gson.fromJson(tokenObj.toString(), Token.class);
String clientName = request.getHeader("clientName");
logger.info("clientName = " + clientName);
if (null != token) {
if (userVerificationService == null) {
ServletContext servletContext = request.getServletContext();
WebApplicationContext webApplicationContext = WebApplicationContextUtils
.getWebApplicationContext(servletContext);
userVerificationService = webApplicationContext.getBean(UserVerificationService.class);
}
ClientResponse cr = userVerificationService.verifyUser(token, clientName, serviceName);
String verStatus = cr != null ? cr.getStatus() : null;
logger.info("verStatus = " + verStatus);
if (verStatus != null && verStatus.equalsIgnoreCase("success")) {
chain.doFilter(myRequestWrapper, response);
} else {
logger.error("Invalid token");
cr.setStatus("failure");
cr.setMessage("Invalid Token");
cr.setErrorCode("157");
cr.setToken(token);
response.getOutputStream().write(new ObjectMapper().writeValueAsBytes(cr));
// ((HttpServletResponse) response).sendError(157, "Invalid Token");
}
} else {
logger.error("token missing.");
ClientResponse cr = new ClientResponse();
cr.setStatus("failure");
cr.setMessage("Missing Token");
cr.setErrorCode("158");
response.getOutputStream().write(new ObjectMapper().writeValueAsBytes(cr));
// ((HttpServletResponse) response).sendError(158, "Token Missing");
}
}
} catch (JSONException e) {
logger.error("exception in authetication filter " + e);
}
}
}
#Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}

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

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;
}
}
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();
}
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

How to redirect to a JSP file from Servlet

I'm a beginner and am trying to understand how to re-direct to a JSP file from a Servlet. My Servlet "generates" a result after receiving replies from a current JSP file and with that I result I want to pass it to a different JSP file. I understand that there is a line of code:
request.getRequestDispatcher("/upload.jsp").forward(request, response);
But do I create a separate method for that and call it in the doGET?
you can do
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/upload.jsp").forward(request, response);
}
even though you created a method seperately you need the request and response object to the method.
I am heavily recommending the official docs:
http://docs.oracle.com/javaee/6/tutorial/doc/bnafd.html
and the pictorial
If you're using version 3.0 with annotations the redirects are very simple.
Suppose you have a User class (Strings fullname and Username with setters and getters) and UserDAO class that deals with database manipulation .
Suppose this is your controller:
#RequestMapping(value = "/user_list")
public String users(HttpServletResponse response, HttpServletRequest request)
{
//some function to verify access
boolean authorized = client.getAccess();
request.setAttribute("authorized", authorized);
if (authorized)
{
List<User> users = UserDAO.geUsers();
request.setAttribute("users", users);
return "user_list";
}
else
{
return "access_denied";
}
}
Then you can redirect from any location using the following syntax
#RequestMapping(value = "/create_user", method = RequestMethod.POST)
public String add_user(HttpServletResponse response, HttpServletRequest request)
{
boolean authorized = client.getAccess();
if (authorized)
{
User user = new User();
user.setUserName(request.getParameter("username"));
user.setFullName(request.getParameter("fullname"));
if (UserDAO.saveUser(user))
{
return "redirect:/user_list";
}
else
{
return "error";
}
}
else
{
return "access_denied";
}
}
The redirect:/user_list will return updated user_list (eg if you were inserting to db your
changes will be reflected).
Btw: you can drop the .jsp and path in your controller if you add few lines to your xml:
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-xml-example/
Have a look at those tutorials:
http://www.javatpoint.com/spring-3-mvc-tutorial
http://www.javatpoint.com/servlet-tutorial

Redirecting to a page using restful methods?

I've created a page which asks user to fill some form fields and when he submits, the form is sent to a Restful method which you can see below:
#POST
#Path("addUser")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void addUser(#FormParam("username") String username,
#FormParam("password") String password,
#FormParam("id") String id,
#FormParam("group_name") String groupName,
#FormParam("authority_name") String authorityName,
#FormParam("authority_id") String authorityId
)
{
//Something will be done here
}
How can I redirect the user at the end of this function to (let's say) index.jsp?
change your code like this, the addUser() should return a Response Object
public Response addUser(#FormParam("username") String username,
#FormParam("password") String password,
#FormParam("id") String id,
#FormParam("group_name") String groupName,
#FormParam("authority_name") String authorityName,
#FormParam("authority_id") String authorityId
)
{
//Something will be done here
java.net.URI location = new java.net.URI("../index.jsp?msg=A_User_Added");
return Response.temporaryRedirect(location).build()
}
Create a URI using javax.ws.rs.core.UriBuilder that maps the parameters and other data you want to preserve. Then use Response.temporaryRedirect to return a redirect to the client and pass it the URI you’ve built.
Finally I come to this conclusion that there are no other way than what I did:
So here is my solution:
try {
java.net.URI location = new java.net.URI("../index.jsp?msg=A_User_Added");
throw new WebApplicationException(Response.temporaryRedirect(location).build());
} catch (URISyntaxException e) {
e.printStackTrace();
}
By adding this block to my code, I got what I needed. Hope it helps you as well.
See below the usage of redirecting in web services:
public class LoginWebService {
#POST
#Path("/check")
public Response checkDetails(#FormParam("name") String name,#FormParam("pass") String pass ) throws URISyntaxException {
URI uri = new URI("/login/success");
URI uri2= new URI("http://localhost:9090/NewWebServiceproject/new/login/failure");
if(name.equals("admin") && pass.equals("pass"))
//#Path("http://localhost:8010/NewWebServiceproject/new/login/success");
{
return Response.temporaryRedirect(uri).build();
//Response.seeOther(uri);
//return Response.status(200).entity("user successfully login").build();
}
else
{
return Response.temporaryRedirect(uri2).build();
//Response.seeOther(uri2);
//return Response.status(200).entity("user logon failed").build();
}
}
#POST
#Path("/success")
public Response successpage()
{
return Response.status(200).entity("user successfully login").build();
}
#POST
#Path("/failure")
public Response failurepage()
{
return Response.status(200).entity("user logon failed").build();
}
}
It is not good idea to use the "WebApplicationException" in order to redirect the request. in Jersey (2.4.1) you should be able to redirect the request via the normal servlet way, (request.getServletContext().getRequestDispatcher().forward() or just response.sendRedirect())
The following is how Jersey process the request
org.glassfish.jersey.servlet.ServletContainer.service(HttpServletRequest request, HttpServletResponse response)
requestScope.runInScope
final ContainerResponse response = endpoint.apply(data)
methodHandler.invoke(resource, method, args);
Responder.process(ContainerResponse);
That methodHandler is your REST service class, method is the function in that service class.
The step to redirect page become straitforward
Get the (request, response) through Jersey injection (#Context HttpServletRequest request, #Context HttpServletResponse response) in class field or function parameter
Call request.getServletContext().getRequestDispatcher() to get the dispatcher for "forward"
or use Response.sendRedirect(url)
Once you application is returned (just null), Jersey will try to process the result in the "Responder.process(ContainerResponse)". In this step, it will use response to set status (204 no contents for your null return).
So the key point here is you must finalize/close response object before return from your service function. Otherwise, Jersey may overwrite your output.
Small tips on why "WebApplicationException" can overwrite Jersey repsponse. It is because org.glassfish.jersey.server.ServerRuntime.mapException() will use the "webApplicationException.getResponse()" as the return response result.

Categories