My Spring Boot application is deployed in embedded Tomcat and it can be accessed through the following url http://localhost:8080/displayResults
#RequestMapping(value = "displayResults", method = RequestMethod.GET)
public ModelAndView getResults(ModelMap model) {
List<Bean> beanToDisplay = handler.getData();
return new ModelAndView("Results", "beanToDisplay", beanToDisplay);
}
Now if I click on a link on the page displayed on above mentioned link, it performs some action. The link will take me to http://localhost:8080/displayResultsChanged. However I still display the same page for both the URLs it's just that it performs some calculations in the server.
Now my question is.. I don't want the URL to be displayed as http://localhost:8080/displayResultsChanged instead I still need http://localhost:8080/displayResults as the URL. How do I achieve that?
You should use REST. If you want to stay on the same page and only make some calculations as you said. I can give you a tip or two.
Firstly annotate your controller with #RestController
After, leave one method that leads you to the page you wanted like : displayResults in your example.
Then you need to create a method that returns NOT ModelAndView but List<Bean> in your case.
#RequestMapping(value = "displayResultsChanged ", method = RequestMethod.GET)
public List<Bean> getChangedResults() {
...
}
Now it depends on the client side how to make the call and proces the data that the server returns. If you provide some client side examples maybe you will get more and better answers.
Related
I have a Spring Boot online shop application and my shopping cart component is accessible from several different views.
I make my views in Thymeleaf and those - and + are <a th:href="#{'/products/addToCart/'+${product.id}}">. Now inside my products controller I do some backend work and return a redirect:home but that kind of kills the whole point of putting these - and + there. I'd like it to return the same view from which the request was sent. Can that be done somehow? I don't like the idea of making seperate controllers for every view.
You could use the referer (yes the official header has a typo) request header to know where you navigated from:
public String addProduct(#RequestHeader(value = HttpHeaders.REFERER, required = false) final String referrer) {
// update cart
// redirect to the referred
return "redirect:" + referrer;
}
However, that is probably quite brittle. I'm not sure the referrer URL will always be there.
For something like this, I would probably use JavaScript to do an AJAX request to a dedicated endpoint that returns JSON. You can add #ResponseBody on a method in your controller so the response is not seen as a redirect or a page view, but a JSON string for example.
#ResponseBody
public CartInfo updateCart(...) {
// do update to cart here
// return a CartInfo object. It will be serialized with Jackson to a JSON string
}
In your HTML page, you will need to add some JavaScript to handle the AJAX call using plain JS or your framework of choice.
I am not sure it this is possible at all. I see that in Facebook when you crate a business page you will get a link with page number, for example:
https://www.facebook.com/degendaUK/
I would like to know if it is possible to create a link like that without having an HTML or JSP page called "DegendaUK" for example.
In my code I have page
http://localhost:8080/offers/empresa?get_Business_ID=29-11-2017-03:39:22R7M5NZ8ZAL
The standard page is called "Empresa" and then I pass the ID so I can query the database.
Is there anyway that instead of my URL I would get
http://localhost:8080/offers/BUSINESS-NAME
without creating a JSP page for each business?
I am using Spring MVC.
You may use Spring #Controller, #RequestMapping and #PathVariable annotations to do this.
#Controller
public class Controller
{
#RequestMapping(value = "/offers/{id}")
public String offer(#PathVariable String id, final Model model)
{
//pass the value from the url to your jsp-view, access it via ${id} from
//there
model.add("id",id);
//render the page "empressa.jsp"
return "empressa";
}
}
Hint: You may need some and in your XML config to make those annotations work.
If your using spring-boot, this should be preconfigured already an work out of the box.
Don't forget to secure those things if they're not public things using spring-security :)
I am using Spring MVC 2.5. I have get and post methods for all the pages I have.
#RequestMapping(value = "/offer", method = RequestMethod.GET)
public ModelAndView getOffer(ModelMap model, HttpSession session) {
//code
return new ModelAndView(OFFER_SETTING_PAGE, model);
}
#RequestMapping(value = "/offer", method = RequestMethod.POST)
public ModelAndView postOffer(ModelMap model, #ModelAttribute("investorsEligiblitySetting")
//code
return new ModelAndView("redirect:/servlets/ProcessAction/privateplacement/createoffer/additionalinformation");
}
After passing the post method and displaying the next jsp file, when I try to hit the back button , instead of displaying the previous data from the cache (which is what I am looking for) it gets in to the get method of the specified url and causes some problems.
How can I make my application to look for cache first instead of getting in to a get method?
This is an old question, but I found this post that gives some ideas as to how to prevent the browser from resubmitting on the back button. You could also set something in your form when you handle the POST that the GET handler can look at to see if the POST already ran.
I am looking for a way to do a redirect or forward from one Controller request mapping to another.
The situation is that I have a Controller that has three stages: User inputs data -> Preview page -> Submit. In the Preview request mapping I have the Model Attribute and its BindingResult. If I have errors in the binding, I want to push the user back to the New form using a redirect, but when I do that Spring re-evaluates the ModelAttribute, and thusly re-creates the BindingResult.
Some code:
#RequestMapping(value = "\new", method = RequestMethod.GET)
#ApplicationUserCreated
public String formNew(
#ModelAttribute("formBean") FormBean formBean,
BindingResult bindingResults,
Model uiModel) {
// Do some stuff
// Send the "new form" view
return "new.jsp";
}
#RequestMapping("/preview", method = RequestMethod.POST)
#ApplicationUserCreated
public String formPreview(
#ModelAttribute("formBean") FormBean formBean,
BindingResult bindingResults,
Model uiModel) {
// TODO: Validate the form
if(bindingResults.hasErrors()) {
// Redirect them back to the "New" form
return "redirect:" + "/new";
} else {
return "preview.jsp";
}
}
Please excuse any typos, as I had to try to simplify the code some. I tried removing the BindingResults from the formNew() method, but when Preview redirects to New, it still seems to overwrite the BindingResults. I also tried doing a "forward" instead, but same results.
I ended up just calling formNew() from formPreview() when I needed to send the user back to the new.jsp. I don't get the redirect, so the URL in the browser shows as "/preview", but at least it's working and I feel like I am not wasting time duplicating code.
You can store the BindingResult in Session or you can try to send that data with Spring Flash Attributes, if you have at least spring 3.1 .
** if ManagementMovesFormBean extends or implements you're FormBean, you should send that bean in flash attributes.
** by the way, to validate you're form, you should have added #Valid in front of #ModelAttribute(".....
Don't forget that a BindingResult is assign to a single class, in you're example you have 2 methods with different expected objects, so those two BindingObjects are different
I am not sure what the purpose of the preview page is but I would recommend performing validation on the same page and only when input is valid to proceed to preview using a redirect.
I have a Spring Annonted Controller that is used to capture the information from a form and get a list of search results from the database.
Here is the definition of the method
#RequestMapping(method = RequestMethod.POST, params = {SUBMIT_BTN })
public ModelAndView processForm(#ModelAttribute(COMMAND_NAME){
// 1. Load search results using search parameters from form (Contained in a collection of some sort)
// 2. Create the ModelAndView
// 3. Redirect with RequestView or redirect: to generate a GET.
}
I think I need to redirect with redirect: since i have a list of items in a collection store in the session. Cannot add that as a url request param.
Basically I'm trying to prevent problems whith the back button where it says that the page is expired. I want to implement the PRG pattern in strings.
I'm having a hard time wrapping my head around converting the POST into a GET. Can I just redirect or do I need two methods? Thanks for any help you can provide.
The standard pattern is to have a controller method to handle the GET,and which shows the form (or whatever) to the user, and one to handle the POST, which is the form submission. The POST method sends a redirect after it has finished processing the submission, which comes back in to the GET method.
#RequestMapping(value="/myapp", method=GET)
public String showForm(#ModelAttribute(COMMAND_NAME){
return "form.jsp";
}
#RequestMapping(value="/myapp", method=POST)
public String processForm(#ModelAttribute(COMMAND_NAME){
// do stuff to process for submission
return "redirect:/myapp";
}
Returning a view name with the "redirect:" prefix forces Spring to send an HTTP direct rather than an internal request forward.
This is the same pattern that Spring 2.0 implemented with SimpleFormController, but the new way is far more transparent.