Spring boot Call java method with Parameter from Thymeleaf - spring

i am using spring boot 2.7.3 with thymeleaf
i want to call java function from thymeleaf
for example the follwoing function i can call from html using [(${testfunction})
#ModelAttribute("testfunction")
public String test() {
return "test";
but i want to call a function with parameter
for example, how i can call this function from html
#ModelAttribute("testfunction")
public String test(String x) {
return "something";
}
i dont want to use static method

Related

Spring Boot redirect to another url

In my spring boot project i wanted to do a redirection from http://localhost:8080 to http://localhost:8080/birdspotting. This is the code of the Home controller:
#RestController
public class HomeController {
#GetMapping("/")
public String showHomePage() {
return "redirect:/birdspotting";
}
}
The result of going to http://localhost:8080 is a print of redirect:/birdspotting
Basically RestController = Controller + RequestBody
Which will send json response but we are expecting view resolver to return the page or redirect url.
So use #Controller instead of #RestController to fix the issue.
Update:
If you want to use both in Same controller then use #Controller on class level and then wherever you want to return API call response put #ResponseBody on method and wherever you want to return web browser page don't put #ResponseBody.
You have to create the other endpoint like:
#GetMapping("/")
public String showHomePage() {
return "redirect:/birdspotting";
}
#GetMapping("/birdspotting")
public String birdspottingPage() {
return "birdspotting";
}
It's expect you have birdspotting.html in your templates.

Spring Boot - mapping

In the code below there are two methods annotated with #GetMapping annotation, one expects empty path, another one expects a path variable.
#Controller
#RequestMapping("/")
public class BasicController {
#GetMapping()
public String get(Model model) {
// doing something
}
#GetMapping("/{variable}")
public String getWithPathVar(#PathVariable("variable") String variable, Model model) {
// doing something different
}
}
Problem: When the app is running and I hit "www.myurl.com/" it enters both methods even though there is no path parameter. How can I fix this?
If so it sounds like a bug or some misconfiguration with filters. I can't reproduce this behaviour on the Spring 5.2.7. Here's an article that explains how Spring works under the hood.
If you can't upgrade the Spring version you can use only single endpoint as a workaround.
#GetMapping("/{variable}")
public String getWithPathVar(#PathVariable("variable") String variable, Model model) {
// doing something different
if(variable != null) {
// fulfill the normal workflow
} else {
// call ex get() workflow
}
}

Thymeleaf + Spring MVC + Rest

I don't understand, how to change #Controller to #RestController for RESTFull serivce, if html template linked with attributes that I get in ModelAndView
#Controller
public class MyController{
#GetMapping("/index")
public ModelAndView index(){
return new ModelAndView("/index", name, userService.getUser().getName());
}
}
and in thymeleaf template it's look like
<p th:text="'Hello, ' + ${name} + '!'" />
But I wanna go to index page, and in background get user name
#RestController
public class MyController{
#GetMapping("/api/user")
public String index(){
return userService.getUser().getName();
}
}
I can use ajax for update tag "p", but in this way it's nothing benefit of using thymeleaf, I can use jsp. So what the best way use thymeleaf with rest and is it rational?
I think the purpose of Thymeleafis for server-side rendering.
Thymeleaf is a Java template engine for processing and creating HTML, XML, JavaScript, CSS, and text.
When you are using JSON API and parse the JSON and use angular or any other client-side rendering framework for that. Thymeleaf with REST is not the approach.
But if you want to use both ways like provide data to Thymeleaf and also provide REST services to other application follow below approach.
#RequestMapping('/foobars')
abstract class FoobarBaseController {
#RequestMapping
abstract listAll()
}
#Controller
class FoobarHtmlController extends FoobarBaseController {
#Override ModelAndView listAll() {
new ModelAndView('foobars/foobarThymeleafTemplate', [foobars: foobarsList])
}
}
#RestController
#RequestMapping('/foobars', produces = MediaType.APPLICATION_JSON_VALUE)
class FoobarJsonController extends FoobarBaseController {
#Override Collection<Foobar> listAll() {
foobarsList
}
}
I hope this address your question properly.

Expose public field of POJO to FTL in Spring

I can't figure out how to send a POJO to my template in Spring Boot.
Here's my POJO and my controller:
class DebugTest {
public String field = "Wooowee";
public String toString() {
return "testie " + field;
}
}
#Controller
#RequestMapping("/debug")
public class WebDebugController {
#RequestMapping(value = "/ftl", method = RequestMethod.GET)
public ModelAndView ftlTestPage(Model model) {
DebugTest test = new DebugTest();
ModelAndView mnv = new ModelAndView("debug");
mnv.addObject("test", test);
return mnv;
}
}
Here's my template:
HERES THE TEST: ${test}$
HERES THE TEST FIELD: ${test.field}$
Here's the output (GET /debug/ftl):
HERES THE TEST: testie Wooowee$
HERES THE TEST FIELD: FreeMarker template error (DEBUG mode; use RETHROW in production!):
The following has evaluated to null or missing:
==> test.field [in template "debug.ftl" at line 3, column 25]
[Java stack trace]
The class itself (DebugTest) must be public too, as per the JavaBeans Specification. Also, fields by default aren't exposed. Defining getter methods is generally the best (with Lombok maybe), but if you want to go with fields, configure the ObjectWrapper as such. As you are using Spring Boot, I think that will be something like this in your application.properites:
spring.freemarker.settings.objectWrapper=DefaultObjectWrapper(2.3.28, exposeFields = true)

spring-boot application displaying html code for view when executed in the browser

I am recently start to work with spring-boot in my spring projects, and right now I am facing this problem:
I have one spring-boot application with this main class:
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
and this controller:
#Controller
public class AcessoController {
#RequestMapping(value = "/signin")
public String signin(Model model) {
return "acesso/signin";
}
#RequestMapping(value = "/admin")
public String admin(Model model) {
return "private/admin";
}
#RequestMapping(value = "/index")
public String index(Model model) {
return "public/index";
}
}
when I run the application and try access the url mapping /signin, for example, the browser display the html code for this view, instead of the actual content.
What I am doing wrong here?
Are you trying to render a view using a template engine, or just return a static HTML file?
If you are trying to render a template, then you most likely do not have the right dependency in place to pull in a template engine. (Per your code, I believe this is what you are trying to do.) Even if you don't intend to use the template engine for templates, you will want one to render the HTML for you. Depending on your spring-boot setup, try starting with spring-boot-starter-web, or pull in Thymeleaf (spring-boot-starter-thymeleaf) or Freemarker (spring-boot-starter-freemarker) specifically.
If you want to simply return static content and do not want do custom configuration, you'll need to place the files in a certain location and do not need specific controller request mappings.
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-spring-mvc-static-content

Resources