Spring-MVC: How can I display errors while using an AbstractCommandController? - java

I have ajax requests that come into my controller and my validation is working great. In the controller I call a failure jsp page if there is a failure. The only problem is that I have no idea how I can output the errors to the user on the failure.jsp page. I don't have access to the form tags of spring obviously. What should you do in this scenario?
Edit: All I really want to know is how I can access the binding errors on a JSP page when I'm using an AbstractCommandController.

What I've done in the past is use HTTP headers to send back messages to the AJAX requester (the XMLHTTPRequest object). You will not get a full binding and validation support this way, but it's a simple way to pass messages.
Another option that will give you the full power of Spring binding and validation is as follows. I'm assuming you're submitting a form via AJAX. You could do the standard spring binding and validation, and in the case of an error, send back and replace the form with the exception messages next to the problem input. This way you can leverage the full power of Spring binding and validation while getting the AJAX goodness that you want. This would require you to separate your form into a separate JSP page, so you could just return that form on AJAX submission and error.
In response the comment
My issue is just how to access the
BindingErrors from a JSP if I'm using
an AbstractCommandController. Ajax
isn't really that important in the
equation. I just didn't want to use a
formController because it didn't make
sense.
I think you can simply set a variable in your model like this:
ModelAndView.addObject(this.getCommandName(), errors)
This would be done in AbstractCommandController's
protected abstract ModelAndView handle(
HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException errors)
throws Exception
method. Be sure the name of the model attribute is the name of your command (set in the setCommandName method).
This is untested and from memory.

You can check the BindException object for errors (and also catch and handle exceptions), and return information about them in your Ajax response. If you're using JSON, you could pair a list of error information with an "errors" key. The front-end would then need to check for and display these errors.

Related

Displaying Error Messages from a Web Service Call to JSP

I am calling a web service to validate an email address. In case of an invalid email address this service returns messages and I need to display them in a JSP. I am using Jersey with Struts2 and I have a form which submits to an action which takes care of this logic at the back end. I am not using a servlet to get the messages from the HttpServletRequest object.
I get a list of messages and I need to display the error message text on the screen but I am not sure how to do it. On click I get the form id which goes to the back end using struts2 action.
Thanks...
I'd strongly recommend using the Struts2 validation interceptor. The documentation is very straight forward and it's very robust.
https://struts.apache.org/docs/basic-validation.html
https://struts.apache.org/docs/email-validator.html
You simply need to call the interceptor stack in your action in struts.xml, then specify what validations you want. You can then display your error on the JSP should the validation fail.
You can either use the default validators provided by the XML validation or set your own by creating a validate method in the action class that is called by the stack, or both.
http://www.simplecodestuffs.com/struts-2-fielderror-example/
Here is an example for you to work with.

JSON response giving Http 500 internal server error

I am getting Internal Error when trying to make an ajax POST Call which returns JSON.
The ajax call is made from JS page:
$.post(
'FilterAsJson',
$(formWithReportData).serialize(),
function(data){funtion_body}
);
This is my Spring MVC calling method:
#RequestMapping(value = "/Reporting/FilterAsJson", method = RequestMethod.POST)
public #ResponseBody PagedQueryResult<GetEntitlementOverviewReportResult> filterAsJson(#ModelAttribute GetEntitleReportQuery query, HttpSession session)
{
getEntitlementOverviewFromSession(session).updateFromQuery(query, session);
return queryDispatcher.dispatch(query);
}
The issue comes where I am setting only few fields in this class GetEntitlementOverviewReportResult(17 out of 30). This is a bean class with simple setter getters. If I set all the 30 fields it works fine.
Can you suggest how the JSON response is set so I can rectify this issue.
A 500 error means that your server encountered an error while processing the request. Since you are using AJAX, you do not see the full message from the server.
2 Options:
A - Check the server logs
B - See below:
Best way I know of to check this with an asynchronous call is to press F12 to bring up your developer tools in your web browser.
Then, you click the "Network" tab on the browser tool and you can see all of the requests that your application makes.
Make your request that is giving you a 500 error, then find it in the list of network requests. You should see the 500 error and be able to see the actual output (server response) that will give you an actual message.
#RequestMapping(value = "/Reporting/FilterAsJson", headers = "Accept=application/json", method = RequestMethod.POST)
public #ResponseBody PagedQueryResult<GetEntitlementOverviewReportResult> filterAsJson(#ModelAttribute GetEntitleReportQuery query, HttpSession session) {
getEntitlementOverviewFromSession(session).updateFromQuery(query, session);
return queryDispatcher.dispatch(query);
}
UPDATED
Oh, i see. I didn't understand question properly.
Show us please class GetEntitleReportQuery which propagate #ModelAttribute.
Also check what does method serialize when you filled not all fields. Does it exist?
UPDATED
An idea.
When u filled up not all fields of class, he try to find class with such fields and can't find. So, try to named your class in Controller and add binding result param: filterAsJson(#ModelAttribute("query") GetEntitleReportQuery query, HttpSession session, BindingResult result) also send from JSP with name "query".

Jquery post to Spring controller to return java bean for jstl parsing

I'm new to jquery and SpringMVC. I'm using jquery to submit a request after a user clicks a href. After the server processes the request, a modal popup is displayed with the details from the server.
$.post(taskSrchURL, function(data) {
$('#popupmodal').modal('show');
});
Here is the Controller:
#RequestMapping(value = "/api/task/{id}", method =
{RequestMethod.POST})
public ModelAndView searchDetails(#PathVariable("id") String
id,
HttpServletRequest request, HttpServletResponse response)
throws SearchException, ApplicationException {
Details details = service.getDetails(id, request, response);
prepareResponse(request, response, taskDetails);
ModelAndView modelAndView = new ModelAndView("details ");
modelAndView.addObject("details ", details);
return modelAndView;
I'm expecting to have access to the "details" object when the response returns, however, I'm not sure how to access it. I'm expecting to be able to use jstl tags to reference the data as it is complex and needs to be dispalyed on several tabs.
However,
<c:out value="${details.id}"/>
does not work. I have seen a lot examples that set the 'data' from the ModalAndView to the html element of a div, but I don't want to do that.
Is there a way to do this?
Thanks in advance!
You basically have 2 choices:
Client-side rendering:
If the data you need from the server can be inserted into your page with javascript without too much hassle, you should return it as JSON from your Controller method using #ResponseBody. Convertion to JSON can be done by Jackson automatically.
You could then use an existing Javascript template engine library to render your data to html on the clients browser and insert it into the page or just insert it manually (for example with jQuery).
Server-side rendering:
If you want to render the part of the page with the data on the server-side to then send the ready-made part of your page back to the client, you need a template engine which allows you to render your templates anytime anywhere (in your controller method in this case). You could then send the html String back again as JSON using #ResponseBody and insert it into the page.
I don't think JSP/JSTL can do this (or it is very difficult/hacky). I recommend FreeMarker instead.
You could still use JSP/JSTL for your "complete" pages, and FreeMarker for the parts. FreeMarker is not too different from JSP/JSTL, so you could probably translate the part of your page without too much problems.
Besides my comment, I would highly recommend using the #ResponseBody annotation instead of using ModelAndView
Be sure to have jackson-databind on your classpath, this will cause Spring to automatically serialize your POJO into JSON, which can be directly used as Javascript objects in the ajax callback function
See a quick tutorial here:
http://www.journaldev.com/2552/spring-restful-web-service-example-with-json-jackson-and-client-program
This approach decouples the Application Server from your view, thus liberating you from having to rely on JSTL templating and you can choose a front-end workflow that is intuitive for you (checkout AngularJS).

Struts 1.2 ActionForms & isTokenValid CSRF

I have an issue currently that the validate method of the actionform happens before the execute method of the action.
The reason this is an issue is that a user can submit their own request and should they have all required fields completed the validate passes and using the isTokenValid(request) method I can see that the request is invalid. and forward them to an "access denied" page. However if they do not complete all required fields in their forged request the validate method returns errors and they are forwarded to the actual page(.jsp) with error messages displayed.
Any idea how to prevent this?
To implement CSRF prevention in Struts1 using using tokens you should not allow direct access to your JSP pages.
A user should get to your forms through Struts Actions and the action will call saveToken(request) before they are forwarded to the form in the JSP page.
Where you usually forward directly to a JSP you can change to forward to an action that inherits from ActionForward. Within the execute it can then forward by calling parent ActionForward execute method. You could also implement additional logic restrictions in your new action class.
This answer to Struts CSRF question on separate thread may also be useful:
https://stackoverflow.com/a/5339391/6136697

How servlet handle multiple request from same jsp page

Sorry friends if this question is very easy but i am confuse i unable to find out solution.
As we all know in spring MVC framework we create controller which will handle multiple request from same page using #requestmapping annotation.
but same thing i want to do in servlet how can i do ?
Suppose i have a jsp which which will contain a jqgrid,and two forms i want to use only one servlet to load the data into jqgrid and that servlet only will handle request from both the form . Since we have only doGet and doPost in servlet how one servlet fulfill all three request. Hope you understand my question if you have and link where i get sample or and tutorial link plz reply me
Well, the only easy way to do this would be to use a request parameter to control how the processing happens.
In a very basic example, you may have something like a requestType value that gets passed as either part of the query string or the request body. You would assign values of 1-3 (or 0-2) with each value indicating a different type of request. Your servlet would then parse the request accordingly.
This actually is how the DispatcherServlet in SpringMVC works. There's only one servlet class instance and when a request comes in, it examines the query string along with other parts of the request to determine which controller should handle the request.

Categories