Java class loading from jar file at runtime in Tomcat - java

I need to load some servlet from jar file and map it to the URL in Tomcat.
Servlet code is
package net.arturik.mymodulepackage;
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;
#WebServlet(name = "QWERTY", urlPatterns = {"/qqq"})
public class QWERTY extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet QWERTY</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet QWERTY at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
#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);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Servlet compiled and stored in file MyModulePackage-1.0-SNAPSHOT.jar.
In Java Web App I has ServletContextListenerImpl class:
package net.arturik.testosgispring;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebListener;
#WebListener
public class ServletContextListenerImpl implements ServletContextListener {
#Override
public void contextInitialized(final ServletContextEvent sce) {
try {
System.out.println("++++++++++++++");
final ServletContext servletContext = sce.getServletContext();
//////////////////////////////////////////////
String pathToJar = "m:\\myhostingpanel\\myhostingpanel\\Tests\\MyModulePackage\\target\\MyModulePackage-1.0-SNAPSHOT.jar";
JarFile jarFile = new JarFile(pathToJar);
Enumeration e = jarFile.entries();
URL[] urls = {new URL("jar:file:" + pathToJar + "!/")};
URLClassLoader cl = URLClassLoader.newInstance(urls, this.getClass().getClassLoader());
while (e.hasMoreElements()) {
JarEntry je = (JarEntry) e.nextElement();
if (je.isDirectory() || !je.getName().endsWith(".class")) {
continue;
}
// -6 because of .class
String className = je.getName().substring(0, je.getName().length() - 6);
className = className.replace('/', '.');
Class c;
Object obj;
try {
System.out.println("className !!! " + className);
c = cl.loadClass(className);
obj = c.newInstance();
System.out.println(c.getPackage() + " " + c.getName());
Class noparams[] = {};
// Method method = c.getDeclaredMethod("qqq", noparams);
// method.invoke(obj, null);
// MyInter obj1 = (MyInter) c.newInstance();
// obj1.qqq();
System.out.println("registering");
final ServletRegistration.Dynamic dynamic = servletContext.addServlet("QWERTY", c);
dynamic.addMapping("/qqq");
final Map<String, ? extends ServletRegistration> map = servletContext.getServletRegistrations();
for (String key : map.keySet()) {
System.out.println("Registered Servlet: " + map.get(key).getName());
}
System.out.println("end of registering ");
} catch (Exception ex) {
ex.printStackTrace();
}
}
//////////////////////////////////////////////
} catch (IOException ex) {
Logger.getLogger(ServletContextListenerImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void contextDestroyed(final ServletContextEvent sce) {
//NO-OP
}
}
This code got output
++++++++++++++
className !!! net.arturik.mymodulepackage.QWERTY
package net.arturik.mymodulepackage net.arturik.mymodulepackage.QWERTY
registering
Registered Servlet: default
Registered Servlet: jsp
Registered Servlet: QWERTY
Registered Servlet: T1
Registered Servlet: mvc-dispatcher
Registered Servlet: T2
Registered Servlet: T3
end of registering
As we can see - servlet registered successfully.
But if I try to open page /qqq , Tomcat got Exception
22-Nov-2014 02:07:56.846 SEVERE [http-nio-8082-exec-5] org.apache.catalina.core.StandardWrapperValve.invoke Allocate exception for servlet QWERTY
java.lang.ClassNotFoundException: net.arturik.mymodulepackage.QWERTY
As I understand - it is a class visibility problem - my class initialized by URLClassLoader and my class doesn't passed to the main (system) Class Loader.
How can I pass my class, loaded by URLClassLoader to the system class loader for global visibility?

Related

I am trying to build a web application where someone can upload multiple file at once but i get the error request cannot be casted to request context

package Connectivity;
import java.io.File;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
#WebServlet("/upload")
#MultipartConfig
public class upload extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws
ServletException{
try { boolean isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (isMultipart)
{
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
// Parse the request
List<FileItem> items = upload.parseRequest((RequestContext) request);
Iterator<FileItem> iterator = items.iterator();
while (iterator.hasNext())
{
FileItem item = (FileItem) iterator.next();
if (!item.isFormField())
{
String fileName = item.getName();
File uploadedFile = new File("C:\\Users\\Ragul prasath\\Desktop\\Register\\src\\main\\webapp\\uploaded\\"+fileName);
System.out.println(uploadedFile.getAbsolutePath());
if(fileName!="")
item.write(uploadedFile);
else
out.println("file not found");
out.println("File Uploaded Successfully....");
}
else
{
}
}
}
catch (Exception e)
{
out.println(e);
}
}
else
{
out.println("Not Multipart");
}}
catch(Exception f) {
System.out.println(f);
}
}}
This is my code.i get the error
java.lang.ClassCastException: class
org.apache.catalina.connector.RequestFacade cannot be cast to class
org.apache.tomcat.util.http.fileupload.RequestContext
(org.apache.catalina.connector.RequestFacade and
org.apache.tomcat.util.http.fileupload.RequestContext are in unnamed
module of loader java.net.URLClassLoader #66d2e7d9)
How can i cast this request to request context

the specified http method is not allowed for the requested resource in servlet

I write controller with annotations to mapping the controller.
In the page jsp i have ajax request to the controller but i get error
"
type: Status report
message: HTTP method GET is not supported by this URL
description: The specified HTTP method is not allowed for the requested resource.
"
why it's happend?
the controller class:
package controllers;
import java.io.IOException;
import java.util.List;
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.servlet.http.HttpSession;
import model.AntiXss;
import model.HibernateToDoListDAO;
import model.Items;
import model.ToDoListDAOException;
import model.User;
#WebServlet("/DeleteMessage/*")
public class DeleteMessageController extends HttpServlet{
private static final long serialVersionUID = 1L;
HttpSession session = null;
User user = null;
Items item = null;
List<Items> items = null;
String message;
HibernateToDoListDAO actions = HibernateToDoListDAO.getInstance();
public DeleteMessageController()
{
super();
}
#Override
#SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
session = request.getSession(false);
if(session == null)
{
response.sendRedirect("error.jsp");
}
try{
message = request.getParameter("item");
if(AntiXss.isUsername(message) == false )
{
if(session != null){
session.invalidate();
}
response.sendRedirect("error.jsp");
}
else
{
items = (List<Items>)session.getAttribute("listItems");
user = (User)session.getAttribute("user");
for(Items newItem : items)
{
if(newItem.getMessage() == message && newItem.getUsername() == user.getUsername())
{
item = newItem;
}
}
actions.deleteItems(item);
items = actions.getItems(user.getUsername());
session.setAttribute("listItems", items);
request.getRequestDispatcher("Index.jsp").forward(request, response);
}
}catch(ToDoListDAOException e){
e.printStackTrace();
}
}
}
and the jsp page:(i put here just the ajax request);
var xmlhttp = new XMLHttpRequest();
var item = "test";
if((txtSearch(item, item.length)) == 1)
{
var url = "DeleteMessage";
try
{
xmlhttp.open("post",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("item=" + item);
}catch(e){
alert("unable to connect to server");
}
}

Java Servlet class can not find the bean class

I have created a servlet file 'LoginServlet.java' and a bean file 'SimpleBean.java' and placed them in a same folder.When i compiled the bean file it compiled successfully but when i compile the servlet file i get error 'cannot find symbol' and it indicates the bean class which i instantiated inside the servlet class.
LoginServlet.java
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.*;
public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/writer");
PrintWriter pw = response.getWriter();
String name = request.getParameter("username");
String password = request.getParameter("password");
String code = request.getParameter("code");
SimpleBean bean = new SimpleBean();
//admin login
if (name.equals("admin") && password.equals("admin")) {
RequestDispatcher rd = request.getRequestDispatcher("adminservlet");
rd.forward(request, response);
} else { //general login
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/" + code, "root", "");
PreparedStatement pst = con.prepareStatement("SELECT * FROM demo_teacher WHERE name = ?");
pst.setString(1, name);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
HttpSession session = request.getSession(true);
session.setAttribute("user", name);
ArrayList rows = new ArrayList();
do {
List row = new ArrayList();
row.add(rs.getString("name"));
row.add(rs.getString("login_time"));
row.add(rs.getString("logout_time"));
rows.add(row);
} while (rs.next());
request.setAttribute("resultSet", rows);
RequestDispatcher rd = request.getRequestDispatcher("profile.jsp");
rd.forward(request, response);
} else {
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
SimpleBean.java
public class SimpleBean {
String name;
String loginTime;
String logoutTime;
public void setName(String n) {
name = n;
}
public void setLoginTime(String t) {
loginTime = t;
}
public void setLogoutTime(String t2) {
logoutTime = t2;
}
public String getName() {
return name;
}
public String getLoginTime() {
return loginTime;
}
public String getLogoutTime() {
return logoutTime;
}
}
Command Prompt:
Since you are compiling from the command line, review your classpath. Ensure it contains the directory where the .class files are being stored (in this case, it is the current directory):
set CLASSPATH=.;%CLASSPATH%

getting HTTP Status 404 - 502.shtml The requested resource is not available.while uploading a file

I'm getting the above error while using servlet I've written. the war file is set on Tomcat ver 7.0.39 installed on cPanel. the servlet compiled and tested on local machine no problem. I've learnet that there is a problem that has something to do with the cPanel/PHP config. I tried to play with the cPanel configuration but no luck
I feel that it has nothing to do with the java code but I'll put the fileUploadServlet anyhow
EDIT: I was able to upload a very small-sized file so it has something to do with file size \ long procssing time
package servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import convertor.TextAnalayzer;
import exception.ZoharException;
import beans.ParashaBean;
import beans.UserBean;
import jdbcHandler.JDBCZhoarHandler;
import util.ParashaName;
import util.XmlUrelParaser;
#WebServlet(urlPatterns = { "/upload" }, loadOnStartup = 1)
#MultipartConfig
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 8626646959046203428L;
private JDBCZhoarHandler appHandler = new JDBCZhoarHandler();
public static final String ERROR_PARAMETER = "error";
public static final String COMMAND_PARAMETER = "command";
public static final String USER_ATTRIBUTE = "user";
public static final String HANDLER_ATTRIBUTE = "handler";
#Override
public void init() throws ServletException {
super.init();
try {
getServletConfig().getServletContext().setAttribute("list",
appHandler.viewParashot());
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String command = request.getParameter(COMMAND_PARAMETER);
String nextPage = "/login.jsp";
if ("convert".equals(command)) {
nextPage = this.upload(request, response);
} else if ("login".equals(command)) {
nextPage = this.login(request, response);
} else {
}// do nothing!!
this.getServletConfig().getServletContext()
.getRequestDispatcher(nextPage).forward(request, response);
}
private String login(HttpServletRequest request,
HttpServletResponse response) {
String name = request.getParameter("userName");
String password = request.getParameter("password");
JDBCZhoarHandler handler = new JDBCZhoarHandler();
try {
UserBean user = handler.getUser(name, password);
HttpSession session = request.getSession(true);
session.setAttribute(HANDLER_ATTRIBUTE, handler);
session.setAttribute(USER_ATTRIBUTE, user.getId());
return "/uploadFile.jsp";
} catch (Exception e) {
request.setAttribute(ERROR_PARAMETER, e.getMessage());
return "/login.jsp";
}
}
private String upload(HttpServletRequest request,
HttpServletResponse response) {
// view artifacts
HttpSession session = request.getSession(false);
ParashaName parashaName = new ParashaName();
JDBCZhoarHandler handler = (JDBCZhoarHandler) session
.getAttribute(HANDLER_ATTRIBUTE);
List<ParashaBean> list = null;
try {
list = handler.viewParashot();
} catch (SQLException e1) {
request.setAttribute(ERROR_PARAMETER, e1.getMessage());
}
session.setAttribute("list", list);
// Processing file
if ("convert".equals(request.getParameter("command"))) {
OutputStream out = null;
InputStream filecontent = null;
try {
// Create path components to save the file
XmlUrelParaser xml = new XmlUrelParaser();
SimpleDateFormat format = new SimpleDateFormat(
"dd-MM-yy_HH-mm-ss");
final Part filePart = request.getPart("file");
if (filePart.getSize() == 0) {
throw new ZoharException("you must upload a file first");
}
final String fileName = xml.getUR("incomingFilesDir")
+ session.getAttribute(USER_ATTRIBUTE)
+ parashaName.convert(Integer.parseInt(request
.getParameter("parasha")))
+ format.format(new Date()) + ".docx";
out = new FileOutputStream(new File(fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
TextAnalayzer ta = new TextAnalayzer();
Integer ID = (Integer)session.getAttribute("user");
ta.analayze(fileName,
Integer.parseInt(request.getParameter("parasha")),
Boolean.parseBoolean(request.getParameter("orginal")),
ID);
request.setAttribute(ERROR_PARAMETER, "Upload complete");
return "/uploadFile.jsp";
} catch (Exception e) {
request.setAttribute(ERROR_PARAMETER, e.getMessage());
} finally {
try {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
} catch (IOException e) {
request.setAttribute(ERROR_PARAMETER, e.getMessage());
}
}
}
return "/login.jsp";
}
}
This is a resault of memory lack. Better memory-managing code solved the problem.

I have a trouble with my Login Authentication Servlet

i have a problem with my login authentication login.jsp
I have a class UsuarioLogin:
package br.com.cad.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import br.com.cad.basica.Contato;
public class UsuarioLogin {
private Contato usuario;
public UsuarioLogin(Contato usr)
{
usuario=usr;
}
public boolean verificaLogin(){
if(usuario.getEmail()!=null && usuario.getSenha()!=null)
{
try
{
ConnectDb con = new ConnectDb();
String strsql="SELECT PF_EMAIL, PF_SENHA FROM DADOS_CADASTRO WHERE PF_EMAIL = ? and PF_SENHA = ?;";
PreparedStatement stmt = con.getConnection().prepareStatement(strsql);
stmt.setString(1, usuario.getEmail());
stmt.setString(2, usuario.getSenha());
boolean logado = false;
ResultSet rs=stmt.executeQuery();
rs.close();
stmt.close();
return logado;
}
catch (SQLException e)
{
e.printStackTrace();
return false;
}
}
return false;
}}
and my Servlet LoginAuthentication:
package br.com.cad.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import br.com.cad.basica.Contato;
import br.com.cad.dao.UsuarioLogin;
public class LoginAuthentication extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
} finally {
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String email=request.getParameter("email");
String senha=request.getParameter("password");
RequestDispatcher rd = null;
Contato user = new Contato();
user.setEmail(email);
user.setSenha(senha);
UsuarioLogin ul = new UsuarioLogin(user);
if(ul.verificaLogin())
{
HttpSession sessao = request.getSession();
sessao.setAttribute("USER",email);
rd=request.getRequestDispatcher("logado.jsp");
rd.forward(request,response);
}
else
{
request.setAttribute("msg", "Usuário ou senha inválidos");
rd=request.getRequestDispatcher("login.jsp");
rd.forward(request,response);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
But i don't know how i got a user or password invalid if i entered a valid e-mail and pass!!! please somone can help me?
I guess the loganto is the boolean flag indicating that a user is logged in or not.
The problem in your code is that you execute the Select query but you never check if a record was found. You can do it like this:
ResultSet rs=stmt.executeQuery();
while(rs.next()){
loganto=true; //a valid record was found so return true
}
rs.close();
return loganto;

Categories