Issue passing JSON object to HttpServlet - java

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>

Related

doGet() cannot get any data from model

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);
}

Java servets request.getMethod() not working

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.

How to process href parameters jsp

I have little test page, but I can't get request parameters an don't understand why.
Test page have "href" links like this:
Show smth
Simple controller:
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class Controller extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
processRequest(request, response);
}
protected void processRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
StringBuilder sb = new StringBuilder("Do SMTH<br>");
sb.append("Other will be later...<br>");
String s = sb.toString();
request.setAttribute("result", s);
RequestDispatcher view = request.getRequestDispatcher("test.jsp");
view.forward(request,response);
}
}
web.xml:
<?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_3_1.xsd"
version="3.1">
<welcome-file-list>
<welcome-file>main.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>/main.jspc</url-pattern>
</servlet-mapping>
</web-app>
and test page, where i want to show some obtained parameters:
test.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<%
out.print("<br>" + "Parameter: ");
request.getParameter("param");
out.print("<br>"+ "URL:");
request.getRequestURL();
out.print("<br>" + "Result:");
request.getParameter("result");
%>
</body>
</html>
But test page showing empty parameters, I don't understand why.
The use of scriptlets (those <% %> things) in JSP is old one and discouraged since the birth of taglibs(JSTL) and EL(Expression Language, those ${} things).
Use below code access your parameter :
Parameter : ${params} <br>
Result : ${result} <br>
URL : ${pageContext.request.requestURI}

browser shows 404 error [duplicate]

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 servlet and making my first servlet using eclipse.I have made Index.html, Login.java and WelcomeServlet.java. But whenever I am trying to access the using
localhost:8080/ServletExample/
It shows 404 error.Here are the codes..
Index.html
<form action="Login" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
Login.java
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet")) {
RequestDispatcher rd=request.getRequestDispatcher("WelcomeServlet");
rd.forward(request, response);
} else {
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
}
WelcomeServlet.java
package java.io;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/WelcomeServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
package java.io;
why u put this line in WelcomeServlet.java.
You're mapping to 'WelcomeServlet' not 'ServletExample'.
Try going to localhost:8080/WelcomeServlet
EDIT: There shouldn't be a trailing slash, sorry!
Make sure ur projrct name is ServletExample.
localhost:8080/ServletExample/index.html

Java Servlet JSP does not print out attribute

I'm trying to write a servlet using generated HTML code, rather then printing out static HTMLs.
I'm using Eclipse-EE Europa and Tomcat 6.
I tried to use the flowing tips from HERE
But instead of printing the desired attribute It seems that the jsp ignoring the attribute or the attribute is empty.
Here is the servlet:
package com.serv.pac;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
* Servlet implementation class for Servlet: testServlet
*
*/
public class testServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#HttpServlet()
*/
public testServlet() {
super();
}
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "doGet response";
request.setAttribute("message", message);
request.getRequestDispatcher("/testServlet/WEB-INF/index1.jsp").forward(request, response);
PrintWriter out = response.getWriter();
out.println("the servlet");
}
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("first servlet");
}
}
Here is the JSP
<!doctype html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: ${message}</p>
</body>
</html>
And the following is the :
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>servlet1_test</display-name>
<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>index1.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>testServlet</display-name>
<servlet-name>testServlet</servlet-name>
<servlet-class>com.serv.pac.testServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/testServlet</url-pattern>
</servlet-mapping>
</web-app>
And that is what I'm getting in the browser:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: </p>
</body>
</html>
As one may see there is nothing after the "Message" in the html body, as if the message attribute is empty.
Thank You
The only way I can see this happenning is you aren't actually accessing your Servlet.
You've declared a <welcome-file>
<welcome-file>index1.jsp</welcome-file>
So if you try to hit
localhost:8080/YourContextPath
the default Servlet will render and send you that jsp with a missing message attribute.
If you want to hit your actual Servlet, you need to use
localhost:8080/YourContextPath/testServlet
Note that you need to change
request.getRequestDispatcher("/testServlet/WEB-INF/index1.jsp").forward(request, response);
to
request.getRequestDispatcher("/WEB-INF/index1.jsp").forward(request, response);
and move your file under WEB-INF.

Categories