I want to handle all the address which I didn't make a specific function for.
For example,
@GetMapping({"/"}) // handles "/"
public String main(Model model) {
return "homepage";
}
@GetMapping({"/admin"}) // handles "/admin"
public String main(Model model) {
return "admin";
}
How can I handle all the other address, such as "/asdf" etc and send them all to a specific page? Thanks!
CodePudding user response:
Something like this could help you:
@GetMapping("/{whatever}")
public void xxx(@PathVariable String whatever) {
// Do things
}
CodePudding user response:
@RequestMapping(value="*", method = RequestMethod.GET)
public String fallback(){
return "specific-page";
}
Just make sure that this is your last RequestMapping, I remember that in node.js it has weird results until it was placed on the bottom of the class, so just to be safe, but it on the bottom as well in your java class.
CodePudding user response:
You can use @PathVariable for this.
@GetMapping("/{var}") // handles any string you can pass
public String main(@PathVariable(value="var",required=true)String var) {
return "anyString";
}
CodePudding user response:
Another option is to write custom exception handler, where you will place logic that will execute when user tries to go to path that doesn't exist.
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.servlet.http.HttpServletRequest;
import java.util.logging.Level;
import java.util.logging.Logger;
@RestControllerAdvice
public class ExceptionHandlerAOP {
@ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest request, Exception e) {
// when some other exception occures, you can handle it here..
}
@ExceptionHandler(NoHandlerFoundException.class)
public ModelAndView handleError404(HttpServletRequest request, Exception e) {
//do whatever you want, return some page..
}
}
CodePudding user response:
Yes, you can use wildcards like this
@GetMapping("/**")
public String handle() {
return handleException(exception, "404");
}
but I think it is more elegant to catch it as a 404 error and then you can continue as you like
@ExceptionHandler(NoHandlerFoundException.class){
public ModelAndView handlePageNotFoundException(final Exception exception) {
return handleException(exception, "404");
}