JSP page not working in Servlet Program - java

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

Related

Unable to pass form data to Servlet

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)

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!

HTTP Status 500 -with description -The server encountered an internal error that prevented it from fulfilling this request [duplicate]

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

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

I downloaded an open-source sql injection application. When I tried to run it gives me error "HTTP method POST is not supported by this URL" and some warnings as well. I am sharing my code and some images.
HTML:
<%# 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>Login Page</title>
<form action="userCheck">
<div>
<input type="text" name="user" value=""/>
<input type="submit" value="Submit"/>
</div>
</form>
</head>
<body>
</body>
</html>
XML:
<?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></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-list>
<servlet>
<servlet-name>userCheck</servlet-name>
<servlet-class>RKINJ.userCheck</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>userCheck</servlet-name>
<url-pattern>/userCheck</url-pattern>
</servlet-mapping>
</web-app>
Java:
package RKINJ;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.sql.*;
import java.sql.Connection;
public class userCheck extends HttpServlet {
protected void processRequest (HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
response.setContentType("'text/html;charset=UTF-8'");
PrintWriter out = response.getWriter();
try {
String user = request.getParameter("name");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/logindb";
// String dbName = "logindb";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "test1234";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url, userName, password);
Statement st = conn.createStatement();
String query = "SELECT * FROM userdetail where id='' + user + ''";
// out.println("Query : " + query);
// System.out.printf(query);
ResultSet res = st.executeQuery(query);
// out.println("Results");
while (res.next()) {
String s = res.getString("name");
out.println("\t\t" + s);
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
} finally {
out.close();
}
}}
These are few warnings I got when run the program
Build path specifies execution environment JavaSE-1.6. There are no JREs installed in the workspace that are strictly compatible with this environment.
Classpath entry C:/Java-Programs/mysql-connector-java-5.1.23-bin-folder.jar/mysql-connector-java-5.1.23-bin.jar will not be exported or published. Runtime ClassNotFoundExceptions may result.
Classpath entry C:/Java-Programs/mysql-connector-java-5.1.23-bin.jar will not be exported or published. Runtime ClassNotFoundExceptions may result.
Invalid location of tag (form). login.jsp /RKINJ/WebContent line 9 JSP Problem.
The serializable class userCheck does not declare a static final serialVersionUID field of type long
You need to override doPost method that in the servlet.
public void doPost(HttpServletRequest req, HttpServletResponse res)
You need to specify the action method
<form action"something" Method="POST / Get">
And you need also to override doPost method that in the servlet.
public void doPost(HttpServletRequest req, HttpServletResponse res)
I wish i was helpfull

JSTL - iterating through array of random integers - not displaying in webPage

I'm trying to iterate through myList (array) of random generated integers using JSP/JSTL.
My code snipet which generates and stores integers, is located in my servlet.
On the other hand,iterating through an arrayList of Strings (see code below) works perfectly but when i try it with arrays based on the same logic, my webpage just doesnt show any unordered list of my random integers.
thank you for helping me out
My Servlet
package be.intec.servlets;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
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;
import be.intecbrussel.entities.Auto;
#WebServlet("/JSTLServlet")
public class JSTLServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String VIEW = "WEB-INF/JSP/JSTL.jsp";
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher(VIEW);
//=======below is the code using Array=====================================
int[] myList = new int[42];
for (int i = 0; i < myList.length; i++) {
myList[i] = (int) (Math.random() * 100);
}
request.setAttribute("mylist", myList);
//=======below is the code using ArrayList=====================================
List<String> names = Arrays.asList("John", "Georges", "Kevin");
request.setAttribute("names", names);
dispatcher.forward(request, response);
}
}
My jstl.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" session="false"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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">
<link rel="stylesheet" type="text/css" href="styles/default.css">
<title>JSTL Expample</title>
</head>
<body>
<h2>Iterate through my array</h2>
<ul>
<c:forEach var="arrayVar" items="${myList}">
<li>${arrayVar}</li>
</c:forEach>
</ul>
<!-- ================================================================================ -->
<h2>Iterate through my arrayList</h2>
<ul>
<c:forEach var="name" items="${names}">
<li>${name}</li>
</c:forEach>
</ul>
</body>
</html>
my web.xml
<?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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ServletsAndJSPExampleProject</display-name>
<welcome-file-list>
<welcome-file>IndexServlet</welcome-file>
</welcome-file-list>
</web-app>
my index Servlet
package be.intec.servlets;
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("/IndexServlet")
public class IndexServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String VIEW = "/WEB-INF/JSP/index.jsp";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher(VIEW);
dispatcher.forward(request, response);
}
}
Output in Browser is :
Iterate through my array:
// here it should be showing my random numbers
Iterate through my arrayList:
// work very well
John
Georges
Kevin
You've used "mylist" as name in your Servlet, and want to fetch the list using ${myList}. The name is case-sensitive!
Change your for each as shown below:
<c:forEach var="arrayVar" items="${mylist}">
<li>${arrayVar}</li>
</c:forEach>

Categories