I have a form controller.Form element is a drop down box.
For eg there is user name form element.if user select his name .I want the children names to be loaded for particular user.
I have List getChildernByUser(User user);
Please would like to know how this can be made using jquery or ajax.If user is selected in next form element he gets all his children to select .
In the server side, I'd use a controller method like this:
#RequestMapping("/users/{userId}/children")
public #ResponseBody List<User> getChilden(#PathVariable String userId) { ... }
More info in this kind of controller methods can be found in the Spring reference doc. You'll also need the Jackson libraries in your /lib folder for Spring MVC to convert the bean to JSON.
Then, in your client code (HTML) you can use the getJSON() function to make an Ajax call and get a List of users in JSON format.
Good luck.
Related
I would like to call a controller method using a button on a JSP page in Spring MVC, but I would like it to stay on a current page, don't reload it or anything, simply call a method. I found it difficult. My button is on cars.jsp page. In order to stay on this page I have to do something like this:
#RequestMapping(value="/start")
public String startCheckingStatus(Model model){
System.out.println("start");
model.addAttribute("cars", this.carService.getCars());
return "car\\cars";
}
button:
Start
But this is not a good solution because my page is actually reloaded. Can I just call controller method without any refreshing, redirecting or anything? When I remove return type like so:
#RequestMapping(value="/start")
public void startCheckingStatus(Model model){
System.out.println("start");
}
I got 404.
Add an onclick event on your button and call the following code from your javascript:
$("#yourButtonId").click(function(){
$.ajax({
url : 'start',
method : 'GET',
async : false,
complete : function(data) {
console.log(data.responseText);
}
});
});
If you want to wait for the result of the call then keep async : false otherwise remove it.
As mentioned elsewhere you can achieve this by implementing an Ajax based solution:
https://en.wikipedia.org/wiki/Ajax_(programming)
With Ajax, web applications can send data to and retrieve from a
server asynchronously (in the background) without interfering with the
display and behavior of the existing page. By decoupling the data
interchange layer from the presentation layer, Ajax allows for web
pages, and by extension web applications, to change content
dynamically without the need to reload the entire page.
To achieve this you will need to make changes to both the client and server side parts of your app. When using Spring MVC it is simply a case of adding the #ResponseBody annotation to your controller method which:
can be put on a method and indicates that the return type should be
written straight to the HTTP response body (and not placed in a Model,
or interpreted as a view name).
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-responsebody
Thus, for example, to return a simple String in the Ajax response we can do the following (without the #ResponseBody the framework would try and find a view named 'some status' which is obviously not what we want):
#RequestMapping(value="/start")
#ResponseBody
public String startCheckingStatus(Model model){
return "some status";
}
For the client part you need to add some javascript which will use the XMLHttpRequest Object to retrieve data from your controller.
While there are various frameworks which can simplify this (e.g. JQuery) there are some examples at the below using vanilla javascript and it might be worth looking at some of these first to see what is actually going on:
http://www.w3schools.com/ajax/ajax_examples.asp
If we take this specific example:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_callback
and [1] copy the <button/> and <script/> elements to your JSP, [2] change the URL to point to your controller and, [3] create an element <div id="demo"></div> in your JSP then, on clicking the button in your page, this <div/> should be updated to display the String returned by your controller.
As noted this is a lot of code for one action so you can use some JS framework to abstract a lot of it away.
I'm trying to configure Spring MVC so that each browser session or tab has it's own session. Can this be done?
A snippet from my controller:
#Controller
#Scope("session")
public class TestController {
#Autowired
private AuthenticationService as;
private User user = new User();
#RequestMapping(value="/testIntegration")
public String getIntegration(Model model) {
logger.debug("user: " + user.toString());
if(!as.authenticateUser(user, sessionTimeout)) {
.
.
.
The class User is a POJO.
When 'testIntegration' is accessed first time all values are null. This is expected. 'as.authenticateUser(user, sessionTimeout))' sets the correct values. On the next access values are set on User. This is expected and desired.
If another browser window is opened and attempts to access 'testIntegration' the same populated User object is retrieved from the session. This is NOT expected nor desired. A new browser should garner a new session and require a new User object to be created and populated.
I've seen an older thread indicating that a conversation indicator can be implemented by placing the conversation ID on each form of the application. I'm hoping for a better/different approach via Spring annotations or configuration.
That's the way HTTP and browsers work: session identifiers are implemented with cookies, these are shared across all browser tabs. In order to get this you need to pass along unique browser tab identifier along with session id cookie.
Considering your application can contain anchor tag links which client can control/command click (or right click and select open link in new tab) this can be tricky and you will need to make tradeoffs.
One way to do this is to generate a tab-id (for instance UUID) if tab-id parameter is not specified in request, and make sure that its put in all links and submitted with all forms in your application.
Link generation can be affected by wrapping HttpServletResponse (using HttpServletResponseWrapper) and overriding the encodeURL method. And if you're using spring forms taglib or thymelef you can add hidden inputs to forms using RequestDataValueProcessor.
I will prefix this with the fact that I am new to Spring.
I have a list of beans off of a backing bean which I am using to create a form with checkboxes. Is it possible, after submitting this form to have the same list of beans populated only with the beans that the user has checked?
I am running into problems with this approach and I know I could set it up to get the ID attribute for these beans as a list of Strings but I would ideally like to have it populate a list of the same type of beans (I'm just not sure if Spring forms work this way).
I think adding code might convolute my question but here is the basics of what I am working with:
When Java gets to my controller code, should myBackingBean have a list of myGenericBeans that were selected via checkbox? What am I missing?
Java
class MyBackingBean
{
List<MyGenericBean> myGenericBeans;
public function getMyGenericBeans()
{
return myGenericBeans;
}
}
HTML
<form:form action="/path/formHandler" commandName="myBackingBean" class="popup-form">
<form:checkboxes path="myGenericBeans" items="${myBackingBean.myGenericBeans}" />
</form:form>
Java (controller code)
#RequestMapping(value = "/formHandler", method = RequestMethod.POST)
public String editAccountTeam(#ModelAttribute("myBackingBean") MyBackingBean myBackingBean, BindingResult result) {
...
return "";
}
I think the best you are going to be able to do is generate a list of bean names that is used as the value of the check boxes. Then when the user submits the page, build a list of selected beans (from the check boxes) and get the beans from your application context (i.e. getBean("bean name");)
I am using Starbox in my Spring page. I want to submit the user rating so I can store it in the database and not have to refresh the page for the user. How can I have a Spring controller that accepts this value and doesn't have to return a new view. I don't necessarily need to return any updated html - if the user clicks the Starbox, that is all that needs to happen.
Similarly, if I have a form with a submit button and want to save the form values on submit but not necessarily send the user to a new page, how can I have a controller do that? I haven't found a great Spring AJAX tutorial - any suggestions would be great.
If you use annotations, perhaps the more elegant way to return no view is to declare a void-returning controller method with #ResponseStatus(HttpStatus.OK) or #ResponseStatus(HttpStatus.NO_CONTENT) annotations.
If you use Controller class, you can simply return null from handleRequest.
To post a from to the controller via AJAX call you can use the appropriate features of your client-side Javascript library (if you have one), for example, post() and serialize() in jQuery.
The AJAX logic on the browser can simply ignore any data the server sends back, it shouldn't matter what it responds with.
But if you really want to make sure no response body gets sent back, then there are things you can do. If using annotated controllers, you can give Spring a hint that you don't want it to generate a response by adding the HttpServletResponse parameter to your #RequestMapping method. You don't have to use the response, but declaring it as a parameter tells Spring "I'm handling the response myself", and nothing will be sent back.
edit: OK, so you're using old Spring 2.0-style controllers. If you read the javadoc on the Controller interface, you'll see it says
#return a ModelAndView to render, or
null if handled directly
So if you don't want to render a view, then just return null from your controller, and no response body will be generated.
We are developing an application using Spring MVC. There is a page which displays list of user, a check box next to it, and a submit button at the bottom of the page.
A logged in user can select those check boxes and submit, currently a controller checks whether the selected user list is empty or not and acts accordingly. Should we just bring a validator only to do this check ? or else is it fine to do it in the controller itself ? Is there any doc which says what a controller, validator should do and should not do ?
Until Spring 3.0 is released - there is no built-in support for model validation. You'll have to handle validation on your own - like this:
#RequestMapping
public String post(#ModelAttribute MyModel myModel, BindingResult result){
myValidator.validate(myModel, result);
if (result.hasErrors()) return "myView";
...
}
You can do what you like, it's your code. But by convention, the controller should just be concerned with directing things - validation should really be in a separate validator.