java.lang.ClassCastException: Servlet.Telnet cannot be cast to javax.servlet.Servlet - java

I want to implement a servlet and call it in a WebApp.
I am constantly get java.lang.ClassCastException: Servlet.Telnet cannot be cast to javax.servlet.Servlet from the Apache Tomcat Server. I made sure my class extends HttpServlet this is my code:
package Servlet;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.net.telnet.TelnetClient;
public class Servlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
TelnetClient telnet = new TelnetClient();
telnet.connect(request.getParameter("router"), 23);
PrintStream output = new PrintStream(telnet.getOutputStream());
output.println(request.getParameter("login"));
output.flush();
output.println(request.getParameter("password"));
output.flush();
out.printf("SUCCESS");
telnet.disconnect();
} catch (Exception e) {
e.printStackTrace();
out.printf("ERROR");
}
}

I renamed the package and the class and it works perfectly.

Related

What is missing in the following steps to test db connection from eclipse using tomcat and java ?am getting 404 error

My code to test db connection from eclipse is given below
import java.io.IOException;
import java.io.PrintWriter;
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.sql.*;
#WebServlet("/TestDbServlet")
public class TestDbServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user="user01";
String pass="pass01";
String jdbcUrl = "jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC";
String driver = "com.mysql.cj.jdbc.Driver";
// get connection to database
try {
PrintWriter out = response.getWriter();
out.println("Connecting to database: " + jdbcUrl);
Class.forName(driver);
Connection myConn = DriverManager.getConnection(jdbcUrl, user, pass);
out.println("SUCCESS!!!");
myConn.close();
}
catch (Exception exc) {
exc.printStackTrace();
throw new ServletException(exc);
}
}
am getting 404 error when i run this on server .I have added mysql-connector-java8.0.11.jar to lib folder of webinf.am using tomcat9 with java14 .
Normally, if you are getting a 404 error it means that the page is not found (Probably if your url isn't correct), if there is an error in the doGet Method "The connection to the database part" the server will respond with a 500 error.
https://www.codejava.net/java-ee/servlet/solved-tomcat-error-http-status-404-not-found
Let me know if that helped.

Package doesnt exist error when trying to import my own package to servlet

im trying to import my own packages to a servlet im making, using tomcat.
The two java files im working with are the servlet (movieServlet.java), and another class im trying to import from a package (Movie.java)
The hierarchy of folders is:
classes
|
+--movieServlet.java
|
+--movie
|
+--Movie.java
movieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import movie.Movie;
#WebServlet(urlPatterns = {"/movieServlet"})
public class movieServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
Movie Movie = new Movie();
request.setAttribute("movies", Movie.getAllMovies());
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsps/movies.jsp");
dispatcher.forward(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsps/movieDetails.jsp");
dispatcher.forward(request,response);
}
}
and this is the top of Movie.java (its a long file)
package movie;
import java.util.*;
import java.util.List;
import javax.sql.*;
import java.sql.*;
import javax.naming.InitialContext;
public class Movie implements java.io.Serializable
{
private static DataSource dataSource = null;
private static Connection c = null;
private int id;
private String title;
private String url;
private int year;
public Movie(){}
if theres more info needed please ask :), this has been reallllly bugging me.
I am new here so excuse me if my answer is not perfect. As you have mentioned that you want to import your own package which contains Movie class. I tried to implement all your main methods and it's running perfect and I am getting my value from Movie.java.
movieServlet.java
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;
import movie.Movie;
public class movieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
Movie Movie = new Movie();
request.setAttribute("movies", Movie.getAllMovies());
out.println(request.getAttribute("movies"));
}
}
Movie.java
package movie;
public class Movie {
String s;
public Movie(){
s="hello zDoctor";
}
public String getAllMovies(){
return s;
}
}
servlet output
file structure

Addition of web service access in servlet unrecognized/unresolved; seen as "type".

I am trying to create a simple servlet (tomcat) that accesses a database, then a USDA web service. I've successfully deployed/tested the database connectivity. When I added the web service access, eclipse reports the problem: AwdbWebService_Service cannot be resolved to a type.
The hour is late... I just don't see why this won't resolve as a service instance.
The error is tripped by this line:
AwdbWebService_Service lookup = new AwdbWebService_Service(wsURL,new QName("http://www.wcc.nrcs.usda.gov/ns/awdbWebService","AwdbWebService"));
Here is the code:
package localdomain.localhost;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URL; //added for usda webservice
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.servlet.ServletConfig;
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 javax.sql.DataSource;
import javax.xml.namespace.QName; // added for usda webservice
import usda.nrcs.wcc.awdbWebService.*;
#WebServlet(value = "/MyServlet")
public class MyServlet extends HttpServlet {
// use this for usda reservoir station values later
static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
protected final Logger logger = Logger.getLogger(getClass().getName());
#Resource(name = "jdbc/mydb", lookup = "jdbc/mydb")
private DataSource dataSource;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
logger.info("Init");
System.out.println(getClass().getName() + ".init");
}
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
PrintWriter writer = resp.getWriter();
writer.println("<html>");
writer.println("<head><title>MyServlet</title></head>");
writer.println("<body><h1>MyServlet</h1>");
writer.println("<h2>DataSource</h2>");
Connection conn = null;
try {
writer.println("Datasource: " + dataSource + "<br/><br/>");
conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("select 1");
while (rst.next()) {
writer.println("Resultset result: " + rst.getString(1) + "<br/><br/>");
}
rst.close();
stmt.close();
conn.close();
writer.println("SUCCESS to access the datasource");
// Now try accessing usda
URL wsURL = new URL("http://www.wcc.nrcs.usda.gov/awdbWebService/services?wsdl");
AwdbWebService_Service lookup = new AwdbWebService_Service(wsURL,new QName("http://www.wcc.nrcs.usda.gov/ns/awdbWebService","AwdbWebService"));
m_webService = lookup.getAwdbWebServiceImplPort();
} catch (Exception e) {
e.printStackTrace(writer);
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
writer.println("</body></html>");
}
}
For those following this thread:
The package statement at the start of the java classes I generated with wsimport begins with:
package gov.usda.nrcs.wcc.awdbWebService
My import statement however looked like this:
import usda.nrcs.wcc.awdbWebService.*;
In essence I placed the source # the wrong level and defined the build config to point incorrectly for the package references in the java classes. I removed the build reference, moved the tree to begin pointing on the gov level. Now that there wasn't a mismatch, the unresolved type error vanished.

NullPointerException on Apache Server Servlet using JPA

Im trying to display contents of table (test_dept) which is in SQLSERVER
I have created a connection profile also.
I have written a Servlet like below... But Im getting this error.
import java.io.IOException;
import java.io.PrintWriter;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
//import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#SuppressWarnings("serial")
#WebServlet(urlPatterns = "/ServletClient")
public class ServletClient extends HttpServlet
{
#PersistenceUnit
EntityManagerFactory factory;
#SuppressWarnings("rawtypes")
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
//ServletOutputStream out = resp.getOutputStream();
PrintWriter pw = resp.getWriter();
java.util.List list = factory.createEntityManager().createQuery("select f from test_dept f;").getResultList();
pw.println("<html><body bgcolor=silver text=green><table>");
for (Object tdp : list)
{
pw.println("In The Loop");
pw.println("<tr><td>" + ((TestDept) tdp).getDptnam() + "</td></tr>");
}
pw.println("</table>");
pw.println("<font size=35><b>List created AdapChain</b></font>");
pw.println("</body></html>");
}
}
I don't think any version of Apache Tomcat supports injection of EntityManager or EntityManagerFactory objects out of the box.
You need to choose a server platform that supports more of the JavaEE specification.

iText working Google App engine

I'm trying create pdf in java with google app engine but it doesn't work yet:
#SuppressWarnings("serial")
public class GuestbookServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("application/pdf");
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
document.open();
document.add(new Paragraph("Hello World"));
document.close();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is the error:
HTTP ERROR 500
Problem accessing /guestbook. Reason:
com/itextpdf/text/DocumentException
Caused by:
java.lang.NoClassDefFoundError: com/itextpdf/text/DocumentException
I have read the incompatibility with java.awt and java.nio with google appengine. But I don't know how to do it. Is there any special version of itext to google app engine? Or do you know any clue that can help me?
Yes, there's a GAE version of iText. See http://lowagie.com/iPadSchools to watch a demo. The GAE port is distributed by iText Software. There's no link to get it online.
package mx.gob.campeche.sit.web.reportes;
import java.io.IOException;
import java.io.OutputStream;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import mx.gob.campeche.sit.doc.recibo_oficial.ReciboOficial;
#WebServlet("/reciboOficial")
public class ReporteReciboOficialServlet extends HttpServlet {
#Inject
ReciboOficial reciboOficial;
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpServletRequestWrapper srw = new HttpServletRequestWrapper(request);
String folio = "";
if (request.getParameterMap().containsKey("folio")) {
folio = request.getParameter("folio");
System.out.println("contenido" + folio);
}else
if (request.getParameterMap().containsKey("numero")) {
folio = request.getParameter("numero");
System.out.println("contenido" + folio);
}else{
throw new ServletException("No ingreso parametro");
}
byte[] pdfData = reciboOficial.crearReciboOFicialCajas(folio, srw.getRealPath(""));
response.setContentType("application/pdf");
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "inline; filename=\"" +"samplePDF2.pdf" +"\"");
OutputStream output = response.getOutputStream();
output.write(pdfData);
output.close();
}
this is small example, this help

Categories