Forwarding request to a new controller - java

I have this two controller from two separate projects lets name them:
project1.controller1
project2.controller1
Obviously these are two Spring controllers from different projects.What I want is to make project1.controller1 a gateway all request will be sent here. And will process the request if it will go to project2.controller1 or a new controller.
Some pseudoCode:
#Controller
public class someClassFromProject1{
#RequestMapping(value="/controller1", method=RequestMethod.POST)
public String smsCatcher(String target, HttpServletRequest request,
HttpServletResponse response){
//some processing, converting request to string, etc
if("someStringThatIsPartOfTheRequest".equals("someString"))
//carry request and forward it to project2.controller1
else
//go to another external controller
}
}
And in project2.controller 1 will look something like this:
#Controller
public class someClassFromProject2{
#RequestMapping(value="/controller1", method=RequestMethod.POST)
public String smsCatcher(String target, HttpServletRequest request,
HttpServletResponse response){
//processing
}
}
I've already tried return "forward:/someUrl"; and return "redirect:someUrl";. It didn't work and it didn't reach project2.controller1. So any ideas on this one?
Edit: Forgot to add this one, different project means different WAR but deployed on the same sever. And the request should be carried over from project1.controller1 to project2.controller1 because I'm gonna process the request there.
Thanks!

You need to use redirect instead of forward.

The protocol is required if the host is different to that of the current host
return "redirect:http://www.yahoo.com";
Have a look at the redirect: prefix section from Spring Web MVC framework also check this
A logical view name such as redirect:/myapp/some/resource will
redirect relative to the current Servlet context, while a name such as
redirect:http://myhost.com/some/arbitrary/path will redirect to an
absolute URL.

Figured it out but then it's kind of messy, I've used HttpClient to Post my Request to the URL. It also carried the request along with the forwarding. Anyway, thanks for all the help guys. Thanks :)

Related

Request Forward to another url in spring boot mvc with mustache template

I am trying to forward the request to another url in spring boot.
I know how to forward the request from one endpoint to another endpoint in the same spring boot application. The code for this is like -
#GetMapping("/home")
public ModelAndView home(#PathVariable(name = "env", required = false) String env) {
return new ModelAndView("index");
}
#GetMapping("/forward")
String callForward(){
return "forward:/home";
}
Here If I go to http://localhost:8080/forward then it will be server by "/home" endpoint and we'll get the home page rendered. Interesting thing here is "url" in the browser remains same http://localhost:8080/forward.
My requirement is > I want to forward to the request to any third party url for example when http://localhost:8080/forward is called I want it to be served by https://google.com/forward.
How can I do it.
I am open to any solution which can fulfill the requirement.
There is a difference between Forward vs Redirect.
Forward: happens on the server-side, servlet container forwards the same request to the target URL, hence client/browser will not notice the difference.
Redirect: In this case, the server responds with 302 along with new URL in location header and then client makes another request to the given URL. Hence, visible in browser
Regarding your concern, it can be achieved using multiple ways.
Using RedirectView
#GetMapping("/redirect")
RedirectView callRedirect(){
return new RedirectView("https://www.google.com/redirect");
}
Using ModelAndView with Prefix
#GetMapping("/redirect")
ModelAndView callRedirectWithPrefix(){
return new ModelAndView("redirect://www.google.com/redirect");
}
Usecase for forwarding could be something like this (i.e. where you want to forward all request from /v1/user to let's /v2/user on the same application)
#GetMapping("/v1/user")
ModelAndView callForward(){
return new ModelAndView("forward:/v2/user");
}
The second approach (using ModelAndView) is preferable as in this case, your controller will have no change where it redirects or forwards or just returning some page.
Note: As mentioned in comments, if you are looking for proxying request, i would suggest checking this SO Thread

Passing $routeParams from angularjs to spring-MVC controller

This is what I have in my AngularJs controller
.when("/M:topicId", {templateUrl: "Mu", controller: "conMFs"})
app.controller('conMFs',function($scope,$routeParams){
$scope.otherId = $routeParams.topicId;
});
This is my Spring Controller
#RequestMapping(value="/controlerM", method = RequestMethod.GET)
public ModelAndView controlerM(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView model = null;
session=request.getSession(true);
user = (User) session.getAttribute("user");
List<ends1> ends=(List<ends1>) ifriendlistservice.getends(user.getId(),5);
session.setAttribute("MutualFriends", MutualFriends);
model = new ModelAndView("ends");
return model;
I am able to fetch the topicId from my AngularJS page in AngularJS controller (with $scope.otherId), however I am unable to pass this value to my Spring controller, from where I am redirecting to new page.
How should I do this?
.when("/M:topicId", {templateUrl: "Mu", controller: "conMFs"})
app.controller('conMFs',function($window){
$window.location.reload();
});
Then server app gets topicId from request's url. You also need to have $locationProvider.html5Mode enabled.
How should I do this?
You shouldn't. Angular's off-hour job is to not let server apps to reload the page. The code above is quick-and-dirty, it can be ok only if you're in the middle of Angular integration into existing project, but the time-frame requires you to partially rely on old code base.
If you really need to make a redirect (e.g. to external page), make an AJAX request, put topicId and whatever there, get redirect url in response, redirect with $window.location.href.
I'm barely familiar with Spring, but the above applies to any server-side application.
Thanks estus,
Issue seems to be resolved...
I had created 2 controller in Spring, One for setting parameter through ajax , and other for redirection.

Alternative of URL parameter for deciding which method to call

Right now based on the site name in the URL parameter, we decide the appropriate actions to take(method calls etc) in the Java (Standard Jsp/Servlet web applications). For example, the request would be something like www.oursite.com?site=Ohio
Wondering what would be the alternative of doing this without having to provide URL parameter.
You could use POST instead of GET.
GET appends request parameters to the end of the URL.
POST sends encoded data using a form.
http://www.tutorialspoint.com/jsp/jsp_form_processing.htm
Why not just code it into the path?
www.oursite.com/Ohio
If you're just using straight servlet api, you can just do something of this nature:
String path = request.getPathInfo();
String site = path.split("/")[0];
That being said, most web frameworks have some support for helping with this.
For example, in spring mvc:
#RequestMapping(value="/{site}/blah/blah", method=RequestMethod.GET)
public ModelAndView blahBlah(HttpServletRequest req,
HttpServletResponse resp,
#PathVariable("site") String site) {
// do stuff here
}
Of course you could do this at the controller level too if all your methods need that sort of mapping:
#Controller
#RequestMapping(value="/{site}")
public class MyController {
#RequestMapping(value="/blah/blah", method=RequestMethod.GET)
public ModelAndView blahBlah(HttpServletRequest req,
HttpServletResponse resp,
#PathVariable("site") String site) {
// do stuff here
}
}
I believe this is cleaner than a query param, though it still shows up in your URL. There's other, more complex methods like using apache's reverse proxying and virtual host capabilities to switch based on site names. You could do something at login, and store the site in session. It all depends on your requirements.
You could use an alternate URL, like ohio.oursite.com. This process could be automated by having your server respond to *.oursite.com. I would probably set up a filter that looked at what the subdomain was and compared that with a predefined list of allowed sites. If it didn't exist, you could redirect back to the main (www) site. If it did, you could set a request attribute that you could use in a similar way that you currently use the request parameter now.

Spring 3.x - how do I redirect from a mapping that returns data?

I have a method in my controller like this:
#RequestMapping(value="getData", method=RequestMethod.GET)
#ResponseBody
public List<MyDataObj> getData()
{
return myService.getData();
}
The data is returned as JSON or xsl, depending on the request.
If the person making the request is not authorized to access the data I need to redirect the user to a "not authorized" page, so something like this:
#RequestMapping(value="getData", method=RequestMethod.GET)
#ResponseBody
public List<MyDataObj> getData()
{
if (!isAuthorized())
{
// redirect to notAuthorized.jsp
}
return myService.getData();
}
All the examples I've seen using Spring require the method to return either a String or a ModelAndView. I thought about using HttpServletResponse.sendRedirect() but all my JSPs are under WEB-INF and can't be reached directly.
How can I deny access gracefully to the data request URL?
A more elegant solution may be to use a HandlerInterceptor which would check for authorization, blocking any requests which are not permitted to proceed. If the request then reaches your controller, you can assume it's OK.
The answer is below. But your particular case would rather to handle with other approach.
#RequestMapping(value = "/someUrl", method = RequestMethod.GET)
#ResponseBody
public Response someMethod(String someData, HttpServletResponse response){
if(someData=="redirectMe"){
response.sendRedirect(ppPageUrl);
}
...
}
Another approach is filter. You can move all security logic into filter and keep clean code in controllers.
Pretty simple:
Send a error status to the client
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
and handle the same with you ajax callback handler and redirect. :)

How to intercept custom HTTP header value and store it in Wicket's WebSession?

I need to grab a certain custom HTTP header value from every request and put it in WebSession so that it will be available on any WebPage later on. (I believe the Wicket way to do this is to have a custom class extending WebSession that has appropriate accessors.)
My question is, what kind of Filter (or other mechanism) I need to be able to both intercept the header and access the WebSession for storing the value?
I tried to do this with a normal Java EE Filter, using
CustomSession session = (CustomSession) AuthenticatedWebSession.get();
But (perhaps not surprisingly), that yields:
java.lang.IllegalStateException:
you can only locate or create sessions in the context of a request cycle
Should I perhaps extend WicketFilter and do it there (can I access the session at that point?), or is something even more complicated required?
Of course, please point it out if I'm doing something completely wrong; I'm new to Wicket.
I'd guess you need to implement a custom WebRequestCycle:
public class CustomRequestCycle extends WebRequestCycle{
public CustomRequestCycle(WebApplication application,
WebRequest request,
Response response){
super(application, request, response);
String headerValue = request.getHttpServletRequest().getHeader("foo");
((MyCustomSession)Session.get()).setFoo(headerValue);
}
}
And in your WebApplication class you register the custom RequestCycle like this:
public class MyApp extends WebApplication{
#Override
public RequestCycle newRequestCycle(Request request, Response response){
return new CustomRequestCycle(this, (WebRequest) request, response);
}
}
Reference:
Request cycle and request cycle
processor

Categories