I think that my folder hierarchy is wrong.
Should the .html and .jsp file is in WEB-INF?
I tried to move them there, but I received an error 404.
No, everything you put in the WEB-INF folder will NOT be available to the users of your web application. Your hierarchy looks OK.
WEB-INF resources not directly visible for the public. You can use webservlet annotation. For example;
#WebServlet(urlPatterns = {"/adminlogin", "/register"})
or servlet mapping(old-fashioned),
web.xml :
<servlet>
<servlet-name>LoginController</servlet-name>
<servlet-class>yourPackage.LoginController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginController</servlet-name>
<url-pattern>/adminlogin/</url-pattern>
<url-pattern>/logout/</url-pattern>
<url-pattern>/register/</url-pattern>
<url-pattern>/userlogin/</url-pattern>
</servlet-mapping>
LoginController
//post get method
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath = request.getServletPath();
if (userPath.equals("/logout")) {
//Your Model
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
} ...
}
Related
I have a simple application to test the communication between html and jsp. My jsp is located in
WEB-INF/test.jsp
Here is the structure of my files:
ProjectA
src
irstServlet.java
Web-Content
test1.html
WEB-INF
test.jsp
Here is the code from servlet
protected void doPost(HttpServletRequest request, response) throws ServletException, IOException {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/test.jsp");
request.setAttribute("userName", request.getParameter("userName"););
dispatcher.forward(request, response);
}
First I have deploy in tomcat start my test1.html: It take me to the servlet: FirstServlet.java and I can enter userName there.
But after i enter the values in and press enter I expect it to forward me to test.jsp which is not working. I get the error:
The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Edited:
In my html I am trying to use it like:
<form method="POST" name="XX" action="/HelloWorldServlet">
Still not working.
Please can someone help me?
Your code does not look like it would compile at all.
Parameter response has no type - should be HttpServletResponse
There is a semicolon (;) after request.getParameter("userName")
Also I'm not sure why you're getting RequestDispatcher from servlet context rather than from the request - then again I've never checked if it makes any difference.
Anyway, I would rewrite doPost method like this:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("userName", request.getParameter("userName"));
req.getRequestDispatcher("/WEB-INF/test.jsp").forward(req, resp);
}
EDIT:
I'm assuimng you have either a correct servlet mapping in your web.xml:
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/HelloWorldServlet</url-pattern>
</servlet-mapping>
or your servlet is annotated with #WebServlet annotation:
#WebServlet("/HelloWorldServlet")
public class FirstServlet extends HttpServlet {
//your code
}
. If neither of those is true, that's your problem right there.
This question already has an answer here:
Change root context for a servlet in an IntelliJ IDEA project
(1 answer)
Closed 4 years ago.
I'm trying to run my simple servlet "Hello".
I have installed tomcat 9.0.6
Than i create a new JavaEE web project in Idea (called test)... after i create new package in src (called servlet), after new servlet file "myServlet".
Project Structure
Here is code:
public class myServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Hello my first Servlet</h2>");
out.println("<br/>");
out.println("Time on the server is: " + new java.util.Date());
out.println("</body></html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
Than i open web.xml and add next lines for servlet and servlet-mapping:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>servlet.myServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myServlet</servlet-name>
<url-pattern>/myServlet</url-pattern>
</servlet-mapping>
</web-app>
After successfully running tomcat ("Artifact is deployed successfully") i try to visit url: http://localhost:8080/test/myServlet Result was page 404... But if i change url to: http://localhost:8080/myServlet result was correct.
Result
What's wrong with url: http://localhost:8080/test/myServlet ???
Need some libraries or what ???
Where is my mistake ???
Also i try with #WebServlet("/myServlet") annotation without servlet and servlet-mapping lines in web.xml - result the same.
You need to define the context path in context.xml - please see this link
http://tomcat.apache.org/tomcat-9.0-doc/config/context.html#Defining_a_context
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I am new to java, I just tried to read initialization parameters from Deployment Descriptor file (web.xml), But got above error?
My web.xml and java file coding coding in snap attached.
My directrory structure is
c:\....tomcat\webapps\dd\web-inf\classes
No error in java class file.
Java file code which is compiled successfully
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet {
String fileName;
public void init(ServletConfig config) throws ServletException {
super.init(config);
fileName = config.getInitParameter("logfilename");
}
protected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
processRequest(request, response);
}
protected void processRequest(HttpServletRequest request,HttpServletResponse
response)throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println(fileName);
out.close();
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>MyServlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
<init-param>
<param-name>logfilename</param-name>
<param-value>value1</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet2</servlet-name>
<url-pattern>/mc11</url-pattern>
</servlet-mapping>
</web-app>
Other detail of my directory and error page i think that my web.xml not working
There are two problems I can see at the moment...
Servlet init parameters
You currently have:
//defining param1
param1
value1
That's not how you define the parameter. You should specify a param-name element containing the name of the parameter, rather than using the name of the parameter as an XML element name.
<init-param>
<param-name>logfilename</param-name>
<param-value>...</param-value>
</init-param>
Also note that // isn't how you write comments in XML - if you wanted a comment, you should have:
<!-- Define the first parameter -->
<init-param>
<param-name>logfilename</param-name>
<param-value>...</param-value>
</init-param>
(The param-value element should have been a hint - if you could really just specify your own element, I'd have expected <logfilename>value in here</logfilename> - having the name specified as an element name, but the value specified with a fixed element name of param-value would have been an odd scheme.)
Servlet mapping
Currently your mapping is:
<servlet-name> FormServlet</servlet-name>
<url-pattern>/ss/</url-pattern>
</servlet-mapping>
I suspect that mapping won't match http://localhost:8080/dd/ss/s.html because you don't have any wildcards in there - it you may well find that it matches exactly http://localhost:8080/dd/ss/. It's not clear where the dd part comes in, but I assume that's a separate part of your configuration. You should try:
<!-- I would recommend removing the space from the servlet
- name *everywhere*. -->
<servlet-name>FormServlet</servlet-name>
<url-pattern>/ss/*</url-pattern>
</servlet-mapping>
If that doesn't work for http://localhost:8080/dd/ss/s.html, see whether it maps http://localhost:8080/ss/s.html - it may be that your engine isn't configured the way you expect elsewhere.
There is no problem with code,I try net beans tool and done assignment perfectly with the help of above code.Before that may be problem in tomcat.
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 1 year ago.
I am writing a Java Servlet, and I am struggling to get a simple HelloWorld example to work properly.
The HelloWorld.java class is:
package crunch;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
I am running Tomcat v7.0, and have already read similar questions, with responses referring to changing the invoker servlet-mapping section in web.xml. This section actually doesn't exist in mine, and when I added it the same problem still occurred.
Try this (if the Java EE V6)
package crunch;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
#WebServlet(name="hello",urlPatterns={"/hello"}) // added this line
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
now reach the servlet by http://127.0.0.1:8080/yourapp/hello
where 8080 is default Tomcat port, and yourapp is the context name of your applciation
You definitely need to map your servlet onto some URL. If you use Java EE 6 (that means at least Servlet API 3.0) then you can annotate your servlet like
#WebServlet(name="helloServlet", urlPatterns={"/hello"})
public class HelloWorld extends HttpServlet {
//rest of the class
Then you can just go to the localhost:8080/yourApp/hello and the value should be displayed. In case you can't use Servlet 3.0 API than you need to register this servlet into web.xml file like
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>crunch.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
Writing Java servlets is easy if you use Java EE 7
#WebServlet("/hello-world")
public class HelloWorld extends HttpServlet {
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Hello World");
out.flush();
}
}
Since servlet 3.0
The good news is the deployment descriptor is no longer required!
Read the tutorial for Java Servlets.
this is may be due to the thing that you have created your .jsp or the .html file in the WEB-INF instead of the WebContent folder.
Solution: Just replace the files that are there in the WEB-INF folder to the Webcontent folder and try executing the same - You will get the appropriate output
For those stuck with "The requested resource is not available" in Java EE 7 and dynamic web module 3.x, maybe this could help: the "Create Servlet" wizard in Eclipse (tested in Mars) doesn't create the #Path annotation for the servlet class, but I had to include it to access successfuly to the public methods exposed.
You have to user ../../projectName/Filename.jsp in your action attr. or href
../ = contains current folder simple(demo.project.filename.jsp)
Servlet can only be called with 1 slash forward to your project name..
My problem was in web.xml file. In one <servlet-mapping> there was an error inside <url-pattern>: I forgot to add / before url.
This is pretty simple and straightforward. I want to throw a 503 error from the servlet side.
response.sendError(503);
When this is thrown, I need it to hit a custom error page. Basically a 503 error page itself, but with a few modifications.
Say I have 503.html, and I added
<error-page>
<error-code>503</error-code>
<location>/503.html</location>
</error-page>
in web.xml.
I created a war file, with a servlet which throws the 503 error, and web.xml with this content. I kept the 503.html in the parent folder location. (Should I keep it elsewhere ?)
I deployed the app in WLS, but this custom 503.html is not getting hit. I am getting the generic 503 error.
Am I missing something?
My code is below:
webapp1.war
->web-inf
->web-inf->classes->prject4->Class1.class
->web-inf->jsp->error->custom.html
web.xml
<?xml version="1.0"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>Class1</servlet-name>
<servlet-class>project2.Class1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Class1</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<error-page>
<error-code>503</error-code>
<location>/WEB-INF/jsp/error/custom.html</location>
</error-page>
</web-app>
class1.java
public class Class1 extends HttpServlet
{
private ServletConfig config;
public void init(ServletConfig config)throws ServletException
{
this.config=config;
}
public void service (HttpServletRequest request, HttpServletResponse response)
throws IOException
{
response.setContentType("text/html");
ServletOutputStream l_out = response.getOutputStream();
response.sendError(503);
}
}
Ok, this was a minor error which I didn't figure out in the beginning.
In my web.xml the servlet-mapping was given as /*, which was causing an infinite loop condition as it throws the same code for which it has been mapped. So I had to adjust the servlet mapping so that Class1 doesn't map to any error pages - like say /images/*.
And then everything started working fine. :)
You can also try handling it with custom Error Handler.
public void service (HttpServletRequest request, HttpServletResponse response)
throws IOException
{
try
{
//some error generating code
throw new Exception("503_Exception");
}
catch(Exception e)
{
response.sendRedirect(HandleError.handle(e, request));
}
}
A separate class to handle errors. This can handle different types of errors.
You can add functionality to log stacktrace, send out emails if something is wrong etc.
public class HandleError{
public static String handle(Throwable t, javax.servlet.http.HttpServletRequest request)
{
String sErrorMsg = t.getMessage();
if (sErrorMsg.equals("503_Exception")) {
request.setAttribute("msg", Constants.EINVALSESSION);
return "/503.html";
}
return "/default_error.html";
}
}
If you are using Maven as your project build tool then it will look in the src/main/webapp directory, so for example our config looks like this:
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/jsp/error/error404.html</location>
</error-page>
and our error404.html sits in the folder:
${PROJECT_NAME}/src/main/webapp/WEB-INF/jsp/error/
If your not using Maven the path in the location will have a base directory of wherever you put your index.jsp
I guess there's a minimum limit on the number bytes your custom error page has. The lower limit is usually 512 Bytes. See Important note for your Custom error pages. I've seen this behavior in Google-Chrome too when using Tomcat.