Url Binding in SpringBoot - spring-boot

i have been strugling since 4 days but did not found the solution for how to bind the url in Spring Boot with gradle.
I have a url as, http://loalhost:8080/blog/post.html?pid=2&ptitle=abc
I want this url to be shown as below with html and (?),
http://localhost:8080/blog/post/2/abc
Is there any way to do that. I don't want to use tucky urlrewriter. All my html files are placed in webapp folder.
Thanks in Advance.

if your have a POST method in your #RestController to create a post blog:
#PostMapping("/blog/post/{pid}/{ptitle}")
public void create(#PathVariable("pid") String pid, #PathVariable("ptitle") String ptitle) {
// a repo save call
}
(I supposed that you use last spring boot version)

Related

Spring Boot - How to add custom controller logic before user accesses static files

I'm working on a Spring Boot project, where some static contents are served from the src/main/resources/static directory.
My goal is that whenever a user tries to access static contents that end with a certain suffix (e.g. ".xlsx"), the request is intercepted and I check to see if the user has the right permission using Spring AOP, and reject the request if necessary. I've got the AOP part working in other scenarios, but not in this scenario yet.
Currently I've tried something like the following, but the method isn't being invoked upon accessing a file of ".xlsx" suffix:
#RequestMapping("/*.xlsx")
public void checkPermission() {
}
Can this be done without using Spring Security? Thanks in advance.
Have you tried Filter interface? much more available.
LINK: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/filter/OncePerRequestFilter.html
Using this you can easily parse the request before even it reaches the controller and add you business logic/validation to it.

Spring: How can I keep routes in sync with URLs on the page?

How can I keep links in my UI templates (e.g. Thymeleaf templates) in sync with the corresponding request mappings in my Spring application?
I've seen that e.g. the Play framework uses the #router-Object within its templates. How is it solved by Spring?
One example:
Spring Controller - simple
#Controller
public class UserController {
#GetMapping("/users/{username}")
public String getUser(#PathParam String username) {
// do some stuff....
return "user";
}
}
HTML-Page
<body>
User details
</body>
Now I want to change "/users" to "/accounts". I'm pretty sure that I've got to update every html page by hand to update the link. Is there an easier solution for this?
As far as I know, there is no simple way to do this with built-in tools from Spring. However, I don't think that this would be too hard to build. You would need the following:
A YAML file with all of your URL templates defined
A Properties Spring bean that contains your URL mappings (read from the YAML file)
All of your #RequestMapping annotations would have to be prop values; i.e.
#GetMapping("${urls.users.byUsername}")
A custom tag that knows about the Properties bean and can create URLs from the templates that were defined in your YAML file.

Thymeleaf: can't load js and css when direct access the page

Updated: to describe the question more clearly
I create a web applicaiton with spring boot and thymeleaf, everything works fine if I open the login page, then login, then head for the management module or reports module sequently.
The proleam occurs when I type the url locahost:8080/send/kf/index(needs to authenticate, but I have open access to all in customized filter) in the browser, the page loads without js and css. In debug mode, I saw /send/kf was unexpectly put into the path like the following. I can get the resource if I access localhost:8080/assets/avatars/avatar.png.
The following is the folder structure I put my static resources. How could /send/kf automatically added into the url, please help me solve this problem. Thanks!
you can use spring.resources.static-locations in your application.properties file
spring.resources.static-locations=classpath:/resources/css/
spring.mvc.static-path-pattern=/resources/**
this is taken form documentation
Note:Static resources, like JavaScript or CSS, can easily be served from your Spring Boot application just be dropping them into the right place in the source code. By default Spring Boot serves static content from resources in the classpath at "/static" (or "/public")
Using /assets/ instead of assets/ fixes the issue, as otherwise it's a relative url that's supposed to get added to the end of existing url.
I find a solution for this question. I don't know how /send/kf is put into the url for the static resources, but I think if I put the controller mapping under the root path, this problem should avoid. As I think, the url is correct and resources can load successfully.
#Controller
public class ManualMessageController {
#Autowired
private MsgTemplateRepository msgTemplateRepository;
#RequestMapping("/manualMsg")
public String manualMsg(Model model){
model.addAttribute("msgTemplateList", msgTemplateRepository.findByStatus(1));
return "manualMessage";
}
}
updated:
The right solution is to use absolute path rather than relative path in the project. So change assets/css to /assets/css works.

generate sample example in swagger UI (in Spring boot project)

I am using a spring boot application and have configured using Swagger UI.
I want to know whether we could pre-populate the example value with sample value so we can hit the "Try it out!" button without having to type in some sample values to get a response.
It must be present there.
Is there a way we can do this using annotations or a separate file which Swagger uses?
I am using a spring boot project with springfox-swagger2:2.7.0 and springfox-swagger-ui:2.7.0 with dependencies added using gradle.
Since the #ApiParam properties example and examples are not working (see this issue on GitHub), support for adding examples is limited/non existing.
What you can do for simple parameters (#RequestParam) is to add the #ApiParam annotation with the defaultValue property, like this:
#GetMapping
public List<Foo> findAll(
#RequestParam(required = false)
#ApiParam(defaultValue = "foo") // Put the default value here
String input) {
// ...
}
However, there is no support yet for doing this with #RequestBody parameters.
A possible workaround for #RequestBody parameters is by clicking on the code box at the right side of the Swagger tester, where it says Example value. If you click on it, it will insert that example into the field itself.
Here is a workaround for providing an example:
Inject html into swagger
#ApiParam(
name="whatever",
value="whatever",
defaultValue="none</p><p>Example: xyz</p>"
)
They don't protect against it in the latest version 2.9.2.

Why my springboot app with freemarker doesn't work

I tried a springboot web application with freemarker.
In the bootstrap class there's a request-handling method:
#RequestMapping("/showAddPage")
String showAddPage(){
return "showAdd";
}
And i had my template, named "showAdd.ftl" ,lying in the directory of "resources/templates".
I also added freemarker's starter of springboot in pom.xml.
But when i request "localhost:8080/showAddPage", it retured a String, "showAdd", instead of the rendered content of the template "showAdd.ftl".
It doesn't render my showAdd.ftl.
Why could this happen?
I think you must add Servlet Mapping to your DispatcherServlet ;
There is one sample :
https://www.leveluplunch.com/java/tutorials/011-add-servlet-mapping-to-dispatcherservlet-spring-boot/
It would help you

Resources