I creat a web application using eclipse and tomcat7 I had the following code in the html file and the java servlet class
in the html file:
<form action="UserAccessServlet" method = "get">
in the servlet class I had
#WebServlet ("/UserAccessServlet")
then I just made some small changes (new println statements) but it shows no effect I changed the server name with the following peice of code
html file: <form action="SQA_Servlet" method = "get">
java class: #WebServlet ("/SQA_Servlet")
but it seems that no reload take place and I got the following error:
HTTP Status 404 - /SQA_Learning/SQA_Servlet
--------------------------------------------------------------------------------
type Status report
message /SQA_Learning/SQA_Servlet
description The requested resource (/SQA_Learning/SQA_Servlet) is not available.
I tried clean the module, refresh, close the reopen the project with the same result
I replaced #WebServlet ("/SQA_Servlet") with #WebServlet(urlPatterns={"/SQA_Servlet"})
and still have no effect.. any suggestion.
The WebServlet name attribute cannot start with a /. Rather do,
#WebServlet("UserAccessServlet")
or leave it blank (if you want the WebServlet to use the name of your Servlet class name. Example:
#WebServlet
public class UserAccessServlet extends HttpServlet {
//Do stuff
}
I would recommend declaring your WebServlet annotations fully like in this example.
I'm not sure when and in what for conditions you are receiving this error. But if you are deploying to tomcat, the following might occur:
Assuming your webapp is called "my.webapp" resulting in my.webapp.war
assuming you have a Servlet "servlet1" which performs action1 => #WebServlet(urlPatterns = "/action1") (note the slash in front of action1)
Assuming you are calling this action with a html form:
<form action="/action1" method="GET"> this might not work because of the slash in front of action1
When it's there tomcat will redirect to localhost:8080/action1?..
while it should redirect to localhost:8080/my.project/action1?..
Solution alter the html so the form looks like:
<form action="action1" method="GET">, don't change the #WebServlet(urlPatterns = "/action1")
Hope this helps someone!
Related
Can I call a servlet from JSP file without using a HTML form?
For example, to show results from database in a HTML table during page load.
You can use the doGet() method of the servlet to preprocess a request and forward the request to the JSP. Then just point the servlet URL instead of JSP URL in links and browser address bar.
E.g.
#WebServlet("/products")
public class ProductsServlet extends HttpServlet {
#EJB
private ProductService productService;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products = productService.list();
request.setAttribute("products", products);
request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
}
}
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.name}</td>
<td>${product.description}</td>
<td>${product.price}</td>
</tr>
</c:forEach>
</table>
Note that the JSP file is placed inside /WEB-INF folder to prevent users from accessing it directly without calling the servlet.
Also note that #WebServlet is only available since Servlet 3.0 (Tomcat 7, etc), see also #WebServlet annotation with Tomcat 7. If you can't upgrade, or when you for some reason need to use a web.xml which is not compatible with Servlet 3.0, then you'd need to manually register the servlet the old fashioned way in web.xml as below instead of using the annotation:
<servlet>
<servlet-name>productsServlet</servlet-name>
<servlet-class>com.example.ProductsServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>productsServlet</servlet-name>
<url-pattern>/products</url-pattern>
</servlet-mapping>
Once having properly registered the servlet by annotation or XML, now you can open it by http://localhost:8080/context/products where /context is the webapp's deployed context path and /products is the servlet's URL pattern. If you happen to have any HTML <form> inside it, then just let it POST to the current URL like so <form method="post"> and add a doPost() to the very same servlet to perform the postprocessing job. Continue the below links for more concrete examples on that.
See also
Our Servlets wiki page
doGet and doPost in Servlets
How to avoid Java code in JSP
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
You will need to use RequestDispatcher's Methods forward/include depending on your requirement to achieve same.
In JSP you need to use following tags:
jsp:include :
The element allows you
to include either a static or dynamic
file in a JSP file. The results of
including static and dynamic files are
quite different. If the file is
static, its content is included in the
calling JSP file. If the file is
dynamic, it acts on a request and
sends back a result that is included
in the JSP page. When the include
action is finished, the JSP container
continues processing the remainder of
the JSP file.
e.g.
<jsp:include page="/HandlerServlet" flush="true">
jsp:forward :
The element forwards the
request object containing the client
request information from one JSP file
to another file. The target file can
be an HTML file, another JSP file, or
a servlet, as long as it is in the
same application context as the
forwarding JSP file. The lines in the
source JSP file after the
element are not
processed.
e.g.
<jsp:forward page="/servlet/ServletCallingJsp" />
Check Advanced JSP Sample : JSP-Servlet Communication:
http://www.oracle.com/technology/sample_code/tech/java/jsps/ojsp/jspservlet.html
Sure you can, simply include it in your action in the form. But you have to write the correct doPost or doGet to handle the request!
If you want to call a particular servlet method than you also use Expression Language. For example, you can do something like:
Servlet
ForexTest forexObject = new ForexTest();
request.setAttribute("forex", forexObject);
JSP
<body bgcolor="#D2E9FF">
Current date : ${forex.rate}
</body>
I don't understand why i cannot include a class into my jsp file.
So, the file i want to use is:
public_html/admin/dashboard.jsp
i have this code:
<%#page import="frontEnd.General"%>
<%
String getBasePath = General.getBasePath(request);
%>
the class i want to include is located:
public_html/WEB-INF/classes/frontEnd/General.class
but when i do this i recieve the error:
HTTP Status 500 - Unable to compile class for JSP
Can you help me with this?
Thanks!
another relevant example:
i have a page, page.jsp in route that has this code on the top:
<%#page import="frontEnd.General"%>
<%
String getBasePath = General.getBasePath(request);
%>
if i access like this:
www.mydomain.com/page.jsp - works, the class is found
if i move the file into a directory (let's say "admin") and try to access the file like:
www.mydomain.com/admin/page.jsp - i recieve the error that the class is not found
Check the package structure of your server. Most probably it doesnt find the class in your structure hence it throw compilation error.
Try importing other classes and check whether problem still comes.
I recently upgraded Spring framework from 3.1.2 to 4.1.1. Also upgraded to Tomcat 8 and Java 8. I am also using Tiles 2.2.2.
My web page loads fine using Spring 4 and problem comes when I do a form submission. The URL request changes and leaves out the webapp name.
For e.g., when I do a form submission,
the URL that is expected is supposed to be http://xx.xx.xx.xx/webappname/createuser/submit.
But the URL changes to http://xx.xx.xx.xx/createuser/submit. And thus, throws a "Requested resource is not available " error.
I did not have this problem when I was using Spring 3.1.2, Tomcat 7, Java 7.
May I know what I am missing?
Thank you,
Whiskers
EDIT :
My jsp view goes like
<form:form method="post" action = "/createuser/submit" commandName = "createForm" >
.....
< /form>
Prepend your hyperlinks with:
${pageContext.request.contextPath}
See the accepted answer here
Your action URL is start with root change your action URL to
action = "createuser/submit"
Or used <c:url ... /> tag to create URL and give it to action as shown below
<c:url value="createuser/submit" var="myActionUrl" />
<form:form action="${myActionUrl}" .... >
May this will help you.
The javadoc of the javax.servlet.AsyncContext interface says:
In the event that an asynchronous operation has timed out, the
container must run through these steps:
Invoke, at their onTimeout method, all AsyncListener instances registered with the ServletRequest on which the asynchronous
operation was initiated.
If none of the listeners called complete() or any of the dispatch() methods, perform an error dispatch with a status code
equal to HttpServletResponse.SC_INTERNAL_SERVER_ERROR.
If no matching error page was found, or the error page did not call complete() or any of the dispatch() methods, call complete().
But I couldn't find the meaning of "error dispatch" anywhere.
In fact there was an Apache bug that exclaimed the same. (In their exact words: "I haven't seen the def. of 'error dispatch', too")
But of course, there must be a clear definition for this and how to use it.
Does anyone know?
Dispatches made by the container during exceptions/errors are called error dispatches. These are usually dispatches to error pages. There is no way to directly do an error dispatch as I know it.
A request that has come through an error dispatch will have dispatcher type set to DispatcherType.ERROR. (In the servlet's service method code, you can get the dispatch type using getDispatcherType())
The following six request scoped attributes will also be set in error dispatches.
"javax.servlet.error.exception"
"javax.servlet.error.exception_type"
"javax.servlet.error.message"
"javax.servlet.error.request_uri"
"javax.servlet.error.servlet_name"
"javax.servlet.error.status_code"
So if you have an error page to which the container redirects errors, you know you can read those six attributes for more information.
http://docs.oracle.com/javaee/6/api/javax/servlet/DispatcherType.html
http://docs.oracle.com/javaee/6/api/javax/servlet/RequestDispatcher.html
You can setup an error dispatch by using tag in deployment descriptor (web.xml). For example if you added an error-page tag for 404 error code, then the container will dispatch to that page when a page not found error occurs. In that error page, you can use code like request.getAttribute("javax.servlet.error.message") to retrieve details about the error. Example ...
web.xml :
<web-app>
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>
</web-app>
error.jsp :
<!DOCTYPE html>
<html>
<head>
<title>404 Error</title>
</head>
<body>
The page was not found. You requested <%= request.getAttribute("javax.servlet.error.message") %> but it was not found. Sorry.
</body>
</html>
In the above sample application, if a client requested page is not found or you use response.sendError("404", "...") somewhere, the container will do an error dispatch to error.jsp.
The JSP error handling mechanism (using "errorPage" and "isErrorPage" page directives) also applies here.
Another information which is not directly related to the question but which I have seen not clearly mentioned in almost all places, including the answer above is that the error dispatch is technically NOT "redirect", it's rather internal forward. For beginners this might seem confusing as its usually written all over as "container does the redirect to the error page". So the moment your container sees an http error code / uncaught exception being sent by any of the resource it begins to look into the web xml to see if there are any handler defined and if present then it appropriately forwards the request to that resource using a request dispatcher. Then obviously all the information mentioned in the above answer applies.
If some one however wants to do an redirect, they can do so in filter or servlet or from anywhere they have response object available.
Trying to access a Servlet from a button on HTML page
//Html Page
FORM method="GET" action="/StudentDBServlet">
yada yada
INPUT type="submit" value="Register" name="Register">
//My Servlet
#WebServlet(name="StudentDBServlet", urlPatterns={"/StudentDBServlet"})
public class StudentDBServlet extends HttpServlet {
The servlet is located in Package com.zzz.studentregistration
When I hit the "Register" Button this is the url create
http://localhost:8080/StudentDBServlet?FirstName
but it needs to be this to work properly
http://localhost:8080/com.zzz.studentregistration/StudentDBServlet?FirstName
How or where do I add the package name to the Servlet definition?
I tried adding to various parts if #WebServlet but no luck ???
Thanks
The servlet container couldn't care less about your servlets' package. Only the urlPatterns matter. Your code above should work just fine. It is not clear what (and why) do you want to achieve. You can simply write:
#WebServlet(urlPatterns={"/com.zzz.studentregistration/StudentDBServlet"})
But then the form has to point to this particular servlet:
<FORM method="GET" action="/com.zzz.studentregistration/StudentDBServlet">