I have a simple servlet app. In the servlet class, doPost() and doGet() basically get the same data from model class, however, doGet() cannot get any data.
public class ClickerServlet extends HttpServlet {
ClickerModel clickerModel = new ClickerModel();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String servletPath = request.getServletPath();
if (servletPath.equals("/submit")) {
doPost(request, response);
} else if (servletPath.equals("/getResults")) {
doGet(request, response);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String answer = request.getParameter("answer");
clickerModel.addAnswer(answer);
request.setAttribute("recentAnswer", clickerModel.getRecentAnswer());
request.getRequestDispatcher("submit.jsp").forward(request, response);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("ok" + clickerModel.getRecentAnswer());
request.setAttribute("clickerModel", clickerModel);
request.getRequestDispatcher("results.jsp").forward(request, response);
}
}
My ClickerModel class:
public class ClickerModel {
private String recentAnswer;
private HashMap<String, Integer> answers;
public ClickerModel() {
recentAnswer = "";
answers = new HashMap<>();
}
public void addAnswer(String answer) {
recentAnswer = answer;
if (answers.containsKey(answer)) {
answers.put(answer, answers.get(answer) + 1);
} else {
answers.put(answer, 1);
}
}
public void clearAnswers() {
answers = new HashMap<>();
}
public HashMap<String, Integer> getAnswers() {
return answers;
}
public String getRecentAnswer() {
return recentAnswer;
}
}
Anyone knows why I cannot get any data from model using doGet()? Thanks!
For more information:
doPost() is called from a form submission.
<form action="submit" method="post">
<input type="radio" name="answer" value="A"> A<br>
<input type="radio" name="answer" value="B"> B<br>
<input type="radio" name="answer" value="C"> C<br>
<input type="radio" name="answer" value="D"> D<br>
<br><input type="submit" value="submit">
</form>
doGet() is called when I directly paste and hit the url (localhost:something/getResults) in the browser.
And my web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Results</servlet-name>
<servlet-class>Clicker.ClickerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Results</servlet-name>
<url-pattern>/getResults</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Submit</servlet-name>
<servlet-class>Clicker.ClickerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Submit</servlet-name>
<url-pattern>/submit</url-pattern>
</servlet-mapping>
</web-app>
I my understanding, that you place the doGet() method in Results servlet, not same as Submit one.
Submit Servlet:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String answer = request.getParameter("answer");
clickerModel.addAnswer(answer);
request.setAttribute("recentAnswer", clickerModel.getRecentAnswer());
//request.getRequestDispatcher("submit.jsp").forward(request, response);
response.sendRedirect("getResults"); // <---After submit will go to this page.
}
Results Servlet:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("ok" + clickerModel.getRecentAnswer());
request.setAttribute("clickerModel", clickerModel);
request.getRequestDispatcher("results.jsp").forward(request, response);
}
Related
This question already has answers here:
HTTP Status 405 - HTTP method is not supported by this URL
(2 answers)
HTTP Status 405 - HTTP method POST is not supported by this URL java servlet [duplicate]
(5 answers)
Closed 2 years ago.
When i try to run the code in eclipse it won't pass the arguments.
please check the below images url.
But when i individually run the html code it passes the values.
I don't know why this work like this.
My Servlet code is
package com.example;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AddServelet extends HttpServlet
{
public void services(HttpServletRequest req, HttpServletResponse resp) {
int i = Integer.parseInt(req.getParameter("num1"));
int j = Integer.parseInt(req.getParameter("num2"));
int k = i+j;
System.out.println(k);
}
}
and my web.xml code is
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>com.example.AddServelet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
</web-app>
my html code
<html>
<body>
<form action="add">
Number 1: <input type="number" name="num1"><br>
Number 2: <input type="number" name="num2"><br>
<input type="submit">
</form>
</body>
</html>
Can anyone please help me with this.
Thank you in advance.
You need to override the doPost method because you are submitting the form and it's a post request.
public class AddServelet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public AddServelet() {
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
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
int i = Integer.parseInt(req.getParameter("num1"));
int j = Integer.parseInt(req.getParameter("num2"));
int k = i+j;
System.out.println(k);
}
}
override the HttpServlet protected void doGet(HttpServletRequest req, HttpServletResponse resp) method if you want to handle a GET request
I have home page and when I click on reference Servlet don't work and I get error 404. I think issue in web.xml mapping, but a don't understand where. Please help me correct this issue. Thank you.
My web.xml
<!--Homepage.-->
<servlet>
<servlet-name>HomePageServlet</servlet-name>
<servlet-class>ru.pravvich.servlets.HomePageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HomePageServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--Add user in database.-->
<servlet>
<servlet-name>AddUserServlet</servlet-name>
<servlet-class>ru.pravvich.servlets.AddUserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddUserServlet</servlet-name>
<url-pattern>/addition</url-pattern>
</servlet-mapping>
My jsp homepage:
<body>
<ul>
<li>addition</li>
</ul>
</body>
And servlet with doGet method for it:
public class HomePageServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF8");
req.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(req,resp);
}
}
And by http://localhost:8080/items/ I get my home page.
But, when I click on reference from index.jsp, return: HTTP Status [404] – [Not Found]
My addition.jsp same lie in /WEB-INF/views/addition.jsp
My Servlet for work with addition.jsp :
public class AddUserServlet extends HttpServlet {
private DBJoint db;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
db = (DBJoint) getServletContext().getAttribute("db");
db.getDBExecutor().addUser(
new User(req.getParameter("name"),
req.getParameter("login"),
req.getParameter("email")));
req.setAttribute("serverAnswer", "Add ok!");
req.getRequestDispatcher("/WEB-INF/views/answer.jsp").forward(req, resp);
}
}
And addition.jsp:
<body>
<form method="post" action="addition">
<input type="text" required placeholder="name" name="name"><br>
<input type="text" required placeholder="login" name="login"><br>
<input type="text" required placeholder="email" name="email"><br>
<input type="submit" value="add">
</form>
</body>
I would suggest to use try/catch and debugger mode.
And try to use like this your getRequestDispatcher
request.getRequestDispatcher("answer.jsp").forward(request, response);
or
req.getRequestDispatcher("~/WEB-INF/views/answer.jsp").forward(req, resp);
I think you need to get parameter for each of one, and than set. Try this;
public class AddUserServlet extends HttpServlet {
private DBJoint db;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
db = (DBJoint) getServletContext().getAttribute("db");
String Name = request.getParameter("name");
String Login= request.getParameter("login");
String Email= request.getParameter("email");
db.getDBExecutor().addUser(
new User(Name, Login, Email);
//And you need to 'serverAnswer' item in your 'answer.jsp' you know.
request.setAttribute("serverAnswer", "Add ok!");
request.getRequestDispatcher("answer.jsp").forward(req, resp);
}
}
And then you can use getAttribute like this in your answer.jsp,
<%String Answer= (String)request.getAttribute("serverAnswer"); %><%= Answer%>
Don't blame me, just i wanna help to you, i hope so it can be help to you, if you wanna you can look my trial project; https://github.com/anymaa/GNOHesap
Have a nice coding :)
Hello I am trying to create a simple servlet as follows
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Form extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter p=res.getWriter();
p.println("<html><head></head><body bgcolor=\"red\">The request came from"+req.getMethod()+"</body></html>");
}
}
The req.getMethod() should return POST but is giving me a null value.
I am taking the request from an html file coded as follows.
<html>
<body>
<form action="http://localhost:8080/Form" method="GET">
First Name: <input type="text" name="name"/>
<br>
<input type="submit" value="Submit form "/>
</form>
</body>
</html>
here is the web.xml file. Should I make any changes here.
<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
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0" metadata-complete="true">
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<servlet>
<servlet-name>Form</servlet-name>
<servlet-class>Form</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Form</servlet-name>
<url-pattern>/Form</url-pattern>
</servlet-mapping>
</web-app>
You can write this annotation to attach your servlet to your form:
#WebServlet("/Form")
public class Form extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... }
}
You will have to import javax.servlet.annotation.WebServlet.
I hope you can help handle problem with endless loop in servlet. Such problems usually causes wrong servlet-mapping (usualy it's "/*"). But in my case, it has specific value - name of conrete jsp file.
Servlet:
public class TrainsListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
EmployeeService employeeService = new EmployeeServiceImpl();
List<Train> trains = (List<Train>) employeeService.getTrains();
request.setAttribute("trains", trains);
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher("/getTrainsList.jsp");
dispatcher.forward(request, response);
}
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);
}
}
web.xml:
...
<servlet>
<servlet-name>TrainsList</servlet-name>
<display-name>TrainsList</display-name>
<description></description>
<servlet-class>ru.tsystems.jsproject.sbb.Servlets.TrainsListServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TrainsList</servlet-name>
<url-pattern>/getTrainsList.jsp</url-pattern>
</servlet-mapping>
...
getTrainsList.jsp:
...
<c:forEach var="train" items="${trains}">
<tr>
<td><c:out value="${train.getNumber()}" /></td>
<td><c:out value="${train.getSeatsCount()}" /></td>
<td><c:out value="${train.getFrequence()}" /></td>
</tr>
</c:forEach>
...
it's all causes endless loop in processRequest method. Please help,
tell me what I am doing wrong?
Map it with html file
<servlet-name>TrainsList</servlet-name>
<url-pattern>/getTrainsList.html</url-pattern>
And follow http://localhost:8080/.../getTrainsList.html and you will get as response from Servlet getTrainsList.jsp
I have an html form that I want to pass to a servlet when the form is submitted. The form info is:
<form method="post" action = "/directory" name="dirinit" id="srchform">
and the jQuery code I'm trying to use to post is:
$(document).ready(function(){
$("form").on("submit", function(event){
event.preventDefault();
var formData = JSON.stringify(jQuery("form").serializeArray());
$.post("/directory", formData)
});
});
The servlet is set up as:
public class NewDirectory extends HttpServlet{
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/json");
String form = request.getParameter("formData");
System.out.println(form);
}
}
My web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>NewDirectory</display-name>
<servlet>
<servlet-name>newdirectory</servlet-name>
<servlet-class>edu.msu.is.directory.newdirectory</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>newdirectory</servlet-name>
<url-pattern>/directory</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
When I try to post the form data, I get a 404 error saying that the url was not found. I'm pretty new to servlets, so I'm not even sure I'm setting the the servlet up correctly.
Your code should be something like this :
Servlet :
package edu.msu.is.directory;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class NewDirectory extends HttpServlet
{
private static final long serialVersionUID = 1L;
public NewDirectory()
{
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/json");
String form = request.getParameter("formData");
System.out.println(form);
}
}
web.xml
...
<servlet>
<servlet-name>NewDirectory</servlet-name>
<servlet-class>edu.msu.is.directory.NewDirectory</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NewDirectory</servlet-name>
<url-pattern>/directory</url-pattern>
</servlet-mapping>
...
Html Form :
<form method="post" action="directory" name="dirinit" id="srchform">
Javascript :
$(document).ready(function(){
$("form").on("submit", function(event){
event.preventDefault();
var formData = JSON.stringify(jQuery("form").serializeArray());
$.post("directory", formData)
});
});
Note : If you are getting 404 error that means either you are accessing different url or your servlet/jsp is not mapped properly.
Here you set your action url as /directory which should be either only directory or /YourProjectContextRootPath/directory.
<servlet-class>edu.msu.is.directory.newdirectory</servlet-class>
is case sensitive, should be
<servlet-class>edu.msu.is.directory.NewDirectory</servlet-class>