I have written a sample code to pass form data from a html page to a servlet. Here are my source codes,
StudentForm.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Form</title>
</head>Title
<body>
<form action="FormDataServlet" method="get">
FName:<input type="text" name="fName"> <br/>
LName:<input type="text" name="lName"><br/>
<input type="submit" value="submit">
</form>
</body>
</html>
FormDataServlet
package com.kasun.student.form;
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 java.io.IOException;
import java.io.PrintWriter;
/**
* Created by kausn on 5/24/17.
*/
#WebServlet(name = "/FormDataServlet")
public class FormDataServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter printWriter=response.getWriter();
printWriter.print("<html><head></head><body>");
printWriter.print("The F name of the student is "+request.getParameter("fName"));
printWriter.print("The L name of the student is "+request.getParameter("lName"));
printWriter.print("</body></html>");
}
}
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">
<servlet>
<servlet-name>ServletDemo1</servlet-name>
<servlet-class>com.kasun.servlet.demo.ServletDemo1</servlet-class>
</servlet>
<servlet>
<servlet-name>FormDataServlet</servlet-name>
<servlet-class>com.kasun.student.form.FormDataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDemo1</servlet-name>
<url-pattern>/ServletDemo1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>FormDataServlet</servlet-name>
<url-pattern>/FormDataServlet</url-pattern>
</servlet-mapping>
</web-app>
But when I submit the form it says 404 error that is because it is calling the servlet that exists in http://localhost:63342/ServletDemo/web/FormDataServlet?fName=sfddfddfd&lName=dfdf this path. I know for sure that this is where the bug is, but how to fix this? (Please find the screenshot of package structure as below)
Related
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!
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am trying to implement listener program in which i get an HTTP status 500 Error once i submit with the index.html form page which redirect it to Servlet1 class.!
Mylistener.java
import javax.servlet.annotation.WebListener;
import javax.servlet.*;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
#WebListener
public class Mylistener implements HttpSessionListener {
static int total=0, current=0;
ServletContext ctx=null;
public void sessionCreated(HttpSessionEvent e) {
total++;
current++;
ctx=e.getSession().getServletContext();
ctx.setAttribute("total users",total);
ctx.setAttribute("looged users",current);
}
/**
* #see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
*/
public void sessionDestroyed(HttpSessionEvent e) {
current--;
ctx.setAttribute("currentusers",current);
}
}
![enter image description here][1
Servlet1.java
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Servlet1 extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("Text/html");
PrintWriter out=res.getWriter();
String n= req.getParameter("nname");
System.out.println("Welcome"+n);
HttpSession session=req.getSession();
session.setAttribute("uname",n);
ServletContext ctx= getServletContext();
int i=(Integer)ctx.getAttribute("total");
int c=(Integer)ctx.getAttribute("current");
out.println("total users"+i);
out.println("Current users"+c);
out.close();
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="servlet1" method="post">
Enter your name <input type="text" name="nname"><br>
Enter your password : <input type="password" name="npass">
<input type="submit" value="submit">
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
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">
<listener>
<listener-class>Mylistener</listener-class>
</listener>
<servlet>
<servlet-name>First</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>First</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
]
Error:
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
Servlet1.doPost(Servlet1.java:25)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.59 logs.
check null condition before casting.
int i=0,c=0;
if(ctx.getAttribute("total") != null){
i=(Integer)ctx.getAttribute("total");
}
if(ctx.getAttribute("current") != null){
c=(Integer)ctx.getAttribute("current");
}
out.println("total users"+i);
out.println("Current users"+c);
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}
Actually i'm trying to display the details obtained from JSP form with servlet. But I'm not able to display the JSP page. But I can see the program entering into the POST method in Servlet.
Here is my code,
Startup.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="controlServlets" method="post">
<input type="text" name="name"/><br>
<input type="text" name="group"/>
<input type="text" name="pass"/>
<input type="submit" value="submit">
</form>
</body>
</html>
web.xml
<web-app>
<servlet>
<servlet-name>controlServlets</servlet-name>
<servlet-class>com.selenium8x8.servlet.ControlServlets</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>controlServlets</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
ControlServlets.java
import java.io.IOException;
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;
#WebServlet("/ControlServlets")
public class ControlServlets extends HttpServlet {
private static final long serialVersionUID = 1L;
public ControlServlets() {
super();
// TODO Auto-generated constructor stub
}
// #Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String group = request.getParameter("group");
String pass = request.getParameter("pass");
System.out.println("Name :"+ name);
System.out.println("group :"+ group);
System.out.println("pass :"+ pass);
System.out.println("Post method");
}
}
In console,
I can see the following,
Name :null
group :null
pass :null
Post method
Please Help...
Part I)If you want to use web.xml for your application then you need to make following changes :
1)In Startup.jsp change the action attribute of <form> tag to
<form action="ControlServlets" method="post">
↑
2)In web.xml change the <servlet-mapping> to
<servlet-mapping>
<servlet-name>controlServlets</servlet-name>
<url-pattern>/ControlServlets</url-pattern>
</servlet-mapping>
3)In ControlServlets.java several changes as, in web.xml you mentioned
<servlet-class>com.selenium8x8.servlet.ControlServlets</servlet-class>
↑
This is the package name, so you must have first statement in ControlServlets.java
package com.selenium8x8.servlet; //in your code it is missing
Then, comment following two lines
//import javax.servlet.annotation.WebServlet;
and
//#WebServlet("/ControlServlets")
Now, run application, it will give you desired output.
Part II) If you want to use #WebServlet annotation, as you did
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("/ControlServlets")
public class ControlServlets extends HttpServlet {
...
.....
.......
}
Then, no need for web.xml. The above does basically the same as following:
<servlet>
<servlet-name>controlServlets</servlet-name>
<servlet-class>com.selenium8x8.servlet.ControlServlets</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>controlServlets</servlet-name>
<url-pattern>/ControlServlets</url-pattern>
</servlet-mapping>
For using #WebServlet annotation you need Java EE 6 / Servlet 3.0
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.