I am using apache tomcat server. I have written this ResponseServlet.java file but when I try to access it I obtain an error. This is the ResponseServlet.java file which is saved in the ajaxgreetings folder. I compiled it and saved the ResponseServlet.class file in the ajaxgreetings/WEB-INF/classes folder
import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.util.Random;
public class ResponseServlet extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
String name = request.getParameter("name");
PrintWriter out = response.getWriter();
if(name == null){
out.println("No name has been given.");
return;
}
out.println(getGreeting() name);
}
catch(IOException e){
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
String getGreeting(){
switch((new Random()).nextInt(5)){
case 0: return "Hello, ";
case 1: return "Nice to meet you, ";
case 2: return "Hi, ";
case 3: return "Yo, ";
case 4: return "Hey, ";
}
return "Hello, ";
}
}
This is the web.xml file code saved in the ajaxgreetings/WEB-INF folder
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<display-name>A greetings application</display-name>
<description>Asks the user's name and then greets them</description>
<servlet>
<servlet-name>ResponseServlet</servlet-name>
<description>Performs the actual greeting</description>
<servlet-class>ResponseServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ResponseServlet</servlet-name>
<url-pattern>/response</url-pattern>
</servlet-mapping>
</web-app>
When I enter the url http://localhost:8888/ajaxgreetings/response in my browser I obtain the following error. I don't understand why?
CodePudding user response:
By looking into your code, it seems you need doPost() in your ResponseServlet
instead of doGet().
So for doPost, you may need to accept name
via any jsp which will then pass that information to your doPost(), after submission.
CodePudding user response:
You are seeing that error, beacause when you enter your url in browser and hit enter, you are performing GET
request, while on server side are handling post requests.
The doPost() method in servlets is used to process the HTTP POST requests.
So, you need to use doGet()
See: documentation