Serving static content alongside thymeleaf templates with Spring Boot - spring

I'm having trouble sonfiguring Spring Boot to use thymeleaf and still serve static content. I have two directories in my resources dir: "/static" and "/templates". According to the Spring Boot documentation, thymeleaf should find thymeleaf templates in the templates directory by default. I am getting a 404 though when I try to use a template.
Relevant code from my Controller:
#RequestMapping("/")
public ModelAndView index() {
return new ModelAndView("index.html");
}
#RequestMapping(value = "/test")
public ModelAndView test() {
return new ModelAndView("test");
}
index.html is in resources/static and test.html is in resources/templates.
index.html works fine, but if you try to open /test in your browser, it throws a 404 saying that the thymeleaf template could not be found.
I really appreciate any help. I'm stumped.

Any pages that are not going through the ThymeleafViewResolver(your /resources/static) need to be removed.
/**
* Configures a {#link ThymeleafViewResolver}
*
* #return the configured {#code ThymeleafViewResolver}
*/
#Bean
public ThymeleafViewResolver thymeleafViewResolver()
{
String[] excludedViews = new String[]{
"/resources/static/*"};
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setOrder(1);
/*
* This is how we get around Thymeleaf view resolvers throwing an error instead of returning
* of null and allowing the next view resolver in the {#see
* DispatcherServlet#resolveViewName(String, Map<String, Object>, Locale,
* HttpServletRequest)} to resolve the view.
*/
resolver.setExcludedViewNames(excludedViews);
return resolver;
}

Have you tried just returning the String name of the template and not ModelAndview?
And have your ModelAttributes annotated as indicated in the documentation?

Related

spring Ausing double-slashes in URLs

I'm trying migration spring 4.0.7.RELEASE mvc project to webFlux,but old project definition url /getData/api/test,use /getData//api/test can request success,but in webFlux whether use Controller or FunctionType it`s response 404 notFound。How can I make it compatible old spring?
useController
#PostMapping("/getData/api/test")
public Object getData(#RequestBody Person person) {
log.info("received");
return "<html>hello</html>";
}
use function
#Bean
public RouterFunction<ServerResponse> timeRouter() {
return route().POST("/getData/api/test", timeHandler::getCurrentTime)
.build();
}

spring boot override default REST exception handler

I am not able to override default spring boot error response in REST api. I have following code
#ControllerAdvice
#Controller
class ExceptionHandlerCtrl {
#ResponseStatus(value=HttpStatus.UNPROCESSABLE_ENTITY, reason="Invalid data")
#ExceptionHandler(BusinessValidationException.class)
#ResponseBody
public ResponseEntity<BusinessValidationErrorVO> handleBusinessValidationException(BusinessValidationException exception){
BusinessValidationErrorVO vo = new BusinessValidationErrorVO()
vo.errors = exception.validationException
vo.msg = exception.message
def result = new ResponseEntity<>(vo, HttpStatus.UNPROCESSABLE_ENTITY);
result
}
Then in my REST api I am throwing this BusinessValidationException. This handler is called (I can see it in debugger) however I still got default spring boot REST error message. Is there a way to override and use default only as fallback? Spring Boot version 1.3.2 with groovy. Best Regards
Remove #ResponseStatus from your method. It creates an undesirable side effect and you don't need it, since you are setting HttpStatus.UNPROCESSABLE_ENTITY in your ResponseEntity.
From the JavaDoc on ResponseStatus:
Warning: when using this annotation on an exception class, or when setting the reason attribute of this annotation, the HttpServletResponse.sendError method will be used.
With HttpServletResponse.sendError, the response is considered complete and should not be written to any further. Furthermore, the Servlet container will typically write an HTML error page therefore making the use of a reason unsuitable for REST APIs. For such cases it is preferable to use a ResponseEntity as a return type and avoid the use of #ResponseStatus altogether.
I suggest you to read this question: Spring Boot REST service exception handling
There you can find some examples that explain how to combine ErrorController/ ControllerAdvice in order to catch any exception.
In particular check this answer:
https://stackoverflow.com/a/28903217/379906
You should probably remove the annotation #ResponseStatus from the method handleBusinessValidationException.
Another way that you have to rewrite the default error message is using a controller with the annotation #RequestMapping("/error"). The controller must implement the ErrorController interface.
This is the error controller that I use in my app.
#RestController
#RequestMapping("/error")
public class RestErrorController implements ErrorController
{
private final ErrorAttributes errorAttributes;
#Autowired
public MatemoErrorController(ErrorAttributes errorAttributes) {
Assert.notNull(errorAttributes, "ErrorAttributes must not be null");
this.errorAttributes = errorAttributes;
}
#Override
public String getErrorPath() {
return "/error";
}
#RequestMapping
public Map<String, Object> error(HttpServletRequest aRequest) {
return getErrorAttributes(aRequest, getTraceParameter(aRequest));
}
private boolean getTraceParameter(HttpServletRequest request) {
String parameter = request.getParameter("trace");
if (parameter == null) {
return false;
}
return !"false".equals(parameter.toLowerCase());
}
private Map<String, Object> getErrorAttributes(HttpServletRequest aRequest, boolean includeStackTrace)
{
RequestAttributes requestAttributes = new ServletRequestAttributes(aRequest);
return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace);
} }

Spring Social facebookConnected.jsp

After successful authentication facebook redirects to facebookConnected.jsp. I want it to be redirected to the home page instead. How can it be achieved? I tried doing with controller to redirect but didn't work well.
In ConnectController you got these methods
/**
* Returns the view name of a page to display for a provider when the user is connected to the provider.
* Typically this page would allow the user to disconnect from the provider.
* Defaults to "connect/{providerId}Connected". May be overridden to return a custom view name.
* #param providerId the ID of the provider to display the connection status for.
*/
protected String connectedView(String providerId) {
return getViewPath() + providerId + "Connected";
}
/**
* Returns a RedirectView with the URL to redirect to after a connection is created or deleted.
* Defaults to "/connect/{providerId}" relative to DispatcherServlet's path.
* May be overridden to handle custom redirection needs.
* #param providerId the ID of the provider for which a connection was created or deleted.
* #param request the NativeWebRequest used to access the servlet path when constructing the redirect path.
*/
protected RedirectView connectionStatusRedirect(String providerId, NativeWebRequest request) {
HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
String path = "/connect/" + providerId + getPathExtension(servletRequest);
if (prependServletPath(servletRequest)) {
path = servletRequest.getServletPath() + path;
}
return new RedirectView(path, true);
}
Concretely they say that methods could be overriden to get our specific redirect url. But honestly I don't know how overriding them. I guess you could create a new #Config class that extends it and override #RequestMapping("/connect") too.
If you know some way please write here because I'm on the same situation because I use Spring Webflow and I would like maintaining the flow.
In my case controller /WEB-INF/connect/facebookConnected.xhtml which throw Not Found in ExternalContext as a Resource because I configured my app to look for on folder /WEB-INF/flows.
I had the same problem and I fixed the issue by overriding the ConnectController class
#Controller
#RequestMapping("/connect")
public class CustomController extends ConnectController {
public CustomController(ConnectionFactoryLocator connectionFactoryLocator,
ConnectionRepository connectionRepository) {
super(connectionFactoryLocator, connectionRepository);
}
#Override
protected String connectedView(String providerId) {
return "redirect:/facebook";
}
}
This link has more explanation about how to change the default spring social redirect flow .

Passing data in the body of a DELETE request

I have two Spring MVC controller methods. Both receive the same data in the request body (in the format of an HTLM POST form: version=3&name=product1&id=2), but one method handles PUT requests and another DELETE:
#RequestMapping(value = "ajax/products/{id}", method = RequestMethod.PUT)
#ResponseBody
public MyResponse updateProduct(Product product, #PathVariable("id") int productId) {
//...
}
#RequestMapping(value = "ajax/products/{id}", method = RequestMethod.DELETE)
#ResponseBody
public MyResponse updateProduct(Product product, #PathVariable("id") int productId) {
//...
}
In the first method, all fields of the product argument are correctly initialised. In the second, only the id field is initialised. Other fields are null or 0. (id is, probably, initialised because of the id path variable).
I can see that the HttpServletRequest object contains values for all fields in the request body (version=3&name=product1&id=2). They just are not mapped to the fields of the product parameter.
How can I make the second method work?
I also tried to use the #RequestParam annotated parameters. In the method that handles PUT requests, it works. In the DELETE method, I get an exception: org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'version' is not present.
I need to pass data in the body of DELETE requests because the data contain a row version which is used for optimistic locking.
The problem is not a Spring problem, but a Tomcat problem.
By default, Tomcat will only parse arguments that are in the form style, when the HTTP method is POST (at least for version 7.0.54 that I checked but it's probably the same for all Tomcat 7 versions).
In order to be able to handle DELETE methods as well you need to set the parseBodyMethods attribute of the Tomcat Connector. The connector configuration is done in server.xml.
Your updated connector would most likely look like:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
parseBodyMethods="POST,PUT,DELETE"
URIEncoding="UTF-8" />
Here is documentation page for configuring Tomcat connectors.
Once you setup Tomcat to parse the parameters, Spring will work just fine (although in your case you will probably need to remove #RequestBody from the controller method)
You can try adding the annotation #RequestBody to your Product argument.
But if you just need to pass version information, using a request param is more appropriate.
So add a new argument in your delete method #RequestParam("version") int version, and when calling the delete method pass a query param like ..ajax/products/123?version=1
As you said request param is not working for you in delete, can you post the exact url you used and the method signature ?
Spring boot 1.5.*
#Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() {
return new TomcatEmbeddedServletContainerFactory(){
#Override
protected void customizeConnector(Connector connector) {
super.customizeConnector(connector);
connector.setParseBodyMethods("POST,PUT,DELETE");
}
};
}
Passing data in the body of a DELETE request
#Component
public class CustomiseTomcat implements WebServerFactoryCustomizer {
#Override
public void customize(TomcatServletWebServerFactory factory) {
factory.addConnectorCustomizers( new TomcatConnectorCustomizer() {
#Override
public void customize(Connector connector) {
connector.setParseBodyMethods("POST,PUT,DELETE");
}
});
}
}
for spring boot 2.0+ :
#Bean
public TomcatServletWebServerFactory containerFactory() {
return new TomcatServletWebServerFactory() {
#Override
protected void customizeConnector(Connector connector) {
super.customizeConnector(connector);
connector.setParseBodyMethods("POST,PUT,DELETE");
}
};
}

Spring 3.0 RESTful Controller Fails on Redirect

I am setting up a simple RESTful controller for a Todo resource with an XML representation. It all works great - until I try to redirect. For example, when I POST a new Todo and attempt to redirect to its new URL (for example /todos/5, I get the following error:
Error 500 Unable to locate object to be marshalled in model: {}
I do know the POST worked because I can manually go to the new URL (/todos/5) and see the newly created resource. Its only when trying to redirect that I get the failure. I know in my example I could just return the newly created Todo object, but I have other cases where a redirect makes sense. The error looks like a marshaling problem, but like I said, it only rears itself when I add redirects to my RESTful methods, and does not occur if manually hitting the URL I am redirecting to.
A snippet of the code:
#Controller
#RequestMapping("/todos")
public class TodoController {
#RequestMapping(value="/{id}", method=GET)
public Todo getTodo(#PathVariable long id) {
return todoRepository.findById(id);
}
#RequestMapping(method=POST)
public String newTodo(#RequestBody Todo todo) {
todoRepository.save(todo); // generates and sets the ID on the todo object
return "redirect:/todos/" + todo.getId();
}
... more methods ...
public void setTodoRepository(TodoRepository todoRepository) {
this.todoRepository = todoRepository;
}
private TodoRepository todoRepository;
}
Can you spot what I am missing? I am suspecting it may have something to do with returning a redirect string - perhaps instead of it triggering a redirect it is actually being passed to the XML marshaling view used by my view resolver (not shown - but typical of all the online examples), and JAXB (the configured OXM tool) doesn't know what to do with it. Just a guess...
Thanks in advance.
This happend because redirect: prefix is handled by InternalResourceViewResolver (actually, by UrlBasedViewResolver). So, if you don't have InternalResourceViewResolver or your request doesn't get into it during view resolution process, redirect is not handled.
To solve it, you can either return a RedirectView from your controller method, or add a custom view resolver for handling redirects:
public class RedirectViewResolver implements ViewResolver, Ordered {
private int order = Integer.MIN_VALUE;
public View resolveViewName(String viewName, Locale arg1) throws Exception {
if (viewName.startsWith(UrlBasedViewResolver.REDIRECT_URL_PREFIX)) {
String redirectUrl = viewName.substring(UrlBasedViewResolver.REDIRECT_URL_PREFIX.length());
return new RedirectView(redirectUrl, true);
}
return null;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
}

Resources