ThymeLeaf: Cannot display view after calling endpoint - spring

I am trying to call a REST endpoint and then display a ThymeLeaf template:
The Endpoint:
#GetMapping("/devices")
public String getDeviceDetailU(Model model) {
List<FinalDevice> devices = deviceService.getAll();
model.addAttribute("devices", devices);
return "deviceList";
}
For the endpoint I tried returning /deviceList, /deviceList.html, deviceList.html.
Whenever I navigate to the endpoint, I simply get the string that was returned.
Here is the template:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<body>
Hello World!
</body>
</html>
While I understand, at this point, it will not display the list, I just want to be forwarded to the template.
If I go to localhost:8080/deviceType I display that template. This to me indicates it is not a security or configuration issue.
Any ideas?
This should all work according to this tutorial.

You probably have #RestController instead of just a #Controller.
If you want templates to be rendered you need to use #Controller. #RestController means that all your #Mappings simply serialize the return value and output it as json or xml (which is why you are seeing the string deviceList instead of the template).

Related

Spring Boot - how make different resources for different users

I am writing a spring boot application and have encountered the problem of sharing resources for different users. Simplified by example, it looks like this: there is one variable. You can assign a value to it through the form on the page. If the first user assigns the value hello java from one browser, then the second user will see the same value through another browser. I dont know how to make each user work with their own variable and their values do not overlap?
Controller:
#Controller
public class MessageController {
private String message;
#GetMapping(value = "/show_message")
public String showMessage(Model model){
model.addAttribute("message", message);
return "message";
}
#PostMapping(value = "set_message")
public String setMessage(#RequestParam(name = "newMessage") String newMessage){
message = newMessage;
return "redirect:/show_message";
}
}
html page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<p>Message value: <th:block th:utext="${message}"/></p>
<p>Enter a new message value</p>
<form method="POST" th:action="#{/set_message}">
<input type="text" name="newMessage"/>
<input type="submit" value="Send"/>
</form>
</body>
</html>
The rule of thumb is that controllers as well as services are not designed to maintain a state, particularly the client state.
Besides, Spring beans are by default singletons : they are shared among clients/requests. That explains the behavior that you notice.
To solve that issue you may use the in-memory HttpSession (old practice) but that is not advised any longer because it sticks the client/user to a specific server instance that has first served his request.
You should preferably either resend the data at each request (which may be cumbersome to do) or better store the data in an in-memory database such as Redis.
That is fast and it doesn't stick the client to a specific instance of your spring boot application.
With Spring, a good association with the in-memory database usage to handle the user state is using HttpSession but Spring Session backed to a database (Redis or another).
For how to use the Session with Spring MVC, you have that good post.

Spring Boot HTML page not rendering

I am in the process of learning Spring Boot and became unstuck when trying to post model data to an HTML file.
I have a controller, where I populate the model and call an HTML page from. When I put a breakpoint inside this method, the model data gets populated correctly, but the HTML page is rendered with only the name of the HTML file, and nothing else (no browser errors either). I am thinking it may have something to the with the file structure, and the fact that my RestController already has a path specified (because when I create a clean new controller with no explicit class-based #RequestMapping specified and call the template from the root path + name of HTML file, it renders correctly). I do have the ThymeLeaf dependency installed, and "userView.html" is placed inside the "template" directory.
ReaderController.java extract:
#RequestMapping("/reader")
public class ReaderController {
...
#RequestMapping(value = "/userView")
public String getUser(Model model) {
// business logic goes here
model.addAttribute("userName","Somebody");
model.addAttribute("url", "www.example.com");
return "userView";
}
userView.html extract:
<body>
<h1>User Data</h1>
<p th:text="'Username: ' + ${userName}"/>
<p th:text="'Url: ' + ${url}"/>
</body>
http://localhost:8080/reader/userView only renders the word "userView".
I found the solution to the issue. I inadvertently used the #RestController annotation instead of the #Controller annotation to the controller class. This link helps to explain the issue.

Ajax Thymeleaf Springboot

I'm trying to use ajax with thymeleaf. I designed a simple html page with two input field. I would like to use addEventHandler for the value of first input text, then I want to send it to controller and make calculation, after that I need to write it in same html form in the second field which returns from controller.
For example:
first input text value -> controller (make calculation) -> (write value) in second input text.
My html page is
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css'>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<input type="text" name="Thing" value=""/>
<script th:inline="javascript">
window.onload = function () {
/* event listener */
document.getElementsByName("Thing")[0].addEventListener('change', doThing);
/* function */
function doThing() {
var url = '#{/testurl}';
$("#fill").load(url);
alert('Horray! Someone wrote "' + this.value + '"!');
}
}
</script>
<!-- Results block -->
<div id="fill">
<p th:text="${responseMsg}"/></div>
</div>
</body>
</html>
My controller
#RequestMapping(value = "/testurl", method = RequestMethod.GET)
public String test(Model model) {
model.addAttribute("responseMsg","calcualted value")
return "test";
}
However I cannot call controller from ajax. Could you help me?
There are a few issues with your code. First of all, it looks like you're using the same template for both the initial loading of the application, and returning the calculated result.
You should split these two into different calls if you're using AJAX, since one of the goals of AJAX is that you don't need to reload an entire page for one change.
If you need to return a simple value, you should use a separate request method like this:
#GetMapping("/calculation")
#ResponseBody
public int multiply(#RequestParam int input) {
return input * 2; // The calculation
}
What's important to notice here is that I'm using #ResponseBody and that I'm sending the input to this method as a #RequestParam.
Since you will be returning the calculated value directly, you don't need the Model, nor the responseMsg. So you can remove that from your original request mapping.
You can also remove it from your <div id="fill">, since the goal of your code is to use AJAX to fill this element and not to use Thymeleaf. So you can just have an empty element:
<div id="fill">
</div>
Now, there are also a few issues with your Thymeleaf page. As far as I know, '#{/testurl}' is not the valid syntax for providing URLs. The proper syntax would be to use square brackets:
var url = [[#{/calculation}]];
You also have to make sure you change the url to point to the new request mapping. Additionally, this doesn't look as beautiful since it isn't valid JavaScript, the alternative way to write this is:
var url = /*[[ #{/calculation} ]]*/ null;
Now, your script has also a few issues. Since you're using $().load() you must make sure that you have jQuery loaded somewhere (this looks like jQuery syntax so I'm assuming you want to use jQuery).
You also have to send your input parameter somehow. To do that, you can use the event object that will be passed to the doThing() function, for example:
function doThing(evt) {
var url = [[#{/calculation}]];
$("#fill").load(url + '?input=' + evt.target.value);
alert('Horray! Someone wrote "' + this.value + '"!');
}
As you can see, I'm also adding the ?input=, which will allow you to send the passed value to the AJAX call.
Finally, using $().load() isn't the best way to work with AJAX calls unless you try to load partial HTML templates asynchronously. If you just want to load a value, you could use the following code in stead:
$.get({
url: /*[[ #{/calculation} ]]*/ null,
data: { input: evt.target.value }
}).then(function(result) {
$('#fill').text(result);
});
Be aware that $.get() can be cached by browsers (the same applies to $().load() though). So if the same input parameter can lead to different results, you want to use different HTTP methods (POST for example).

how to have a base layout in mustache for spring-boot?

Hi is there a way I can have a base layout, like in express for node, see here , when using mustache for spring boot? So that I could do:
base layout:
<html>
<body>
<p>Title</p>
{{{body}}} // or similar, not sure about #
</html>
and then use the Controller's returned view name as content to render a view, so the outside is always the same?
You can do this via Mustache lambda functions. With this tutorial I was able to achieve what you need: https://spring.io/blog/2016/11/21/the-joy-of-mustache-server-side-templates-for-the-jvm#layout-abstractions-using-a-lambda
Create a controller advice like this:
#ControllerAdvice
class LayoutAdvice {
#ModelAttribute("layout")
public Mustache.Lambda layout() {
return new Layout();
}
}
class Layout implements Mustache.Lambda {
String body;
#Override
public void execute(Fragment frag, Writer out) throws IOException {
body = frag.execute();
}
}
This will make a lambda function named "layout" accessible for your Mustache templates. The lambda function itself receives the fragment (which will be inside the layout tags, see below) and store it in the layout object's body field. This will be accessible from the layout template:
<html>
<body>
{{{layout.body}}}
</body>
</html>
The filename must be "layout.html" as we used #ModelAttribute("layout") above.
Then you can use your layout by calling the lambda function and passing a fragment which will be the body of your layout:
{{#layout}}
<h1>Demo</h1>
<div>Hello World</div>
{{/layout}}
{{>layout}}
It will produce the desired output:
<html>
<body>
<h1>Demo</h1>
<div>Hello World</div>
</body>
</html>

How to Return a View from a Controller to an iFrame

I am new to MVC 3 and have come accross the following scenario:
First let me explain how I have setup my application:
All post backs to the server use jquery ajax which which return a view from the controller that either appended or prepended or replace a targeted div.
The Scenario:
I have come to a point where I would like to upload images but unfortunately because of the jquery ajax posting I cannot get the values for an html in C# Request.Files. I know there are plugins out there to help out with this but I would like to do this myself so I have created an <iframe> which i then use a bit of javascript and post the form targeted to the iframe (old classic way of doing things):
function UploadImg(SACTION) {
alert(SACTION);
validatorform.action = SACTION;
validatorform.target = "fraImage";
validatorform.method = "POST";
validatorform.submit();
}
the SACTION parameter looks like this #Url.Action("UploadFile", "Response"). This all works well as it hits the controllers action method and I can then save the image:
[HttpPost]
public ActionResult UploadFile(string ArticleID)
{
ViewBag.PreviewImage = cFileUploads.UploadFile(ArticleID, Request.Files[0]);
return View("ImagePreview");
}
I would now like to return a view to the iframe (simply to preview the image and then do a couple of other things but this is besides the point)
The View for previewing the Image:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="">
<img alt="" src="#ViewBag.PreviewImage" />
</form>
</body>
</html>
The Problem:
Unfortunately when I return the View (ImagePreview.cshtml) in C# the whole page is refreshed, all I want is for the iFrame to be refreshed. How should I return the view from the controller?
Fiqured out the problem, I had a bit of javascript that was replacing the contents of a div that the iframe was sitting in ... (slap on my forehead). All working perfectly now :)
Will leave this question here just incase ..

Resources