Java Error Page in web.xml not for all requests - java

Is it possible to setup error-page but that should be triggered not for all URI's but for example with /custom-path, and for requests with URI's /main-path do not handle errors?
In web.xml i suppose it is only possible to match error page with certain Exception types.
The problem is we have one single war file inside which we have both rest api and html management UI. So if error comes from rest api, it should be rendered as it is and no error page should be displayed.

I had the same problem and I solved it by calling setStatus() on HttpServletResponse instead of throwing exceptions or calling sendError().
Example of my Spring MVC controller:
#RequestMapping(value = "/{ean}", method = RequestMethod.GET)
#ResponseBody
public User getUser(#PathVariable("id" Long id, HttpServletResponse response) {
// response.sendError(HttpServletResponse.SC_NOT_FOUND)
response.setStatus(HttpServletResponse.SC_NOT_FOUND)
}
This way my RESTful API controllers don't render error pages.

Related

Migrating JSP code to Spring Controller and Service

We are migrating jsp mapping to Spring controller and we want move jsp code to Spring service as we have only scriptlet code in jsp files but the main thing we do not want to change the url that we are calling from UI using ajax call.
Ajax call sample
/ProjectContext/jsp/project/module/downloadFile.jsp
So here .jsp extension will remain same so what should I have to mention in viewResolver.
Please do let me know is there any better way to migrate jsp scriptlet code to spring controller and service.
I have tried below code but not work for me.
#Controller
public class DownloadController {
#Autowired
private DownloadService downloadService;
#RequestMapping(value = "/jsp/project/module/downloadFile.jsp", consumes = APPLICATION_FORM_URLENCODED_VALUE)
public void downloadFileToLocal(HttpServletRequest request, HttpServletResponse response) {
downloadService.downloadFileToLocal(request, response);
}
}

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".

Passing $routeParams from angularjs to spring-MVC controller

This is what I have in my AngularJs controller
.when("/M:topicId", {templateUrl: "Mu", controller: "conMFs"})
app.controller('conMFs',function($scope,$routeParams){
$scope.otherId = $routeParams.topicId;
});
This is my Spring Controller
#RequestMapping(value="/controlerM", method = RequestMethod.GET)
public ModelAndView controlerM(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView model = null;
session=request.getSession(true);
user = (User) session.getAttribute("user");
List<ends1> ends=(List<ends1>) ifriendlistservice.getends(user.getId(),5);
session.setAttribute("MutualFriends", MutualFriends);
model = new ModelAndView("ends");
return model;
I am able to fetch the topicId from my AngularJS page in AngularJS controller (with $scope.otherId), however I am unable to pass this value to my Spring controller, from where I am redirecting to new page.
How should I do this?
.when("/M:topicId", {templateUrl: "Mu", controller: "conMFs"})
app.controller('conMFs',function($window){
$window.location.reload();
});
Then server app gets topicId from request's url. You also need to have $locationProvider.html5Mode enabled.
How should I do this?
You shouldn't. Angular's off-hour job is to not let server apps to reload the page. The code above is quick-and-dirty, it can be ok only if you're in the middle of Angular integration into existing project, but the time-frame requires you to partially rely on old code base.
If you really need to make a redirect (e.g. to external page), make an AJAX request, put topicId and whatever there, get redirect url in response, redirect with $window.location.href.
I'm barely familiar with Spring, but the above applies to any server-side application.
Thanks estus,
Issue seems to be resolved...
I had created 2 controller in Spring, One for setting parameter through ajax , and other for redirection.

forwarding from spring controller to a jsp file

I am trying to forward my request from a Spring-MVC controller method - to a JSP page.
My controller method is supposed to handle an Ajax request. By forwarding the request to the JSP file, I want the response to the Ajax request to be the (dynamic) HTML output of the JSP file.
What I have tried:
public ModelAndView ajaxResponse(HttpServletRequest request, HttpServletResponse response) {
request.setAttribute("command", "hello world");
request.getRequestDispatcher("jspfile").forward(request, response);
return null;
}
This fails and I get "HTTP Status 404"
"jspfiles" is defined in a tiles config file to be directed to the actual jsp file. When I run the following method:
public String ajaxResponse(HttpServletRequest request, HttpServletResponse response) {
request.setAttribute("command", "hello world");
return "jspfile";
}
... I get the content of the file as my Ajax response - but JSP tags in that file are not parsed) - hence I conclude that my tiles definition is correct (???).
My JSP file looks like this:
<%=command%>
So I want to get as my Ajax response the string "hello world".
Could you show me an example code of how to achieve my purpose?
Specifically I need to know:
What should be the controller method return type?
What should be the controller method actual return value (if it matters)?
How should I set the jsp file path in the request.getRequestDispatcher(...) so it would be recognized?
Have a look at the controller example here:
http://maestric.com/doc/java/spring/mvc
It's a bit out of date, but the concept of what you must do remains the same. Spring 3 has annotation-based ways to do a lot of what is in that example.

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

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.

Categories