Is there a way to set the displayed url of a page using Spring MVC ?
Let me be clearer with an example : I have the following controller :
#Controller
public class Display{
#RequestMapping(value = "myPage")
public ModelAndView display() {
ModelAndView result = new ModelAndView(Uris.MY_PAGE);
return result;
}
#RequestMapping(value = "myPage/revisited")
public ModelAndView accountManagement() {
ModelAndView result = new ModelAndView(Uris.ACCOUNT);
return display();
}
}
If I go on myPage/Revisited, I'll get the JSP associated to myPage. However, in my browser, the url will stay the same (myPage/revisited). How could I prevent that ?
To be more precise on what sam said, you can use UrlRewriteFilter, the installation process is explained in the link, then set a rule in the file urlrewrite.xml:
<rule match-type="wildcard">
<from>/myPage/revisited/redirect</from>
<to type="redirect">%{context-path}/myPage</to>
</rule>
And in your controller, just use what Emanuele said, i.e.
response.sendRedirect("redirect");
Related
I want to display the contents of the HTML page. But this returns the name of the web page. I tried using #controller and #Responsebody also using #RestController. Neither gives the contents of the page. Please help me to solve this problem. I'm trying to display vendors.html, but prints the name "vendors".
This is my code.
#Controller
#RequestMapping("/vendors")
public class VendorController {
#Autowired
private VendorService vendorService;
#RequestMapping("/indexVendor")
#ResponseBody
public String viewIndexVendor2(Model model) throws Exception {
List<Vendor> listVendor;
listVendor = vendorService.listAll();
model.addAttribute("listVendor", listVendor);
return "vendors";
}
}
thanks :)
#ResponseBody return the response of the method, in your case a String in the value is "vendors", so your request "/vendors/indexVendor" return "vendors". It is quite normal who should display "vendors".
To display the content of your "vendors.html" page, start by removing the #ResponseBody annotation and rename your page to "vendors.jsp" and configure a templating engine to handle jsp files or use themleaf.
I cannot access the templates I wrote under the templates folder. It will just redirect me to the Whitelabel Error Page. My structure is like this:my controller is under the src/main/java/com.project/controller/IndexController.java while my templates are under the src/main/resources/templates/home.html.My code in the controller is like this:
#Controller
public class IndexController {
#RequestMapping(path = {"/vm"}, method = {RequestMethod.GET})
public String template(Model model) {
return "home";
}
#RequestMapping(path = {"/index"}, method = {RequestMethod.GET})
#ResponseBody
public String index() {
return "Hello world";
}
}
And my home.html is like this:
<html>
<body>
<pre>
Hello World!
</pre>
</body>
</html>
I've solved the problem myself. The thing is the dependency. I did not import the spring-boot-starter-thymeleaf from org.springframework.boot. The dependency is really hard to deal with in Spring.
The default context path of the app would be "/" and there is neither index.html file is present nor a controller method for that path which is why you are seeing that White label Error Page. If you don't want to see that error, add the below property in your application.properties file then you would the HTTP 404 Error.
server.error.whitelabel.enabled=false
For the below method that you have in controller:
Annotation that indicates a method return value should be bound to the web response body.
#RequestMapping(path = {"/vm"}, method = {RequestMethod.GET})
public String template(Model model) {
return "home";
}
Go to http://localhost:8080/vm this would load the home.html file that you have in templates folder.
Whereas for this one:
#RequestMapping(path = {"/index"}, method = {RequestMethod.GET})
#ResponseBody
public String index() {
return "Hello world";
}
You have used the annotation #ResponseBody which would indicate a method that the return value should be bound to the web response body, so you would see the text Hello world in the browser when you hit the http://localhost:8080/index
I'm new to Spring. I'm trying to learn it by doing instead of reading. So I found some stuff which is confusing. But it works. I want to know why and how?
#Controller
#RequestMapping("/ok")
public class MyController {
#RequestMapping(value = "/ok", method = RequestMethod.GET)
public ModelAndView findAllAccounts() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("account");
mav.addObject("someText", "Listing all accounts!");
return mav;
}
#RequestMapping(value="/ok/{accountId}", method = RequestMethod.GET)
public ModelAndView findAccount(#PathVariable int accountId, Model model) {
ModelAndView mav = new ModelAndView();
mav.setViewName("account");
mav.addObject("someText", String.format("Showing account %d", accountId));
return mav;
}
}
For above code I found that.
working Get request url : http://localhost:8080/ok/
working Get request url : http://localhost:8080/ok/ok/888
But I was expecting url : http://localhost:8080/ok/ok/ should also work. But it doesn't work. Why? If http://localhost:8080/ok/ok/888 works why http://localhost:8080/ok/ok/ doesn't work?
Also when I deploy it in tomcat. It only works if named ROOT.war. If I change to XYZ.war, it doesn't work. Why?
The http://localhost:8080/ok/ok/ does not work as it treats your last ok as your accountId and it fails conversion to an integer. The best documenation is the javadoc
Your question about tomcat - I believe it should be fine with another name, only then you would have to access it as http://localhost:8008/XYZ/
I'm developing a simple web application using spring MVC and thymeleaf. I have a form correctly handled by this method in my controller
#RequestMapping(value = "/list", method = RequestMethod.POST)
public ModelAndView searchJob(
#ModelAttribute(SEARCH_PARAMS) #Valid SearchParams params,
BindingResult bindingResult) {
ModelAndView output = null;
if (!bindingResult.hasErrors()) {
JobsAPIImplService service = new JobsAPIImplService();
JobsAPI api = service.getJobsAPIImplPort();
ArrayList<NoaJob> jobs = (ArrayList<NoaJob>) (api.search(JobUtils.toSearchParams(params))).getItem();
output = new ModelAndView("scheduler/list");
output.addObject("jobs", jobs);
} else {
// errors handling
}
return output;
}
So in my result page I can access to the ArrayList "jobs" in this way:
<tr th:each="job : ${jobs}">
...
</tr>
In the same page, I have a simple link which calls another GET method on the same controller. The goal here is to have the same ArrayList in another page in order to implement a "back" button without re-executing the search logic (a call to a web service).
Here is the method called
#RequestMapping(value="/list/{id}", method = RequestMethod.GET)
public ModelAndView details(#PathVariable("id") String jobUuid,
#ModelAttribute("jobs") ArrayList<NoaJob> jobs) {
ModelAndView output = new ModelAndView("scheduler/details");
LOGGER.info("Size jobs list: " + jobs.size());
NoaJob job = new NoaJob();
job.setJobUuid(jobUuid);
output.addObject("job", job);
output.addObject("jobs", jobs);
return output;
}
the problem is that the arraylist here is always null! I read that in GET requests Spring allocates a new ModelAttribute, so how can I pass this object throug pages?
Define a session attribute like this in the head of your controller:
#SessionAttributes({ "myFancyList"})
#Controller
public class HomeController {
// your code here
}
Now.. when you have to insert the "list" to be viewable via thymeleaf:
output.addObject("myFancyList", jobs);
and modify thymleaf pseudocode accordingly.
in the "post" of the search "override" the session attribute with the current search result..
i think this should do the trick for you
What is the proper way to forward a request in spring to a different controller?
#RequestMapping({"/someurl"})
public ModelAndView execute(Model model) {
if (someCondition) {
//forward to controller A
} else {
//forward to controller B
}
}
All of the controller have dependencies injected by Spring, so I can't just create them and call them myself, but I want the request attributes to be passed on to the other controllers.
Try returning a String instead, and the String being the forward url.
#RequestMapping({"/someurl"})
public String execute(Model model) {
if (someCondition) {
return "forward:/someUrlA";
} else {
return "forward:/someUrlB";
}
}
You can use view name like "redirect:controllerName" or "forward:controllerName". The latter will reroute request to another controller and former will tell browser to redirect request to another url.
docs: https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#mvc-redirecting-redirect-prefix
You can use Spring RedirectView to dispatch request from one controller to other controller.
It will be by default Request type "GET"
RedirectView redirectView = new RedirectView("/controllerRequestMapping/methodmapping.do", true);