Spring Boot redirect to another url - spring-boot

In my spring boot project i wanted to do a redirection from http://localhost:8080 to http://localhost:8080/birdspotting. This is the code of the Home controller:
#RestController
public class HomeController {
#GetMapping("/")
public String showHomePage() {
return "redirect:/birdspotting";
}
}
The result of going to http://localhost:8080 is a print of redirect:/birdspotting

Basically RestController = Controller + RequestBody
Which will send json response but we are expecting view resolver to return the page or redirect url.
So use #Controller instead of #RestController to fix the issue.
Update:
If you want to use both in Same controller then use #Controller on class level and then wherever you want to return API call response put #ResponseBody on method and wherever you want to return web browser page don't put #ResponseBody.

You have to create the other endpoint like:
#GetMapping("/")
public String showHomePage() {
return "redirect:/birdspotting";
}
#GetMapping("/birdspotting")
public String birdspottingPage() {
return "birdspotting";
}
It's expect you have birdspotting.html in your templates.

Related

Thymeleaf + Spring MVC + Rest

I don't understand, how to change #Controller to #RestController for RESTFull serivce, if html template linked with attributes that I get in ModelAndView
#Controller
public class MyController{
#GetMapping("/index")
public ModelAndView index(){
return new ModelAndView("/index", name, userService.getUser().getName());
}
}
and in thymeleaf template it's look like
<p th:text="'Hello, ' + ${name} + '!'" />
But I wanna go to index page, and in background get user name
#RestController
public class MyController{
#GetMapping("/api/user")
public String index(){
return userService.getUser().getName();
}
}
I can use ajax for update tag "p", but in this way it's nothing benefit of using thymeleaf, I can use jsp. So what the best way use thymeleaf with rest and is it rational?
I think the purpose of Thymeleafis for server-side rendering.
Thymeleaf is a Java template engine for processing and creating HTML, XML, JavaScript, CSS, and text.
When you are using JSON API and parse the JSON and use angular or any other client-side rendering framework for that. Thymeleaf with REST is not the approach.
But if you want to use both ways like provide data to Thymeleaf and also provide REST services to other application follow below approach.
#RequestMapping('/foobars')
abstract class FoobarBaseController {
#RequestMapping
abstract listAll()
}
#Controller
class FoobarHtmlController extends FoobarBaseController {
#Override ModelAndView listAll() {
new ModelAndView('foobars/foobarThymeleafTemplate', [foobars: foobarsList])
}
}
#RestController
#RequestMapping('/foobars', produces = MediaType.APPLICATION_JSON_VALUE)
class FoobarJsonController extends FoobarBaseController {
#Override Collection<Foobar> listAll() {
foobarsList
}
}
I hope this address your question properly.

How do I add API Endpoints in ASP.NET?

I would like to register API Endpoints in ASP.NET by just adding few methods in ApiController. A new method there means a new API.
In a random example below:
public class ProductController : ApiController
needs to serve the following Endpoints:
/
/price
/price/discount
Problem here is all endpoints are having a GET request to /, and result in same output as /.
Reference URL and Service Contract
You can place Route annotation at method for which you want to use custom route.
public class CustomersController : ApiController
{
// this will be called on GET /Customers or api/Customers can't remember what default
//config is
public List<Customer> GetCustomers()
{
...
}
// this will be called on GET /My/Route/Customers
[HttpGet, Route("My/Route/Customers)]
public List<Customer> GetCustomersFromMyRoute()
{
...
}
}

Tomcat+Spring boot redirect ignoring contextPath

I'am using Spring boot and Tomcat7 to build a vehicle management system.
The base path is localhost:8080/vehicle
My server setting:
server.contextPath=/vehicle
My IndexController:
#RequestMapping("/")
public class IndexController extends BaseController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Model model) {
return "redirect:/login";
}
}
But when I go straight to get this view, my path is ...../login instead of ..../vehicle/login And so it returns 404 Error.
Also when I tried to use return "redirect:/vehicle/login"; it still goes to ...../login.
So what is wrong with my code. Why the server can't recognize the contextPath.
In application.properties use : server.servlet.context-path=/contextPath.
Example:
server.servlet.context-path=/vehicle
Tomcat Server:
In the webapps folder, the context path(vehicle) must be the same as the folder name(vehicle).

How to use send.redirect() while working with Spring MVC

I was trying to redirect to a dynamic page from Interceptors and Handler Mapping program. I have already defined a controller which handles and redirects (/hello.htm) through model (I have only this controller in my program). Until this point it is working fine. Apart from this, I registered a handler which will redirect to a page once it satisfies some condition.
public class WorkingHoursInterceptor extends HandlerInterceptorAdapter {
#Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("In Working Hours Interceptor-pre");
Calendar c=Calendar.getInstance();
if(c.get(Calendar.HOUR_OF_DAY)<10||c.get(Calendar.HOUR_OF_DAY)>20){
response.sendRedirect("/WEB-INF/jsp/failure.jsp");
return false;
}
return true;
..............
..............
}
But once it comes to response.sendRedirect, it is showing resource not found even though the mentioned page is present. I tried to redirect to "WEB-INF/jsp/hello.jsp" as well but keeps showing the same error. If the condition in the interceptor is not satisfied, the program works fine.
Below is shown the only controller present in the program.
#Controller
public class MyController {
#RequestMapping("/hello.htm")
public ModelAndView sayGreeting(){
String msg="Hi, Welcome to Spring MVC 3.2";
return new ModelAndView("WEB-INF/jsp/hello.jsp","message",msg);
}
}
(The controller for handling hello.html works fine if I change the interceptor condition)
Instead of redirecting, if I just print a message in the console, the program works fine. But once it comes to redirect it shows the error. Do I need to specify a separate controller to handle this request? Will this redirection request go to the dispatcher-servlet?
You need to add redirect: prefix in the view name, the code for redirect will look like:
#RequestMapping(value = "/redirect", method = RequestMethod.GET)
public String redirect() {
return "redirect:finalPage";
}
OR
#RequestMapping(value = "/redirect", method = RequestMethod.GET)
public ModelAndView redirect() {
return new ModelAndView("redirect:finalPage");
}
You may get a detail description from here:
enter link description here

How to call one controller to another controller URL in Spring MVC?

Hi I am new to Spring MVC ,I want to call method from one controller to another controller ,how can I do that .please check my code below
#Controller
#RequestMapping(value="/getUser")
#ResponseBody
public User getUser()
{
User u = new User();
//Here my dao method is activated and I wil get some userobject
return u;
}
#Controller
#RequestMapping(value="/updatePSWD")
#ResponseBody
public String updatePswd()
{
here I want to call above controller method and
I want to update that user password here.
how can I do that
return "";
}
any one help me .
Can do like this:
#Autowired
private MyOtherController otherController;
#RequestMapping(value = "/...", method = ...)
#ResponseBody
public String post(#PathVariable String userId, HttpServletRequest request) {
return otherController.post(userId, request);
}
You never have to put business logic into the controller, and less business logic related with database, the transactionals class/methods should be in the service layer. But if you need to redirect to another controller method use redirect
#RequestMapping(value="/updatePSWD")
#ResponseBody
public String updatePswd()
{
return "redirect:/getUser.do";
}
A controller class is a Java class like any other. Although Spring does clever magic for you, using reflection to examine the annotations, your code can call methods just as normal Java code:
public String updatePasswd()
{
User u = getUser();
// manipulate u here
return u;
}
You should place method getUser in a service (example UserService class) .
In the getUser controller, you call method getUser in the Service to get the User
Similarly, in the updatePswd controller, you call method getUser in the Service ,too
Here no need to add #reponseBody annotation as your redirecting to another controller
Your code will look like
#Controller
class ControlloerClass{
#RequestMapping(value="/getUser",method = RequestMethod.GET)
#ResponseBody
public User getUser(){
User u = new User();
//Here my dao method is activated and I wil get some userobject
return u;
}
#RequestMapping(value="/updatePSWD",method = RequestMethod.GET)
public String updatePswd(){
//update your user password
return "redirect:/getUser";
}
}

Resources