Go a page instead of opening a new tab - spring-boot

I use thymeleaf, in a spring boot program
When an user click this link i want to goto a page
<td><a th:href="#{/editings/testament/} + ${testament.id}" target="_blank" rel="noopener noreferrer"><i class="bi bi-pencil-square"></i></a></td>
In my controller I have
#PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_USER') ")
#GetMapping(value = "/editings/testament/{testamentId}")
public String editTestament(Model model, #PathVariable Long testamentId) throws Exception {
....
model.addAttribute("testamentId", testament.getId());
model.addAttribute("testamentDocument", testament.getTestamentDocument());
...
return "starter";
}
Actually when User click the link that open another tab with the starter page...
How to avoid that

So the reason that the page is opening in a new tab is because of the target="_blank" attribute present on the a tag.
If you remove this, you should be all set. The controller shouldn't need to be edited to make this happen. Here is a resource to read more: https://www.w3schools.com/tags/att_a_target.asp
Hope you're having a good day!

Related

thymeleaf doesn't update a model value in my template after a post

I have a session attribute called
#SessionAttributes("myNewAttribute")
which is defined at the top of my controller. when I hit my second endpoint, the post, the value does not update in thymleaf from blank to showing the string but it does print it to my console. I'm going a little crazy. Here is my controller file and my template:
#Controller
#SessionAttributes("myNewAttribute")
public class SpringFileController {
#GetMapping("/pageone")
public String displayPageOne(Model model) {
return "pageone";
}
#PostMapping("/clickedsavebutton")
public String handleSaveButton(Model model){
model.addAttribute("myNewAttribute","catnip");
String valueToDisplay = (String)model.getAttribute("myNewAttribute");
System.out.println(valueToDisplay);
return "pageone";
}
}
my template
<p th:text="${myNewAttribute}"></p>
<!--the save button, other things, wtc.. -->
So in my console when I click save I get "catnip" but "catnip" is not displayed on the page UNTIL I refresh the page. What am I doing wrong
edit: I added window.location.reload() after my post call in my template which makes the attribute show, but I lose other things on the page that have been changed if I do it this way
This is expected behavior, Thymeleaf is a rendering engine and as such can not change things after the initial load of the page.
To get the desired effect you'd have to reload (part) of your web page. this can be either a complete refresh or refreshing a div or field using something like ajax/javascript.
I added
$( "#required-field-div" ).load(window.location.href + " #required-field-div" );
to my function on the save button and got this to work. thank you for all the help!

How to reload a JSP page only under a certain condition in Spring MVC

I have a situation where i have to use a JSP page to create a sophiticated Javascript graph, the graph is drawn by the user when the page is loaded by the controller on a link click:
#RequestMapping(value = "/page1", method = RequestMethod.GET)
public String showPag1e(HttpServletRequest request, HttpServletResponse response) throws IOException {
return "/app/page1";
}
Where the Jsp link is as follows:
<a id="openPage1" class="nav-link" href="/page1">
Now when i move to a certain page2 (mechanism defined as above) and return to page1 all of the graph and the drawing are gone and the page is reloaded.
I saw that one solution is to send back and forth the data using #RequestBody, but is there a simpler solution in Spring MVC where the page is untouched and the route is updated when requesting the page, specifically, is there a solution to conditionnally return "/app/page1" ?(only if it doesn't contain prior data on the JSP page) or maybe just rendering the previous JSP using JQuery/JS?
Thanks for the enlightenment

Browser tabs show other title than exected, how to set tab title in responseEntity

I've created a controller in my spring-boot application to return files stored in my database. This works and when retrieving a pdf-file, this is shown within my browser. I've set the filename as a header in the responseEntity. However, Chrome and Edge are showing me the ID of the file as tab title. How to manipulate what there is shown?
My controller:
#GetMapping("/{id}")
public ResponseEntity<byte[]> getAttachmentById(#PathVariable Long id) {
Attachment attachment = attachmentService.getAttachmentById(id);
HttpHeaders headers = new HttpHeaders();
headers.add("content-disposition", "inline;filename=" + attachment.getAttachmentName());
headers.setContentType(MediaType.valueOf(attachment.getAttachmentType()));
return ResponseEntity.ok().headers(headers).body(attachment.getAttachmentFile());
}
My front-end is built with vue. I show the link with the following code:
<template #item.attachment="{ item: test }">
<a target="_blank" :href="test.attachmentUri">
{{ test.attachmentName }}
</a>
I doubt the front-end has anything to do with the issue as opening the link directly in any browser shows the same result.

laravel backup raising 404 to return a view

In short what is happening is, when I try to access a route, Laravel shows a 404 error, with a short description "Page not Found, No query results for model [App\Models\Product] teste ".
Inside of my model I have the method "teste" which invokes a route.
public function teste($crud = false)
{
return '<a class="btn btn-xs btn-default" href="product/teste" data-toggle="tooltip" title="Just a demo custom button."><i class="fa fa-search"></i> Add Item</a>';
}
button image in the datatable line
Adding a button inside of ProductCrudController
$this->crud->addButton('top', 'bteste', 'model_function', 'teste', 'beginning');
Inside of custom.php I have tried already:
CRUD::resource('product/teste', 'ProductCrudController#teste');
Route::get('product/teste', 'ProductCrudController#teste');
Inside of my Controller I have my method named teste
public function teste(){
return view('vendor/backpack/crud/teste');
}
And finally inside of this path I have my view "which is pretty simple" and only retues a simple hello.
What is the purpose
I need to build a form which allows the user to add "a component" for the product once that the product is always customized. This means, a combination of components makes up a new product.
What I need is: Add a new button in the product line which when clicked gonna redirect the user to add all components which makes up this product. Same idea of an order which contain items.
I could not find by myself the possible options to fit my need.
Is that possible to be done by backpack? If so is there any example to be followed?
Thanks

How to create a dynamic link with Thymeleaf and Spring Boot?

so I've been making a "website" hosted on my computer with Thymeleaf and Spring Boot, and I have a basic, insecure login that I made for fun. What I'm currently trying to do is to make a link that brings you back to a previous page based, which is sent in as a String through the model.
Here are a few snippets:
In the controller:
#RequestMapping("/")
public String index(Model model) {
return ifLoggedIn(model, "home", "");
}
private String ifLoggedIn (Model model, String location, String returnTo) {
if (Login.loggedIn.getOrDefault(Login.IP(), Boolean.FALSE)) {
return location;
} else {
model.addAttribute("login", new Login());
model.addAttribute("return_page", returnTo);
return "login";
}
}
In the loggedin.html file (After you log in successfully):
<body>
<a th:href="'/' + ${return_page}">Return to previous location</a>
</body>
EDIT:
I first change the line in the loggedin.html file to follow what Pau recommended:
<a th:href="#{'/' + ${return}}">Return to previous location</a>
But I kept getting redirected to server.local/null, so I tried removing the '/' + and having the / inside the ifLoggedIn parameters, so it would be return ifLoggedIn(model, "home", "/", but that also kept sending me to server.local/null. Now, I just changed the line in the loggedin.html file to the following:
<a th:if="(${return_page} != null)" th:with="return=(${return_page})" th:href="#{${return}}">Return to previous location</a>
Now it just disappears, meaning that ${return_page} is equal to null. Looking back at the controller I don't understand why it returns null. Another thing, I am redirecting back to other pages as well, with one line saying return ifLoggedIn(model, "messages", "/messages", but even with those I still get sent to server.local/null.
You need to use link expressions using #{...} which is a type of Thymeleaf Standard Epression. In the official doc you can see a lot of examples using expressions inside your link expressions in section 9. Using expressions in URLs:
http://www.thymeleaf.org/doc/articles/standardurlsyntax.html
No problem! Every URL parameter value is in fact an expression, so you can easily substitute your literals with any other expressions, including i18n, conditionals…:
....
the URL base itself can be specified as an expression, for example a variable expression:
<a th:href="#{${detailsURL}(id=${order.id})}">
Furthermore, in the tutorial there is a expressions which is similar as yours, in the section 4.4 Link URLs:
URL bases can also be the result of evaluating another expression:
...
<a th:href="#{'/details/'+${user.login}(orderId=${o.id})}">view</a>
So in your case, it would be like next:
<body>
<a th:href="#{'/' + ${return_page}}">Return to previous location</a>
</body>
You can Use This:
Controller
#GetMapping("/userLogin/{userId}")
public String getUserDetailsById(#PathVariable("userId") int userId, Model model){
return "user/userDetails";
}
HTML
<body>
<a th:href="#{/userLogin/{userId}(userId=${user.userId})}"></a>
</body>
<body>
<a th:href="#{'/' + return_page}">Return to previous location</a>
</body>
This works for me
For e.g. here you want to pass the dynamic value of port from your controller then do like this:-
<a th:href="#{http://localhost:{port}/index.html(post=${serverPort})}">Click here</a>

Resources