Can I specify application path in #RequestMapping on controller? - spring

Can I use EL to specify my application context path on my Spring Controller using something like #RequestMapping("${pageContext.request.contextPath}")? Actually, I get an 404 error. So my question is how to map controller on context root?
I presume #RequestMapping("/") cannot do the job when app is not alone on the server, and url looks like:
http://localhost:8080/myapp/mypage
#Controller
#RequestMapping("${pageContext.request.contextPath}")
public class MainController {
#RequestMapping("/")
public ModelAndView index() {
}
}
PS: I've already added the app path prefix into every single url on my JSPs, like <form class="form-inline" role="form" action="${pageContext.request.contextPath}/search" method="post">. Now I need to make the same trick for my Spring Controllers to make it work when... wheather app deployed as ROOT app or as "just another app on this server".

you can add in the application.properties config file the root context path. That root context path will be the prefix path to all the controller paths.
application.properties
server.contextPath=/myapp/mypage
controller
#RequestMapping("/test")
Result:
http://localhost:8080/myapp/mypage/test

Related

Angular + Spring on same port

I deploy my angular project and add to resources/static in spring project, next I create simple controller:
#Controller
class IndexController {
#RequestMapping(value = "/")
fun index(): String {
return "index"
}
}
And now when I run tomcat and set url to localhost:8080/ everything work well I can click on buttons and browser redirect to proper site, But now if I refresh site or set diffrent url, my angular app stop working and I get 404 or spring endpoints. Question is, how I can set angular as default to load when I type diffrent url than this from controller
You need to separate your API endpoints context. For example /api/**. And then, define an endpoint with a regex, something like this ^/api (all other than /api) to resource path.

Configuring Default Spring Boot app to render HTML pages and CSS JS content

I configured a Basic Spring Boot app containing Hibernate. However, no page is being rendered.
I have places my pages in src/main/resources/templates/ and content(CSS and JS) in src/main/resources/static/
I have added Thymeleaf through Maven and written a basic controller to render my page -
#RestController
#RequestMapping("/testui")
public class GreetingController {
#RequestMapping("/greeting")
public String greeting(#RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}
}
Instead of rendering a page with my name, it is rendering the string - "greeting"
I have placed the greeting.html in templates file. What are the changes in application.properties I need to make to render pages (what keys and values must I give?)
Update - I somehow do not have the webapp folder. Added that. Created a folder called jsp and added a simple page. Referenced it - didnt work
Why is it not working?
Because you are using #RestController. #RestController is used to create API controllers which serve JSON/XML, whereas #Controller is used to create controllers which serve web content such as HTML.
Proposed solution
Replace #RestController with #Controller. For further details, please see the official Getting Started guide of Spring.
You've added #RestController on the Controller class, which means that you want all values returned by the controller methods to be considered as response body (that's the equivalent of annotating all controller methods with #ResponseBody).
Remove that annotation from the class and replace it with #Controller and you should get the expected result.

Spring Boot: How to serve two different HTML files to two different mappings?

I am pretty new to Spring Boot, and I saw that if I start a Spring Boot project and put an index.html file in the folder src/main/resources/static, then when I open my browser and go to address "localhost:8080", I'll see this file displayed in the browser.
Now, I have another html file (let's call it 'hello.html'), and I also placed it in src/main/resources/static. I wrote the following code:
#Configuration
#Controller
#EnableAutoConfiguration
#ComponentScan
public class TopicController {
#RequestMapping("/hello")
public String hello() {
return "hello.html";
}
}
As you can understand, I want that when I go to localhost:8000/hello, I'll see the display of 'hello.html' file.
However, I get the following error in the console:
javax.servlet.ServletException: Circular view path [hello.html]: would
dispatch back to the current handler URL [/hello.html] again. Check your
ViewResolver setup! (Hint: This may be the result of an unspecified
view, due to default view name generation.)
Do you know what I can do so I can get the hello.html file in the browser for accessing "localhost:8080/hello" ?

Configure index.html location in Spring initializr project

I created a Spring boot project using Spring initializr.
The project structure is below. /resources/client is the folder I added manually.
After I ran DemoApplication, I hit localhost:8080 and I saw the home page was pointed to /resources/index.html. I wanted to set the home page to be /resources/client/build/index.html, so I added something in application.properties:
spring.mvc.view.prefix=/resources/client/build/ ### also tried /client/build/
spring.mvc.view.suffix=.html.
However, it did not work and the home page was still pointed to /resources/index.html.
Also, The application is using dispatcherServlet but I did not find a dispatcherServlet file.
Is there any way I can use custom index.html location? Thanks.
Maybe you can try to add a HomeController using java code as following:
#Controller
public class HomeController {
#RequestMapping("/")
public String index() {
return "client/build/index.html";
}
}

Would someone answer some questions about Spring and Request Mapping?

I just started studying Spring, and I'm so confused.
I just created a new 'Spring Legacy Project' at STS. HomeController and home.jsp are there.
When I run it on server, it comes through the HomeController first, and arrives to home.jsp.
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
return "home";
}
What makes my project go through the HomeController at the beginning? Should I look at any xml file?
What does value="/" mean in #RequestMapping?
At the home.jsp, I made a button to go 'result.jsp'. From the 'result.jsp' I want to go back to home.jsp. but it doesn't work. What should I do?
<input type="button" value="뒤로 " onclick="javascript:location.href='/views/home.jsp'">
Why isn't this button working? Those two JSP files are in same place.
Your app is deployed to some app server, such as tomcat. The request <app server>/<context root> is handled by the app server to the .war with the appropriate context root, e.g. to your app. Your app uses Spring MVC, so it is Spring's RequestMappingHandlerMapping bean from your .war file that initially handles the request and finds your method that will handle this request. It does so by comparing the path in the request with the value of each method annotated with #RequestMapping.
The annotation #RequestMapping(value="/") of your home() method means that request <app server>/<context root> will be handled by your 'home()' method.
Any request from your JSP will go back to the Spring MVC that will try to map it to the appropriate controller method, i.e. to the method annotated by #RequestMapping with the appropriate path relative to the context root. So if your result.jsp just links to "/", it should bring you to the home() method and then to the home.jsp.

Resources