I have a link
String url = "original_internet_url";
if I visit that link then the browser will redirect to another_url.
My question is how to use Java, or Spring to get the redirected another_url programmatically.
Update: I want to get the redirected url, not "how to redirect url with Spring". For example: If you visit https://www.fb.com/ then you will be redirected to https://www.facebook.com/. Given https://www.fb.com/, how to know that the final url is https://www.facebook.com/.
You can do it with two ways.
First:
#RequestMapping(value = "/redirect", method = RequestMethod.GET)
public void method(HttpServletResponse httpServletResponse) {
httpServletResponse.setHeader("Location", projectUrl);
}
Second:
#RequestMapping(value = "/redirect", method = RequestMethod.GET)
public ModelAndView method() {
return new ModelAndView("redirect:" + projectUrl);
}
Related
I need some help from you all. Basically it has a base path at the class level (/grade), So the first method will return the jsp page to the user and second method will actually handle the request send from the client using xhr with GET method. So when it send the response I am able to handle it, but when i try to reload with the url http://localhost:8080/grade/12323 it returns me object not the page.
#GetMapping
public String getGradePage(HttpServletRequest request,Model model) {
HttpSession session = request.getSession();
User user = new User();
user.setUsername("1010000001");
user.setPassword("b");
session.setAttribute("user", user);
List<Course> courseList = gradeService.getAllClassById(user.getUsername());
model.addAttribute("courseList",courseList);
return "lecturer/submit-grade";
}
#GetMapping("/{courseCode}")
#ResponseBody
public List<Enrollment> submitGrade(#PathVariable String courseCode) {
List <Enrollment> enrollmentList = gradeService.getAllStudentEnrollmentById(courseCode);
return enrollmentList;
}
just solved it by changing the endpoint in my javascript xhr, what a silly mistake ..
This is an anchor tag in jsp page calling a get url, from this url I am forwarding to a post request
Call1
call1url hit a get request in controller
#RequestMapping(value = "/call1url", method = RequestMethod.GET)
public String make(HttpServletRequest request) {
return "forward:/manctril";
}
to forward to a post request in controller
#RequestMapping(value = "/main", method = RequestMethod.POST)
public String make2(HttpServletRequest request) {
return "forward:/dash";
}
trying to perform the above returns an error similar to
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported
Is my attempt possible or while is it failing
I don't think GET to POST call can be done from the server by using redirect or forward, You need to redesign your Solution. You can try achieving it using below way:
a. You anchor Tag do a POST call to the controller using JS or AJAX, and then from one POST to another POST can be done, like below by setting a request attribute
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT);
#RequestMapping(value = "/call1url", method = RequestMethod.POST)
public String make(HttpServletRequest request) {
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT);
return "forward:/main";
}
#RequestMapping(value = "/main", method = RequestMethod.POST)
public String make2(HttpServletRequest request) {
return "dash";
}
b. Your Anchor Tag should go to a GET call, which should render a jsp/html page and then autosubmit the jsp as POST on the page/body load like below,
<body onload="document.forms['redirectToURLForm'].submit()">
<form:form method="POST" id="redirectToURLForm"
name="redirectToURLForm" action="main">
</form:form>
</body>
This will call the POST /main method.
How can I send a POST request to the application itself?
If I just send a relative post request: java.lang.IllegalArgumentException: URI is not absolute.
#RestController
public class TestServlet {
#RequestMapping("value = "/test", method = RequestMethod.GET)
public void test() {
String relativeUrl = "/posting"; //TODO how to generate like "localhost:8080/app/posting"?
new RestTemplate().postForLocation(relativeUrl, null);
}
}
So using the example above, how can I prefix the url with the absolute server url path localhost:8080/app? I have to find the path dynamically.
You can rewrite your method like below.
#RequestMapping("value = "/test", method = RequestMethod.GET)
public void test(HttpServletRequest request) {
String url = request.getRequestURL().toString();
String relativeUrl = url+"/posting";
new RestTemplate().postForLocation(relativeUrl, null);
}
Found a neat way that basically automates the task using ServletUriComponentsBuilder:
#RequestMapping("value = "/test", method = RequestMethod.GET)
public void test(HttpServletRequest req) {
UriComponents url = ServletUriComponentsBuilder.fromServletMapping(req).path("/posting").build();
new RestTemplate().postForLocation(url.toString(), null);
}
If you want to refresh application.properties, you should AutoWire the RefreshScope into you controller, and call it explicitly, it make it much easier to see what it going on.
Here is an example
#Autowired
public RefreshScope refreshScope;
refreshScope.refreshAll();
I have a spring mvc web application with the following code. When the user is not logged in I am sending one tiles view.
And when the user is logged in I am redirecting to specific url patterns.
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("Requested with /login mapping");
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
List<String> userRoles = AuthenticationUtils.getUserRoles();
if (userRoles.contains("ROLE_ADMIN")) {
return "redirect:/admin.html";
} else if (userRoles.contains("ROLE_USER")) {
return "redirect:/user.html";
}
}
return "template";
}
I am getting the redirection but with some unexpected parameters. How to remove them?
http://localhost:8081/app/admin.html?total=48&loggedInUserRoles=207
I have tried the following url without success.
Spring MVC Controller: Redirect without parameters being added to my url
I have no clue of which part of code is adding the parameters.
You can make your method return View instead of String and then create RedirectView in a way:
RedirectView view = new RedirectView(url);
view.setExposeModelAttributes(false);
return view;
I try to have a redirect with 301 Status Code (you know I want to be SEO friendly etc).
I do use InternalResourceViewResolver so I wanted to use some kind of a code similar to return "redirect:http://google.com" in my Controller.
This though would send a 302 Status Code
What I have tried is using a HttpServletResponse to set header
#RequestMapping(value="/url/{seo}", method = RequestMethod.GET)
public String detail(#PathVariable String seo, HttpServletResponse response){
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return "redirect:http://google.com";
}
It does still return 302.
After checking documentation and Google results I've come up with the following:
#RequestMapping(value="/url/{seo}", method = RequestMethod.GET)
public ModelAndView detail(#PathVariable String seo){
RedirectView rv = new RedirectView();
rv.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
rv.setUrl("http://google.com");
ModelAndView mv = new ModelAndView(rv);
return mv;
}
It does work perfectly fine and as expected, returning code 301
I would like to achieve it without using ModelAndView (Maybe it's perfectly fine though). Is it possible?
NOTE: included snippets are just parts of the detail controller and redirect does happen only in some cases (supporting legacy urls).
I would suggest using redirectView of spring like you have it. You have to have a complete URL including the domain etc for that to work, else it will do a 302. Or if you have access to HttpServletResponse, then you can do the below as below.
public void send301Redirect(HttpServletResponse response, String newUrl) {
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", newUrl);
response.setHeader("Connection", "close");
}
Not sure when it was added, but at least on v4.3.7 this works. You set an attribute on the REQUEST and the spring View code picks it up:
#RequestMapping(value="/url/{seo}", method = RequestMethod.GET)
public String detail(#PathVariable String seo, HttpServletRequest request){
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.MOVED_PERMANENTLY);
return "redirect:http://google.com";
}
If you already return a ModelAndView and don't want to use HttpServletResponse, you can use this snippet:
RedirectView rv = new RedirectView("redirect:" + myNewURI);
rv.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
return new ModelAndView(rv);