问题
I'm checking Thymeleaf with Spring these days. I came across a question on fragments. I've written a Spring controller using @Controller and there is a method @PostMapping below is the method
@PostMapping(value="/xxx/yyy/add",consumes="application/json",produces="application/json")
public @ResponseBody AModel addMethod(@Valid @RequestBody AModel aModel, BindingResult bindingResult)
I've used $.ajax method to POST data to /xxx/yyy/add URL. JSON is mapped ith the AModel object and it works. But I'm returning an AModel object as json response. Not a string mentioning the thymeleaf fragment. The thymeleaf fragment I'm trying to reload contains a table of data. Could someone point me at the right direction of how this could be done? thanks.
回答1:
Try this one.
@RequestMapping(value = "/abc", method = RequestMethod.GET, produces = "application/json")
private ResponseBody test( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse )
{
Response response = new Response<String>();
WebContext webContext = new WebContext( httpServletRequest, httpServletResponse, servletContext );
response.setData( generateTemplate( webContext, viewResolver, "fragmentpath") );
response.setMessage( "Success" );
response.setStatus(SUCCESS );
return response;
}
public static String generateTemplate( WebContext ctx, ViewResolver viewResolver, String baseTemplate)
{
TemplateEngine engine = ( ( ThymeleafViewResolver ) viewResolver ).getTemplateEngine();
String renderedHtml = engine.process( baseTemplate, ctx );
return renderedHtml;
}
来源:https://stackoverflow.com/questions/50481703/thymleaf-loading-fragments-using-jquery