An issue in loading a Thymeleaf fragment inside the controller, the fragment name is being returned - spring-boot

Trying to manipulate a Thymeleaf fragment inside a Java Spring Boot Controller.
According to the link, in order to load the content of the Thymeleaf fragment inside the controller, all we need to do is the following
return "fragments/customerSearch :: customersTable";
While in my case, the following script results in only the String: "fragments/customerSearch :: customersTable" returned:
private String getDocumentsByTransaction(Transaction transaction) {
return "fragments/block-document :: popup(transaction)";
}
inside another function:
...
String documents = getDocumentsByTransaction(transaction);
...
Is there anything missing to load the content of the fragment instead of the fragment name as a static string?

return "fragments/customerSearch :: customersTable"; only works if the method is actually a controller method, and you're going through the entire MVC process.
In your example case, it should look like this:
#Controller
public class WhateverController {
#GetMapping("/page")
private String getDocumentsByTransaction() {
return "fragments/block-document :: popup";
}
}
Now if you access /page in your browser, it will return a fragment rather than an entire page. You also can't just call getDocumentsByTransaction() in your java... There is a lot of spring happening in the background. If you really wanted to do something like that, you'd have to make an http request in your java.

Related

Can I transform the input of a json inside a spring boot controller?

I have a very simple spring boot web application which consumes requests with json body.
For each json which the application will receive (from any client) I would like to manipulate it as a first step.
For example if the client sends the following body:
{
"hello": "world!!!"
}
I would like to replace each ! with a ?. In this case the result is:
{
"hello": "world???"
}
This json transformation should be valid for each controller and for any json entering the system.
Is this kind of operation possible?
Thanks.
You may use string.replace to do the same.
Or also you can add custom annotation to manipulate the values of any keys.
You can use any replacement methods or regex in your classes.
#GetMapping
public String replace(RequestItem item){
// item = item.regex/replacement method
// call your service or whatever
return item;
}
When you got the data, you can do whatever you want to do.

I want to assign Object field eg. greeting.method (which can be post or get ) to Form Method attribute using thymeleaf spring boot

Generally the code is -->
Image of code, click here to see the code!
I want that method which is hardcoded as "post" need to come from greeting object eg. (greeting.method)
How can I achieve that any suggestions?
So just to make it clear, you want to read the url action and method from a variable, instead of hardcoding them in thymeleaf
In that case that is actually very simple:
Pass url and method variables to the model by defining the following in your controller
#ModelAttribute("url") public String url() { return "foo/bar"; }
#ModelAttribute("method") public String method() { return "POST"; }
Define the url and method with thymeleaf: <form th:action="${url}" th:method="${method}" ...>

How do I return a template(thymeleaf) in spring boot and resolve it to a particular endpoint

Short: I want to use Thymeleaf template index.html but have the url point to thanks.html.
In depth: I am trying to have a form submission take my user to a page http://localhost:8080/thanks.html. I dont want the action of the form to be thanks.html for a few different reasons but I have greatly simplified the logic below. When all of the validation of the form are passed, I want to pass in a variable to indicate which layout to use. I have that working by using a model variable called contentPage. The problem is that if i have "return "thanks.html";" in the indexSubmit Method I get an error from thymeleaf saying template not found. If I change that to "return "index.html"; everything works but the url is http://localhost:8080/ instead of http://localhost:8080/thanks.html.
#PostMapping("/")
public String indexSubmit(Model model) {
model.asMap().clear();
model.addAttribute("contentPage","layout/thanks.html");
return "thanks.html";
}
#GetMapping("/thanks.html")
public String thanks(Model model) {
model.addAttribute("contentPage","layout/thanks.html");
return "index.html";
}
I fond an answer on my own:
return "redirect:thanks.html";
Thanks,
Brian

Best Practice of reading text file in spring mvc

What is the best way to read HTML content from a text file and display the content in JSP? I have placed the text file in the resource folder using spring mvc 3. Normally I do this kind of stuff with Apache commons in struts but believe spring must have provided some utility for this.
I am thinking about reading it in a tag file. What utility should i use for that?
Ignoring the question of why you would want to do this. The return value from a Spring MVC controller method is usually used to resolve a view. The resolved view then becomes the response body. However, you can use the #ResponseBody annotation to make the raw return value the response body.
You can do it in the #RequestMapping method. The Key is the return type ModelAndView.
You read your text file and get the html that you need, after this, adding the html to the model and then return the a new ModelAndView Object.
Here's a sample:
#RequestMapping(value = "siteWithResHtml", method = RequestMethod.GET)
public ModelAndView loadSiteWithResHtml(Model model)
{
String resourceHtml;
// do your stuff for reading file and assign it to the String
model.addAttribute("resource_Html", resourceHtml);
return new ModelAndView("yourJSP", "model", model);
}
and in the jsp you can read the value from the model that you forwarded to the jsp, like this:
<div>${model.resource_Html}</div>
please take notice that the names are match.

Spring controller, why is the returned view ignored?

So, say I have an existing, working page Display Cashier, which displays information about a cashier in a shop. Now, I add a button to this page that looks like:
Manager
The request-mapping for this URL maps it (successfully) to a controller: HandleGetManager
the HandleGetManager controller looks like this:
#Controller
public class HandleGetManager{
private employeeBO employeeBO; //BO handles all business logic
//spring hooks
public HandleGetManager(){}
public void setemployeeBo(employeeBO employeeBO){
this.employeeBO = employeeBO;
}
//get controller
#RequestMapping(method=RequestMethod.GET)
public String getManager(#RequestParam String cashierId){
Long managerId = employeeBO.getManagerByCashierId(cashierId);
String redirectUrl = "/displayManager.ctl?managerId=" + managerId.toString();
return redirectUrl;
}
}
Here's what happens when I try it:
I hit the new button on the Display Cashier page, I expect the following to happen:
The browser sends a get request to the indicated URL
The spring request-mapping ensures that the flow of control is passed to this class.
the #RequestMapping(method=RequestMethod.GET) piece ensures that this method is evoked
The #RequestParam String cashierId instructs Spring to parse the URL and pass the cashierId value into this method as a parameter.
The EmployeeBo has been injected into the controller via spring.
The Business logic takes place, envoking the BO and the managerId var is populated with the correct value.
The method returns the name of a different view, with a new managerId URL arg appended
Now, up until this point, everything goes to plan. What I expect to happen next is:
the browsers is directed to that URL
whereupon it will send a get request to that url,
the whole process will start again in another controller, with a different URL and a different URL arg.
instead what happens is:
this controller returns the name of a different view
The browser is redirected to a half-right, half wrong URL: handleGetManager.ctl?managerId=12345
The URL argument changes, but the name of the controller does not, despite my explicitly returning it
I get an error
What am I doing wrong? Have I missed something?
Assuming you have a UrlBasedViewResolver in your MVC configuration, the String value you return is a View name. The ViewResolver will take that name and try to resolve a View for it.
What you seem to want to do is to have a 301 response with a redirect. With view names, you do that by specifying a redirect: prefix in your view name. It's described in the documentation, here.
Here's a question/answer explaining all the (default) ways you can perform a redirect:
How can I prevent Spring MVC from doing a redirect?

Resources