Java servets request.getMethod() not working - java

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.

Related

Asynchronous Servlets or Filters don't work

I'm new to Java EE and was about to learn to use asynchronous Servlets. I created a web application with a simple index.jsp from which the servlet is called after pressing a button. I always get the following exception:
java.lang.IllegalStateException: Request is within the scope of a
filter or servlet that does not support asynchronous operations
But I set async-supported to true as annotation in the servlet or in web.xml or in both ways. I was searching for hours through similar questions here but I couldn't find a solution. I'm using NetBeans 8.0.2 and glassfish server 4.1 that comes along with NetBeans. Here is my index.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Async Test</h1>
<form method="get" action="Asynctest">
<input type="submit"
value="Start test">
</form>
</body>
</html>
the Asynctest servlet:
package Controller;
import java.io.IOException;
import javax.servlet.AsyncContext;
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(asyncSupported = true, name = "Asynctest", urlPatterns = {"/Asynctest"})
public class Asynctest extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
AsyncContext ac = request.startAsync(request, response);
}
#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);
}
}
and the web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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">
<servlet>
<servlet-name>Asynctest</servlet-name>
<servlet-class>Controller.Asynctest</servlet-class>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>Asynctest</servlet-name>
<url-pattern>/Asynctest</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
It makes me crazy.. Thanks for your help!

Form submit not working in servlet application

Below are the web.xml, servlet and jsp code
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MyServlet
*/
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String userName = request.getParameter("userName");
PrintWriter out = response.getWriter();
out.println("hello "+userName+" how are you ?");
}
}
JSPCode:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
This is First Servlet
<form action="firstTest">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="userName"/></td>
</tr>
<tr>
<td> Password:</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td colspan="2"><input name = "sumbit "type="submit" /></td>
</tr>
</table>
</form>
</body>
</html>
Web.xml Code:
<?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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Trial</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/firstTest</url-pattern>
</servlet-mapping>
</web-app>
when i give URL http:localhost:8080/Trial the Index.jsp is coming but when i gave username and password the URL is chaning to http:localhost:8080/firstTest instead of http:localhost:8080/Trial/firstTest and i am getting 405 error "Tomcat error HTTP Status 405 - HTTP method GET is not supported by this URL" is anything wrong in my code
typo...
protected void doGost
change to doPost or doGet...
In your jsp code form tag you have not specified method name, and by default it use GET method, so just replace this code, I hope it will work :
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName");
PrintWriter out = response.getWriter();
out.println("hello " + userName + " how are you ?");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
For to resolve this type of typo errors before we deploy into the server
We use #override annotation for to test whether the method is overloaded method or not. When ever you compiled the java it will throw exception. Actually compiler will check for syntactic errors etc. But in this scenario compiler treated doGost() is also a method by using above annotation at the compilation level only developer can understand where the problem occurred.
So. My suggition is #override for overriding methods.

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}

Issue passing JSON object to HttpServlet

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>

HTTP Status 405 - HTTP method POST is not supported by this URL

I try to send some data but it seems like the Controller could not be clear found or could not handle the request.
test.jsp
<%# page errorPage="exception.jsp"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page session="true" import="java.io.*,java.util.*"%>
<%# page import="eng.ku.sku.exceed_vote.knt.*"%>
<form name="AddForm" action="addtext" method="POST">
<input type="hidden" name="todo" value="add">
Add text:<input type="text" name="text" />
<input type="submit" value="Add">
</form>
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<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_2_5.xsd" version="2.5">
<servlet>
<servlet-name>exceed</servlet-name>
<servlet-class>eng.ku.sku.exceed_vote.knt.Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>exceed</servlet-name>
<url-pattern>/addtext</url-pattern>
Controller.java
package eng.ku.sku.exceed_vote.knt;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
#WebServlet("/addtext")
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response); // Same as doPost()
}
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Retrieve the current session, or create a new session if no session exists.
HttpSession session = request.getSession(true);
System.out.println("HIIEER");
// Retrieve the shopping cart of the current session.
// For dispatching the next Page
String nextPage = "";
String todo = request.getParameter("todo");
// Dispatch to checkout.jsp
nextPage = "/checkout.jsp";
response.sendRedirect(nextPage);
return;
}
}
I read a lot of other topics but didnt find a solution. I hope u can help me :)
Okay it was a wrong config of Tomcat.
It didn't sync the project changes.

Categories