Replace Error Handling from JSP to Servlet - java

I have this code in my JSP script
<%# page errorPage ="error.jsp"%>
<%!
...My JSP Code... //No matter for this question
%>
My error.jsp script is:
<%# page isErrorPage = "true"%>
<% if (exception != null) { %>
The cause of the exception error has been:
<% exception.printStackTrace(new java.io.PrintWriter(out)); %>
<% } %>
like:
http://www.tutorialspoint.com/jsp/jsp_exception_handling.htm
But I want to replace all before code to servlet...
As you can see...
I need to translate <%# page errorPage ="error.jsp"%> to Servlet code...
and error.jsp entirely...for example How translate this:<%# page isErrorPage = "true"%>?
Sorry, but I don't know how to do it...
PD:
I was looking for my question, but sites tell that I need to change web.xml file, I don't want to do it, I think that (My JSP script works fine, and the converted by Tomcat servlet works fine too without change that file).

hey buddy #Luigi Giuseppe. I thing this one will be going to satisfying for you doubt.
Two ways to define Error page in Java web application written using Servlet and JSP like your question related.
1. First way is page wise error page which is defined on each jsp page and if there is any unhanded exception thrown from that page, corresponding error page will be displayed.
2. Second approach is an application wide general or default error page which is shown if any Exception is thrown from any Servlet or JSP and there is no page specific error page defined.
HTTP standard error codes:
1. Information This one is a new return code which is not 100%
supported and normally and only provides information to the client
about the request.
2. Success response, the request has been correctly executed ->
expected answer from server (http code 200).
3. Redirection response. The resource has moved and is not any more at
this URL.
4. Error on client side. Probably most known of all is error 404 : Not
Found.
Defining error.jsp page like:
//error.jsp
<%# page isErrorPage="true"%>
//login.jsp
<%# page errorPage="error.jsp"%>
And, Error page in Java Web Application JSP Servlet page is like:
Default Error page based on Exception:
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.htm</location>
</error-page>
Default Error page based on HTTP Error code:
<error-page>
<error-code>500</error-code>
<location>/internal-server-error.htm</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/page-not-found-error.htm</location>
</error-page>
Create your custom error pages:
1. 400.html -> telling the user did something wrong
2. 500.html -> telling the server did something wrong
400.html:
<error-page>
<error-code>400</error-code>
<location>/404.html</location>
</error-page>
<error-page>
<error-code>401</error-code>
<location>/404.html</location>
</error-page>
500.html:
<error-page>
<error-code>500</error-code>
<location>/500.html</location>
</error-page>
<error-page>
<error-code>501</error-code>
<location>/500.html</location>
</error-page>

hey buddy #Luigi Giuseppe. Yes, #mikemil's telling right buddy, You should just use the try/catch and otherwise use the method to display the exception error like as following code like this:
package com.jmail.servlet.exception;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/MyExceptionServlet")
public class MyExceptionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
throw new ServletException("GET method is not supported.");
}
}
Now, you just getting error page like this:
GET method is not supported.

Related

how to get custom exception message in ajaxError of jquery

I know we can get exception using xhr.responseText, but in my APP, the responseTextdisplay as exception description amended by Tomcat. please refer to below image, is there anyone can tell me how can I control the content of responseText or how to handle custom message(may be in a better way).
I need a title and content in the response as I can display them in dialog of Jquery UI. BTW, I throw a general exception just like throw new Exception("some error happens");
You can define custom error message in your web.xml like this -
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/Error.jsp</location>
</error-page>
You can have any text in your error.jsp page, that text will be sent to client on respective error
more info

Why can't i use doGet method in my servlet code?

I am new to servlets and i have developed a html page which has a submit button that triggers
my servlet.Everything is working fine .But now i want to use GET method as my html page is not posting anything.Hence i made the following changes:
1)In my page.html file, i replaced method="POST" with method="GET".
2)I changed doPost with doGet in my servlet.
But i'm getting error message that "GET not allowed here".Why is it so?
Here are the original files which work correctly(prior to making changes):
My page.html page:
<html>
<head>
<title>A simple revision of servlets</title>
</head>
<body>
<form method="POST" action="Idiot">
<input type="SUBMIT">
</form>
</body>
</html>
My Deployment Descriptor:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>TangoCharlie</servlet-name>
<servlet-class>Revise</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TangoCharlie</servlet-name>
<url-pattern>/Idiot</url-pattern>
</servlet-mapping>
</web-app>
And finally my servlet file named Revise.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Revise extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<html><body><h3>Hello India</h3></body></html>");
out.println("Hello");
}
}
I don't want to add any input fields.My aim is just to run the servlet without a single button on html page that too called using "POST" method.
Just do the job in doGet() method (don't forget to properly rebuild/redeploy/restart the project after editing servlet code, otherwise you will still face a "HTTP 405: method not allowed" error) and invoke the URL of the servlet directly instead of the URL of the JSP in the browser's address bar.
So, the URL in browser address bar should be
http://example.com/contextname/Idiot
instead of
http://example.com/contextname/page.html
Unrelated to the concrete problem, emitting HTML in a servlet is bad design. It should be done by a JSP. You can use RequestDispatcher#forward() to forward the request to a JSP after finishing the doGet() business logic. Further, packageless classes are also a bad design. You should always put publicly reuseable Java classes in a package. Packageless servlets will only work on certain combinations of Tomcat + JVM versions.
See also:
Our servlets wiki page - contains concrete (and properly designed) Hello World examples

How to call a servlet on jsp page load? [duplicate]

This question already has answers here:
Calling a servlet from JSP file on page load
(4 answers)
Closed 6 years ago.
I have below servlet. I would like to call the servlet on jsp page load. How can I do that?
servlet: SomeServlet.java
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>SomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
How can I write corresponding jsp to invoke the servlet on jsp page load. Also I need to get the result from servlet and display in the same jsp. Can I send result back to jsp?
Thanks!
You should do it the other way round. Call the servlet by its URL and let it present the JSP. That's also the normal MVC approach (servlet is the controller and JSP is the view).
First put the JSP file in /WEB-INF folder so that the enduser can never "accidently" open it by directly entering its URL in browser address bar without invoking the servlet. Then change the servlet's doGet() accordingly that it forwards the request to the JSP.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ...
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
Open it by
http://localhost:8080/contextname/HelloServlet
Note that you can of course change the URL pattern in servlet mapping to something like /hello so that you can use a more representative URL:
http://localhost:8080/contextname/hello
See also:
Our Servlets tag info page
<jsp:include page="/HelloWorld"/>
Call a servlet instead get result in request attribute and forward the request to jsp
or make an ajax call to servlet on load and render the response using javascript
In JSP paage you can forward the request to the Servlet
response.sendRedirect(request.getContextPath()+"/SomeServlet");

Hide JSPs from FacesContext

I have a JSF application with a Servlet Filter configured for a urlPattern of /faces/*.
I want to hide a JSP from faces context so that it won't go through the Servlet Filter.
So I kept it under WebContent folder of my project as WebContent/Error.jsp and declared like the following in the web.xml:
<error-page>
<exception-type>java.lang.NullPointerException</exception-type>
<location>/Error.jsp</location>
</error-page>
But my Error.jsp never gets picked up. Instead I see 404 Page not found error.
To be more clear, I want my Error.jsp page URL to be:
http://localhost:8080/myappname/Error.jsp
But it is only reachable by:
http://localhost:8080/myappname/faces/Error.jsp
The same is the case when I declare any view-id in the faces-config.xml. Where do I keep the error JSP if I want to hide it from faces context?
Based on the information given so far, it looks as it should just work fine. You don't have a <dispatcher>ERROR</dispatcher> on the filter, so the filter should not be invoked at all whenever the NPE is thrown.
Apparently the NPE got wrapped up in another exception because it's been thrown at an illogical place such as bean's constructor instead of a normal bean action method. In such case, JSF would rethrow it as a ManagedBeanCreationException. The container would get it instead of the NPE and thus won't be able to locate the error page. In the container's default HTTP 500 error page, you should read the topmost exception of the stacktrace in order to determine the right exception to define an error page for.
Please keep in mind that runtime exceptions like NPEs are developer errors (bugs!), not production errors and that they should be fixed ASAP. I'd personally just use a global HTTP 500 error page for this kind of bugs:
<error-page>
<status-code>500<status-code>
<location>/errors/generic.jsp</location>
</error-page>
For more specific, real production exceptions, you can always declare a more specific error page:
<error-page>
<exception-type>com.example.YourDatabaseAccessException</exception-type>
<location>/errors/database.jsp</location>
</error-page>
<error-page>
<exception-type>javax.faces.application.ViewExpiredException</exception-type>
<location>/errors/sessionexpired.jsp</location>
</error-page>
If you define a filter and declear that in your web.xml, all the request will go through that filter, unless you define the filter mapping.
I think you can define a filter mapping in your web.xml as following:
<filter>
<filter-name>URLFilter</filter-name>
<filter-class>the filter class in your source code</filter-class>
</filter>
<filter-mapping>
<filter-name>URLFilter</filter-name>
<url-pattern>/some pages</url-pattern>//skip error.jsp here
</filter-mapping>
this is not tested, but just an inspiration.
edit: you can find out more from Oracle site
To me it doesn't sound like the Faces filter has anything to do with this issue. Can you reach http://localhost:8080/myappname/Error.jsp with the filter completely disabled? If not, then perhaps there is some issue with the Error.jsp file itself?
It's hard to say without seeing the code itself.

what's the right technique to redirect an Exception from a Servlet to a default error JSP?

I need to have a default error JSP page which is shown when an exception is thrown by the servlet, and that page will show the stacktrace..
How do I do that?? is there a right technique (provided by the API) or I have to do it manually?? I mean, sending the exception thrown as an attribute and then dealing with it by myself??
Thanks
You can configure the exception type and the JSP page to handle in web.xml, e.g:
<error-page>
<exception-type>UnhandledException</exception-type>
<location>UnhandledException.jsp</location>
</error-page>
There's an Oracle article here on the subject:
http://www.oracle.com/technology/sample_code/tech/java/codesnippet/servlets/HandlingServletExceptions/HandlingServletExceptions.html

Categories