How allow duplicate submission in spring MVC? - javascript

I know PRG pattern can prevent duplicate submission(POST) for a page. But I have a JSP page with window.history.back() link. this link take back the user to the previous page that was POST, but all browsers show resubmission warning and suggest to press reload button. I want to allow user go back to that page wihout any confirmation. The POST controller does a search. Inthe JSP page I am using:
...
and the end point is:
#RequestMapping(value="search.htm", method = RequestMethod.POST)
public String searchResults(Model model, #ModelAtrribute(value="search") Serach search, HttpServletRequest request){
......
}
**** I don't want to prevent re-submission.

I can't try it now, so take following example like a "guideline"... anyway I think you should use SessionAttributes within the ModelAttribute in order to keep your model still using window.history.back() link.
So, you could modify your Controller like:
#Controller
#SessionAttributes("searchObj")
public class YourController {
#RequestMapping(value="search.htm")
public ModelAndView searchResults(#ModelAtrribute(value="search") Serach search){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("search-result-page");
modelAndView.addObject("search", search);
modelAndView.addObject("searchObj", search);
return modelAndView;
}
}

Related

Return HTML page with Spring Controller

So, apparently, I'm trying to return an HTML file with help of the Spring Controller.
I already have added Thymeleaf dependencies and also tried the following ways to configure it:
1.
#RequestMapping ("/")
#ResponseBody
public String homeDisplay() {
return "homepage";
}
#Controller
public class HomeController {
#RequestMapping ("/")
public ModelAndView index () {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("homepage");
return modelAndView;
}
}
Anyway, didn't help, I get Whitelabel Error Page.
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Dec 13 20:14:04 EET 2020
There was an unexpected error (type=Not Found, status=404).
No message available
How can I fix it and display the HTML I need.
Try replacing the #RequestMapping with #GetMapping("/") or #RequestMapping(value = "/", method = RequestMethod.GET)
Why? because #RequestMapping will map to any request to that URL, so you have to specify that it's a GET request (I suppose that is what you want to use).
Since you didn't share your frontend code that is sending the request we can't tell if there is a problem there. Please share it as well.
I was running in to a similar problem when trying to get a homepage to show up for a REST API that I was making. The project does not have Thymeleaf though. I used the following and this worked for me. The following code makes the home.html file, stored in resources/static to show up when the application starts. It's a static page and no data is sent to it.
#Controller
public class HomeController {
#RequestMapping("/")
public String welcome() throws Exception {
return "home.html"; //note that this says .html
}
}
For a project that I was using Thymeleaf in, I have the following code which shows the login page stored in resources/templates folder.
#Controller
public class LoginController {
#GetMapping("/login")
public String showLoginForm() {
return "login"; //note that this is just the name of the file with no extension
}
}
Be sure to put the html file in the correct folder. My guess is that since you're using Thymeleaf, you will probably be using some templates.

Asp.net mvc change DIV content without reload and without button

I'm new in Asp.net mvc. I'm trying to write two simple tcp app. First app is client(Windows forms), second one host(Asp.net mvc). In First app we can write message and send it to second one app.
I'm receive properly message in second app and I set property message in HomeController.
I want to change div 'messageDiv' on string that is in message property every time I send it from first app and set property message.
This code below show how to make it but with button. Every time we send from first app message and then click receive button in second it change properly.
It is possible to write interval which will change that div on message property?
Index.cshtml
#{
ViewBag.Title = "Index";
}
<h2>Waiting for messages : </h2>
#using (Ajax.BeginForm(new AjaxOptions()
{
UpdateTargetId = "messageDiv",
HttpMethod = "Post"
}))
{
<input id="btn" type="submit" value="receive"/>
}
<div id="messageDiv"></div>
HomeController.cs
public class HomeController : Controller
{
public static string message { get; set; }
// GET: Home
[HttpGet]
public ActionResult Index()
{
tcpHost host = new tcpHost();
return View();
}
[HttpPost]
public ActionResult Index(string x)
{
return Content(string.Format(message));
}
}
If I understood you correctly, you need something that automatically updates your messages div whenever you/others receive a message?
You need to achieve a real-time communication (recommended) or you could use a setInterval method in JavaScript which will constantly check if there are some new messages and if there are, then it will fetch and display them in messages div (not recommended).

Reload part of the page on button click, Refresh whole page on new URL

I am writing a single page Spring MVC application.
Requirements:
I want it to change the state of the page according to the URL that is entered.
I want it to change the state of the page on a click of a button.
Example use cases:
If I enter a URL "my.site.com/", I want only my site skeleton to be loaded, with no data for the User. (User is an object in my model).
If I enter a URL "my.site.com/users/John", I want the data for "John" to be displayed (the page can be reloaded).
If I enter string "John" in a textbox, and hit button Go!, I want only the part of the page displaying user data to be refreshed and not the whole page reloaded.
Design Question:
I understand that for 1) and 2) I would need to return a new ModelAndView object, and for 3) I could use AJAX. This probably implies I would need three controller methods.
What I don't know is how to avoid conflicting URLs between the MVC and AJAX controller methods, and how to actually then call my AJAX controller method from Javascript, and not the ModelAndView controller method.
Code Example:
What I would need is something like this, except that this, of course, causes conflicting URLs.
/*
* Default view.
*/
#RequestMapping(value = "/users")
public ModelAndView displayDefault() {
return new ModelAndView("userdisplay_default.jsp");
}
/*
* View for a specific user.
*/
#RequestMapping(value = "/users/{username}")
public ModelAndView displaySpecific(#PathVariable(value = "username") String username) {
User user = new User(username);
return new ModelAndView("userdisplay_specific.jsp", "Specific User", user);
}
/*
* AJAX controller method.
*/
#RequestMapping(value = "/users/{username}", produces = "application/json", method = RequestMethod.GET)
public #ResponseBody User getTime(#PathVariable(value = "username") String username) {
return new User(username);
}
In Javascript I would then fetch the POJO like this:
// obtain user
var user = $('#user_input').val(); // this is a text input
$.getJSON("/users/"+user, function() {
//...
});
NOTE: My way of trying to achieve that could be wrong // insufficient // not optimal, so please feel free to also suggest some other way on how to do that.
Could you please give me an explanation along with a code example how what I need should be accomplished?
You can make different methods for your controllers.
For example:
#RequestMapping(value = "/users") and #RequestMapping(value = "/users/{username}") - there are GET methods. But for AJAX make controller with POST:
#RequestMapping(value = "/users/{username}", produces = "application/json", method = RequestMethod.POST)
And JS will be smth like this:
// Send the request
$.post("/users/"+user, data, function(response) {
// Do something with the request
});
Another advice (if it's possible in your situation) - rename url for your rest. E.g. add word api into the url.

Spring MVC - Handling Errors, Form Submits with Multiple forms

I have a .JSP file that has three forms on it whose fields are dynamically shown/hidden based on user interaction with Javascript/Jquery elements.The forms are spring forms sending their action to a URL that matches a controller.
The issue is that when I submit a form, and it does not validate, the URL the form submitted to stays in the URL. Then any action I take that is URL dependent is basically corrupted because the URL has the form action appended to it.
For example, if my .JSP's normal URL is /admin/, and my spring form is:
<form:form id="form" method="POST" action="${pageContext.request.contextPath}/admin/createUser" modelAttribute="User">
If validation fails my URL will now be /admin/createUser. If I am then taking some action using Javascript/Jquery the URL is no longer a valid way to navigate. I could just work around the URL but it just seems...un-ideal.
I have tried using redirects like: "redirect:/admin/", but spring validation will not work with this because you are basically just reloading the page.
Are there any best-practice or "elegant" solutions to this, or something really simple that I'm overlooking?
The redirection should probably be done on the client side anyways with a param of returnToURL, and as for error handling in Spring, you can register method as error handler to return proper error responses:
class YourController {
/**
* see #link{org.springframework.web.bind.annotation.ExceptionHandler}
*/
#ExceptionHandler(Exception.class)
public #ResponseBody String handleException(Exception e, HttpServletResponse rsp) {
// set the response status
return "{\"error\" : ...}"'
}
}
If you get error you can return error message to a custom error page to display the error message. or in your case you can return the admin page again..
here is some example code .
#RequestMapping(value = "/createUser" ,method = RequestMethod.POST)
public ModelAndView create(#ModelAttribute User user) {
if(user == null){
Map<String, String> model = new HashMap<String, String>();
model.put("errorCode", "00");
model.put("errorText", "Error Message Here");
return new ModelAndView("error_page", model);
}
return new ModelAndView("Welcome_page");
}

redirect to POST with javascript in asp.net mvc

I have 2 controller methods:
[HttpGet]
public ActionResult SomeAction(SomeModel model, string someString)
{
//..
return View()
and
[HttpPost]
public ActionResult SomeAction(SomeModel model)
I'm trying to find a way what would allow me to navigate directly to Post method from a controller (some other controller). I've heard the is a way to do it in javascript, but I can't find it anywhere. The idea would be to set a filed in model, and check it at beginning of a view - if it's set, do the javascript thing to redirect immediatly to Post action in controller. If anyone knows how to do it, I would aprreciate it
It sounds to me like you want to check, on page load, if the form has been filled out and if so immediately post it to the appropriate action?
If so
$(function() {
if () { // determine here if the form has been filled out and completed
$('#theform').submit(); // this posts the form, which will hit the post action
}
});

Categories