This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed last month.
I am learning how to use servlet and i copied the example in my book but i keep getting a 404 error. here is the code :
package servlet;
import java.io.IOException;
import` java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SampleServlet2
*/
#WebServlet("/SampleServlet2")
public class SampleServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String[] luckArray = {"超スッキリ","スッキリ","最悪"};
int index = (int) (Math.random()*3);
String luck=luckArray[index];
Date date= new Date();
SimpleDateFormat sdf=new SimpleDateFormat("MM月dd日");
String today=sdf.format(date);
response.getWriter().append("Served at: ").append(request.getContextPath());
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>スッキリ占い</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>"+today+"の運勢は「"+luck+"」です</p>");
out.println("</body>");
out.println("</html>");
}
}
``
I don't really know what to do as the book doesn't include a 404 error and all the topics about servlet are old.
There is no problem in your code.
may be the problem is with your server configuration.
I am using Eclipse IDE and tomcat 9 , and your code is working fine.
Related
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Change default homepage in root path to servlet with doGet
(2 answers)
Closed 1 year ago.
i am learning how to create servlets. i followed this tutorial
https://medium.com/#prashant.srivastava7744/how-to-create-hello-world-servlet-example-using-eclipse-ide-with-tomcat-7-39fdbdc21573
it shows how to create simple hello world servlet.
i followed the steps mentioned in the tutorial but when i run the code via
right click
run as
run on server
i receive
HTTP Status 404 – nicht gefunden"page not found"
and i noticed that despite the end point which stated in the annotation is
#WebServlet("/HelloWorld")
it gets change to be
http://localhost:8080/ServletHelloWorld/
it should be
http://localhost:8080/tHelloWorld/
please let me know how to fix this error
code:
package com.example;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloWorld
*/
#WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public HelloWorld() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("Hello World!");
out.println("</body></html>");
out.close();
}
}
folder structure:
web.xml:
I'm running Apache Tomcat 8 on Eclipse Mars on Windows 7, and here's my piece of code:
import java.io.IOException;
import java.io.PrintWriter;
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("/Main")
public class Main extends HttpServlet {
private static final long serialVersionUID = 1L;
public Main() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("");
pw.println("");
pw.println("");
pw.println("<h1>Example 0</h1>");
pw.println("");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
It starts tomcat, ok, and "Example 0" can be seen when I access localhost. BUT, if I change the string in the response to "Example 1", it takes around 10 min to change it. I'm a beginner in Servlet / Tomcat development, and I'm failing to grasp the reason why the delay occurs. Why that happens??
Not an answer, but I recommend you code web stuffs with Netbeans, there is no doubt Eclipse is the king, but Netbeans does web stuffs better.
I am trying to create a small registeration form using jsp and servlet.
The concept goes like this:
The data being enterd in the jsp form will be checked for duplication by a servlet program.
If duplication exists , then the control must return back to the registeration (jsp) page from where the servlet was called.
I am doing this in eclipse helios.
Servlet program is under the default package under java resources ,
and jsp file is under the web content folder.
My problem is that
I am able to redirect from jsp to servlet;
but when I try to return back to the jsp page from the servlet ,
tomcat server is showing error like:
HTTP Status 404 - /RservletEs/registeration.jsp
type Status report
message /RservletEs/reg.jsp
description The requested resource is not available.
I tried both request.dispatcher() and response.sendRedirect() both are showing same error.
The file path is:
RservletEs/src/ServletCheck
Rservlets/Web Content/registeration.jsp
I have attached the source code below
somebody pls help me out of this
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.collect.ImmutableMap;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import java.util.Map;
import com.google.gson.Gson;
/**
* Servlet implementation class ServletCheck
*/
#WebServlet("/ServletCheck")
public class ServletCheck extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
* /
public ServletCheck() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String clusterName="asdf";
String hostName="localcost";
String index="testdb";
String type="emp_type";
String field="emailId";
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int portNumber=26101;
final TransportClient client = new TransportClient(ImmutableSettings.settingsBuilder().put("cluster.name", clusterName)
.put("client.transport.sniff", true).build());
Settings settings = client.settings();
out.println("**settings:"+ settings);
ImmutableMap<String, String> map = settings.getAsMap();
out.println("**map::"+ map);
((TransportClient) client).addTransportAddress(new InetSocketTransportAddress(hostName, portNumber));
out.println("ES client:" + client);
String firstName=request.getParameter("firstName");
String lastName=request.getParameter("lastName");
String emailId=request.getParameter("emailId");
String age=request.getParameter("age");
String dob=request.getParameter("dob");
String eId=request.getParameter("employeeId");
String value=emailId;
SearchResponse response2 = client.prepareSearch(index)
.setTypes(type)
.setSearchType(SearchType.QUERY_AND_FETCH)
.setQuery(QueryBuilders.termQuery(field, value))
.setFrom(0).setSize(60).setExplain(true).setRouting("1")
.execute()
.actionGet();
SearchHit[] results = response2.getHits().getHits();
int length=results.length;
int i=0;
if (length>0){
response.sendRedirect(request.getContextPath()+"/registeration.jsp");
//request.getRequestDispatcher("/registeration.jsp").forward(request, response);
}
else{
out.println("setting the values");
hr_employee tweet = new hr_employee();
out.println("setting the id");
tweet.setEmployeeId(eId);
tweet.setFirstName(firstName);
out.println("setting the last name");
tweet.setLastName(lastName);
tweet.setEmailId(emailId);
tweet.setDob(dob);
String str=tweet.getEmployeeId();
/* System.out.println("the id is...."+str);
System.out.println("the firstname .... "+tweet.getFirstName());
System.out.println("teh last name....."+tweet.getLastName());
*/
out.println("initiallizing req builder");
final IndexRequestBuilder builder = client.prepareIndex(index, type,str);
out.println("setting source");
builder.setSource(new Gson().toJson(tweet));
out.println("getting response");
final IndexResponse response3 = builder.setRouting("1").execute().actionGet();
out.println("geting connected...");
out.println("ElasticSearchEJBBean:indexDocument:" + index+ ":" + type+ ":" + str + ":index results:" + response3);
response.sendRedirect(request.getContextPath()+"/ServletInsert");
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request,response);
}
}
sounds like there must be some problem with the way u name it.
Try like this:
right click on ur jsp file and select copy qualified name .
then use that name to redirect or dispatch like this:
request.getRequestDispatcher("/registeration .jsp").forward(request,response);
Since jsp is under the web-content folder do this
response.sendRedirect("/registeration.jsp");
or try something like this
response.sendRedirect(request.getSession().getServletContext().getRealPath("/registeration.jsp"));
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 using Eclipse 4.3 kepler on Ubuntu 14.04 and using Apache tomcat 7 , I have successfully created .jsp and .html files in my project but I cannot Run a servlet, I have all jar files added in library . I have read every article on this error 404 ,which I am getting when I launch the following servlet
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
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("/taxProcessor")
public class taxProcessor extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public taxProcessor() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String s=request.getParameter("t1");
int i=Integer.parseInt(s);
String s1=request.getParameter("t2");
int a=Integer.parseInt(s1);
int t=0;
if(i>=500000)
{
t=i*(30/100);
}else if(i>=300000)
{
t=i*(20/100);
}else if(i>=200000)
{
t=i*(10/100);
}
if(a>=60)
{
t=t-(i*(10/100));
}
PrintWriter out=response.getWriter();
out.println("Thank you for Visiting");
out.println("Your Tax Laibality is"+t+"\n");
out.close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
my web.xml file is
and all what I get is this
Instead of web.servlets.newtax.taxProcessor.java use web.servlets.newtax.taxProcessor in the web.xml
BTW your package name is servlet then how come you are giving web.servlets.newtax in the servlet-class tag
Example if in your eclipse your servlet class is in src/somePackageName/ServletClassName then your web.xml must contain the entries like this
<servlet>
<servlet-name>anyName</servlet-name>
<servlet-class>somePackageName.ServletClassName</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>anyName</servlet-name>
<url-pattern>/taxProcessor</url-pattern>
</servlet-mapping>
One more thing as you specified the entries in the web.xml you can remove the annotation#WebServlet("/taxProcessor")
Finally run the servlet as http://localhost:8080/YourProjectName/taxProcessor
In web.xml give /newtax/..../taxProcessor .Dont give /newtax/..../taxProcessor.java and Check from browser by giving the url http://localhost:<port-number>/newtax.taxProcessor. Here give port number to your tomcat server port.Default is 8080
In servlet we can use requestdispatcher and it will forward from one servlet to another servlet with same session in same project.but if i am using different project getRequestDispatcher is not working.its giving 404 error.because its appending servlet name before the url. how can i achieve getRequestDispatcher in different project in same server?
RequestDispatcher rd = request.getRequestDispatcher("/v1/status1/toreply1");
rd.forward(request, response);
In same project getRequestDispatcher working fine. but in different project its not working ?can anyone explain why its happening ..?
You can achieve getRequestDispatcher in different project on same server.
Check out https://stackoverflow.com/a/19273223/1428052
It works on same server for different project by using
getServletContext().getContext() method.
You can follow below steps for detail implementation.
First you need to make changes in below file
(Windows) C:\Program Files\Apache Software Foundation\Tomcat 7.0\conf\context.xml
Set value of crossContext to true.
context.xml
<Context crossContext="true">
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
</Context>
Please note that crossContext="true".
Suppose you have two web applications with name InterServletComm1 and InterServletComm2
having servlets Servlet1 and Servlet1 in each web application respectively. Then the code in each servlets goes as follows:
Servlet1.java
package interServletComm1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Servlet1
*/
#WebServlet("/Servlet1")
public class Servlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Servlet1() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
request.setAttribute("name", "WebApp1");
ServletContext context = getServletContext().getContext("/InterServletComm2");
RequestDispatcher rd = context.getRequestDispatcher("/Servlet2");
rd.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Servlet2.java
package interServletComm2;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Servlet2
*/
#WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Servlet2() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String name = (String) request.getAttribute("name");
pw.println("This is web application 2.");
pw.println("<br>The value received from web application one is: " + name);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Above code sends attribute name from InterServletComm1 and it is received in InterServletComm2.
Please let me know if this answer is not clear.
You have to use the ServletContext of the other web application to get the RequestDispatcher. The other context can be looked up by ServletContext#getContext(String uri):
ServletContext otherContext = request.getServletContext().getContext("/other");
RequestDispatcher rd = otherContext.getRequestDispatcher("/v1/status1/toreply1");