I want to display error messages e.g SQLException errors in the jsp page that the servlet has redirected to. I am new in java and JSP but I have managed to get basic things like saving data using a servlet to a database working. Below is my code for catching errors encountered
catch(SQLException e){
out.println("SQL Error encountered "+e.getMessage());
How can I catch this error into a jsp page that has been redirected to by the servlet using jstl or Expression Language? E.g if an admin submits a duplicate email address from a page called createuser.jsp, the error should be displayed in creatuser.jsp
You should never post exception related material to your front end since this can provide information on your internal structure and underlying architecture which is never a good idea since it could lead to possible attacks.
What you could do would be to do some sort of form validation, as shown in here and, as in your case, instead of showing exception messages, you simply make a check for the name and if it throws and exception, just display a message on the screen something like so: User Already Exists!. Error messages such as these are usually also less confusing for non technical people.
You can add the message as an attribute of your request:
Servlet:
catch(SQLException e) {
request.setAttribute("exception", "SQL error encountered");
}
Jsp:
${exception}
Related
I have an external service I'm calling that just returns 500's with the SAME exception each time no matter the issue.
For example(my api to their service):
Action: Fetch image that does not exist
IMGException: Status code: 500, ErrMsg: File not found
Action: Fetch image that does exist but there are server side issues
IMGException: Status code: 500, ErrMsg: Cannot grab img at this time
Action: Fetch image that does exist but is expired
IMGException: Status code: 500, ErrMsg: Img is expired
What would be the best way to handle this? I was catching them and giving them more descriptive messages to throw to my #ExceptionHandler for logging, etc. Should I just throw them and never catch them since I cannot dependably predict what the exception is caused from and therefore cannot correctly change the status code or message?
You can parse the ErrMsg and throw your own exceptions. But Since the response is from an external service, you can as well include the message from external service in the response to your API in a separate field like ExternalMessage.
This will help the users in case the response from external API changes and you end up throwing a different exception.
I recommend you to simply rethrow these exceptions with the information that the server sends to you and add any information you have. But do not add new information based on what you recieved (with if's, for example), because if they change something your code will just be deprecated.
Of course, never show crypt messages to your final user. In this case add some generic message with instructions about what they can do.
I am trying to send an error message from back bean class to view but it shows for a second and then went away. I don't know the reason please let me know what I am doing wrong.
For scope, I am using ManagedBean and RequestScoped
String msg = "Without 'Sample Id/Experiment Id' Keys file cannot proceed";
FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, ""));
In my view, I am trying to get these error and these containers
<rich:messages globalOnly="true" />
<rich:messages for="gv" />
It shows these messages but doesn't stay there and vanish. Thank you in advance
JSF messages have basically a lifetime of a single request (but you can extend this via Flash Scope in JSF2) and thus disappear after a request finished.
rich:message components get auto-updated (i.e. ajaxRendered) by default. So it's very likely, that you have some AJAX-request, that triggers right after the message was shown on your page. Because of the request-scope of messages, no more messages are available in the new request and the rich:messages get updated again with empty content.
You can verify this by using your browsers developer tools or Firebug to watch network your traffic.
Let me first provide some background information. If you don't care you can skip to the next paragraph. I wanted to use the DrEdit sample Java application which is integrated with Google Drive as the basis of my application. I need to refactor the code, though, because the original scenario assumed that the user would only access the application through the Drive and never directly. Currently when the latter happens, a RuntimeException is thrown which should not be the case in a normal flow.
Thanks to that issue I stumbled upon a difference between my local environment and the GAE which is manifested when the following code is run:
} catch (CredentialMediator.NoRefreshTokenException e) {
try {
resp.sendRedirect(e.getAuthorizationUrl());
} catch (IOException ioe) {
throw new RuntimeException("Failed to redirect user for authorization");
}
throw new RuntimeException("No refresh token found. Re-authorizing.");
}
When I run this application on GAE, the RuntimeException is thrown (I can see it in the logs) and the sendRedirect is also executed so I get to see the page that should be displayed.
However when I run the same application locally, I get the HTTP 500 error and the RuntimeException is displayed but the sendRedirect is ignored.
So far I haven't been successful in finding an explanation for this behaviour. I would like to know why this is the case and if there are settings that I can change in order to fully replicate the GAE environment locally.
This is how standard defines the sendRedirect(). It actually commits the response so after calling this method you should not be able to change or add to the response. However it does not define what happens if you trigger an exception after redirect.
Anyway, your code is ambiguous on purpose - you should not continue processing the request and throw exceptions after sending redirect. If you have any processing to do, then do it before redirect.
OTOH you should not rely on generic exception handling. Instead install a servlet filter that catches exceptions and return a proper user-readable or device-readable response.
I am using GWT. if any server side exception is generated, we are sending an email with error details(have used log4j SMTPAppender). Based on the line number, we can fix the issue..
My scenario is, if any exception is generated in the client package code, as of now, we are giving generic message saying "Some Exception has Occured". But is it possible to display error stack trace along with the exception cause and line number? my code is as below:
GWT.setUncaughtExceptionHandler(new
GWT.UncaughtExceptionHandler() {
public void onUncaughtException(Throwable e) {
Window.alert("Some Exception has Occured");
}
});
I dont think it is possible as client package is converted into Javascript in web mode. Please suggest me if there is any approach to display exception cause and line number where it has occured.
You can read this page
Basically, you have to use JUL to do your logging, and it's client logging : firebug, JS console, etc... You may do some smarter things with the RemoteLogging but i can't help you on that.
The main problem is that log4j is not supported. Maybe with a bridge between JUL and log4j you will be able to achieve everything you want
I would recommend using gwt-log:
Project Page
gwt-log has support for an 'UncaughtExceptionHandler' and a RemoteLogger to send messages/exception to the server.
in gwt-log, you can also turn on the "emulated stack", which is exactly what you want to do:
Wiki Page - Emulated Stack
please note however that this adds a LOT of code to the compiled JS-script
I have a jsp page in my project where user fills up the details for creating an account.
when a user enters username and clicks on the check button, the button looks in the database if the same name exists or not(it is able to check because of the servlet code).
If username exists it shows not available.
Now the problem is even if username is not available when user clicks on sumbit button with existing username the details get saved. how to correct this?
(I'm nt able to post image otherwise it would have been more clear.)
Just add an if-else block to your servlet, something like this:
if (usernameExists) {
showError();
} else {
saveUser();
}
Do not do this:
if (usernameExists) {
showError();
}
saveUser();
I'd also add an UNIQUE constraint on the username column in the DB so that your DAO throws an SQLException or like.
See also:
Our Servlets wiki page - contains a basic Hello world example with server-side validation
First, you serlvet accepting the HTTP POST must validate the data sent to it, when the user clicks a button, if the receiver doesn't validate the information then bad data will get into your system regardless of what you do in the JSP.
Some people send raw HTTP POST messages from time to time just for fun (I don't know why :) ) to see if bad data can get into poorly written web applications.
Once the servlet accepting the POST rejects bad data, you can have it redirect back to the offending web page, filled out with the information that was sent in the bad request, perhaps highlighting the offending field or fields.
Later on, if you have the time, you can write up a bunch of javascript to pre-check the fields and deactivate the submit button. This saves the back end servlet the bother of receiving so many bad requests; however, you cannot use such a technique to avoid fixing the back end servlet. There's too many ways your servlet could get the POST message that don't involve your specific javascript code working.