How to dynamically load a class on tomcat? - java

I've learned how to dynamically load a ".class" file into my program, but if I run it on a tomcat id doesn't work. Here is the code:
package testPackage;
public class ModuleEngine {
public static void main(String pth, String name) {
ModuleLoader loader = new ModuleLoader(pth, ClassLoader.getSystemClassLoader());
try {
Class clazz = loader.loadClass(name);
Protocol execute = (Protocol)clazz.newInstance();
execute.run();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
public class ModuleLoader extends ClassLoader {
private String pathtobin;
public ModuleLoader(String pathtobin, ClassLoader parent) {
super(parent);
this.pathtobin = pathtobin;
}
#Override
public Class findClass(String className) throws ClassNotFoundException {
try {
byte b[]= fetchClassFromFS(pathtobin + className + ".class");
return defineClass(null, b, 0, b.length);
} catch (FileNotFoundException ex) {
return super.findClass(className);
} catch (IOException ex) {
return super.findClass(className);
}
}
}
I run main method in ModuleEngine class with path to subclass of the class Protocol. This subclass is placed in different package. So when I try to define it (defineClass) it tries to load the superclass (Protocol) but fails to do that. Here is the stack trace:
java.lang.ClassNotFoundException: testPackage.Protocol
at java.lang.ClassLoader.findClass(Unknown Source)
at testPackage.ModuleLoader.findClass(ModuleLoader.java:30)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at testPackage.ModuleLoader.findClass(ModuleLoader.java:28)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at testPackage.ModuleEngine.main(ModuleEngine.java:13)
at testPackage.HtmlPage.doGet(HtmlPage.java:27)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

Instead of ClassLoader.getSystemClassLoader() try using ModuleEngine.class.getClassLoader (). This will return class loader that knows about classes sitting near ModuleEngine class.

Related

Caused by: java.lang.NoClassDefFoundError: io/jsonwebtoken/Jwts

i am using jjwt-0.9.1.jar and runtime gives this exception for jersey reset API call.
When i use this code using java main() method, its works perfectly but when i call from servlet to that class, the method throws exception.
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.UUID;
public String createJWTToken() {
String id = UUID.randomUUID().toString().replace("-", "");
//The JWT signature algorithm we will be using to sign the token
// SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
//Let's set the JWT Claims
JwtBuilder builder = null;
try {
builder = Jwts.builder().setId(id).setHeaderParam("typ", "JWT")
.setIssuedAt(now)
.setSubject("")
.setIssuer(API_KEY)
.signWith(SignatureAlgorithm.HS256,SECRET_KEY.getBytes("UTF-8"));
//if it has been specified, let's add the expiration
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
} catch (Exception e) {
e.printStackTrace();
}
return builder.compact();//Builds the JWT and serializes it to a compact, URL-safe string
}
When call servlet to java class method i.e.createJWTToken() gives following exception in tomcat.
javax.servlet.ServletException: Servlet execution threw an exception
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:328)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.test.lms.servlets.GlobalFilter.doFilter(GlobalFilter.java:204)
at com.test.lms.servlets.GlobalFilter.doFilter(GlobalFilter.java:48)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at com.general.FilterDemo.doFilter(FilterDemo.java:312)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:200)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source) Caused by: java.lang.NoClassDefFoundError: io/jsonwebtoken/Jwts
at com.zoom.JWTTokenGeneration.createJWTToken(JWTTokenGeneration.java:31)
at com.zoom.Utilities.setMeeting(Utilities.java:571)
at com.general.InsertController.doPost(InsertController.java:377)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) ... 22 more Caused by: java.lang.ClassNotFoundException: io.jsonwebtoken.Jwts
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1701)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1546) ... 28 more
The exception is java.lang.NoClassDefFoundError: io/jsonwebtoken/Jwts
Check the Jar file(jwt) is packaged in the build or not?

how to solve the Class cast exception in HibernateTemplate's findByCriteria()?

This is the method of Dao class that is throwing Exception:
I did not used any Integer here. Even the phone number property is
also a String as it can contain +,() Symbols sometimes.
public List<StudentDetails> retriveStudents( String studentFirstName, String studentLastName,String studentEmail, String studentPhoneNum) {
logger.info("AddStudentDao retriveStudents():- START");
List<StudentDetails> nonTerminatedStudentsList = null;
//List<UserLocationMapping> userLocationMappings = null;
Set<Integer> studentIdSet = new HashSet<Integer>();
try {
DetachedCriteria objmCriteria = DetachedCriteria.forClass(StudentDetails.class);
//objmCriteria.createAlias("studentDetails", "UserDetails");
objmCriteria.add(Restrictions.ne("loginId", Constants.SUPER_ADMIN));
if (!Utilities.IsEmpty(studentFirstName)) {
objmCriteria.add(Restrictions.like("firstName", "%" + studentFirstName + "%"));
}
if (!Utilities.IsEmpty(studentLastName)) {
objmCriteria.add(Restrictions.like("lastName", "%" + studentLastName + "%"));
}
if (!Utilities.IsEmpty(studentEmail)) {
objmCriteria.add(Restrictions.like("email", "%" + studentEmail + "%"));
}
if (!Utilities.IsEmpty((studentPhoneNum))) {
objmCriteria.add(Restrictions.like("phoneNumber", "%" + studentPhoneNum + "%"));
}
nonTerminatedStudentsList = hibernateTemplate.findByCriteria(objmCriteria);//*****EXCEPTION RAISING*****(Line number 216)
if (studentIdSet != null && studentIdSet.size() > 0) {
nonTerminatedStudentsList = getStudents(studentIdSet);
}
} catch (Exception e) {
logger.error(" AddStudentDao retriveUsers :- ", e);
}
logger.info("AddStudentDao retriveUsers():- END");
return nonTerminatedStudentsList;
}
This is supposed to return a List of StudentDetails objects but the
method used in this scenario is raising an Exception. Hope somebody
can help me.
and the exception is shown like this:
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at org.hibernate.type.StringType.toString(StringType.java:67)
at org.hibernate.type.NullableType.nullSafeToString(NullableType.java:117)
at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:158)
at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:136)
at org.hibernate.loader.Loader.bindPositionalParameters(Loader.java:1732)
at org.hibernate.loader.Loader.bindParameterValues(Loader.java:1703)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1593)
at org.hibernate.loader.Loader.doQuery(Loader.java:696)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
at org.hibernate.loader.Loader.doList(Loader.java:2232)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129)
at org.hibernate.loader.Loader.list(Loader.java:2124)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:118)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1597)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:306)
at org.springframework.orm.hibernate3.HibernateTemplate$36.doInHibernate(HibernateTemplate.java:1056)
at org.springframework.orm.hibernate3.HibernateTemplate$36.doInHibernate(HibernateTemplate.java:1)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.findByCriteria(HibernateTemplate.java:1046)
at org.springframework.orm.hibernate3.HibernateTemplate.findByCriteria(HibernateTemplate.java:1039)
at com.pss.admin.dao.student.AddStudentDao.retriveStudents(AddStudentDao.java:216)
at com.pss.admin.dao.student.AddStudentDao$$FastClassByCGLIB$$41df7ff.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:618)
at com.pss.admin.dao.student.AddStudentDao$$EnhancerByCGLIB$$25e36467_2.retriveStudents(<generated>)
at com.pss.admin.bo.student.SaveStudentService.retriveStudents(SaveStudentService.java:91)
at com.pss.admin.controller.student.StudentController.retriveStudents(StudentController.java:98)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Sorry guys.. My bad.
the constant in the first Restriction is an integer.
Thank you.

java.io.FileNotFoundException uploading image with apache.commons

I'm developing a Spring-MVC project that requires uploading images by the users of the app. I'm using apache.commons, Eclipse Mars2 and Java1.8. Everytime I test the upload, eclipse console throws this:
EDIT: it seems the problem is to find the path to the project independently of the OS. At this moment we are using:
File localFile = new File(System.getProperty("user.home")+File. separator+ "workspace"+File. separator+"ProyectoSpring"+File. separator + "WebContent" + File. separator+"usr"+File. separator+imagen.getNombreImagen());
The problem is the workspace is hardcoded and the app is being developed by more people. Any way to find the path to the project? user.dir returns the eclipe path, not the project or workspace.
Original question:
java.io.FileNotFoundException: C:\Users\UserName\workspace\ApacheTomcat7\ProyectoSpring\WebContent\usr\back.jpg (El sistema no puede encontrar la ruta especificada)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at controller.ImagenController.grabarFicheroALocal(ImagenController.java:84)
at controller.ImagenController.processAddSubmit(ImagenController.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Controller methods:
#RequestMapping(value="/uploadImagen" , method=RequestMethod.GET)
public String addImagen(Model model) {
model.addAttribute("imagen", new Imagen());
return "imagen/uploadImagen";
}
#RequestMapping(value="/uploadImagen", method=RequestMethod.POST)
public String processAddSubmit(#ModelAttribute("imagen") Imagen imagen,
BindingResult bindingResult) {
//if (bindingResult.hasErrors())
// return "imagen/uploadImagen";
//
try {
String aux = imagen.getFichero().getOriginalFilename();
imagen.setImageName(System.getProperty("catalina.home")+ File. separator +"ProyectoSpring"+ File. separator +"WebContent"+ File. separator +"usr"+ File. separator + aux);
grabarFicheroALocal(imagen);
} catch (Exception e) {
e.printStackTrace();
return "user/error";
}
return "redirect:../index.jsp";
}
private void grabarFicheroALocal(Imagen imagen) throws Exception {
CommonsMultipartFile uploaded = imagen.getFichero();
File localFile = new File(imagen.getImageName());
FileOutputStream os = null;
try {
os = new FileOutputStream(localFile);
os.write(uploaded.getBytes());
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
An extract from the object:
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class Imagen {
private String imageName;
private CommonsMultipartFile fichero;
public Imagen(){
super();
}
//GETTERS AND SETTERS
public CommonsMultipartFile getFichero() {
return fichero;
}
public void setFichero(CommonsMultipartFile fichero) {
this.fichero = fichero;
}
...
Of course, the image is not uploaded. In other pc with Linux (I'm using W7-64) the code works, so I suspect it may be a permissions problem, but all folders in the path have write permissions. Any ideas? Thx.

Why am I getting "No suitable driver found for jdbc:mysql://localhost:3306/test2"?

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test2
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.room302.util.DBConnectionUtil.getConnection(DBConnectionUtil.java:32)
at com.room302.dao.roomDAO.addexpense(roomDAO.java:26)
at com.room302.servlet.Navigator.doPost(Navigator.java:69)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
My Util file is as follows:
public class DBConnectionUtil
{
private static final String USERNAME="root";
private static final String PASSWORD="1234";
private static final String URL="jdbc:mysql://localhost:3306/test2";
private static final String DRIVER_NAME="mysql";
private static Connection conn=null;
static
{
try
{
System.out.println("searching for driver");
Class.forName(DRIVER_NAME);
}
catch(ClassNotFoundException cnfe)
{
}
}
public static Connection getConnection() throws SQLException
{
conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
return conn;
}
public static void closeConnection(Connection conn)
{
if(conn!=null)
{
try
{
conn.close();
}
catch (Exception e)
{
}
}
}
}
I have put MySQL connector in the buildpath and also in lib folder of web-inf.
Why am I still getting this error?
You need to load the com.mysql.jdbc.Driver driver class.
private static final String DRIVER_NAME="com.mysql.jdbc.Driver";
Look at the official documentation:
The name of the class that implements java.sql.Driver in MySQL Connector/J is com.mysql.jdbc.Driver. The org.gjt.mm.mysql.Driver class name is also usable for backward compatibility with MM.MySQL, the predecessor of Connector/J. Use this class name when registering the driver, or when otherwise configuring software to use MySQL Connector/J.
This is a fairly old thread so I just though I should add that "com.mysql.jdbc.Driver" has been deprecated so you need to use "com.mysql.cj.jdbc.Driver"

IllegalStateException: Cannot forward after response has been committed

This code below throws IllegalStateException: Cannot forward after response has been committed :
private void doRequest(HttpServletRequest request) throws IOException, ServletException {
CallableStatement stmt = null;
ResultSet rs = null;
String someString;
try {
this.connectDB();
stmt = this.conn.prepareCall("{call sp_SomeSP1(?)}");
stmt.setLong(1, someFunc());
rs = stmt.executeQuery();
while (rs.next()) {
if (rs.getInt(1)==someOtherFunc()) {
someString = rs.getString(2);
break;
}
}
stmt = conn.prepareCall("{call sp_someSP(?, ?)}");
stmt.setLong(1, someFunc());
stmt.setTimestamp(2, new Timestamp(getFrom().getTime()));
rs = stmt.executeQuery();
if (rs.next()) {
lastUpdated = rs.getTimestamp("LastUpdated");
}
request.setAttribute("lastUpdated", lastUpdated);
LOGGER.debug("Forwarding to view...");
getServletContext().getRequestDispatcher("/SomeJSP.jsp").forward(this.request, this.response);
} catch (NamingException e) {
LOGGER.error("Database connection lookup failed", e);
sendError("Server Error");
} catch (SQLException e) {
LOGGER.error("Query failed", e);
sendError("Server Error");
} catch (IllegalStateException e) {
LOGGER.error("View failed", e);
} finally {
try {
if (rs!=null) rs.close();
} catch (NullPointerException e) {
LOGGER.error("Result set closing failed", e);
} catch (SQLException e) {
LOGGER.error("Result set closing failed", e);
}
try {
if (stmt!=null) stmt.close();
} catch (NullPointerException e) {
LOGGER.error("Statement closing failed", e);
} catch (SQLException e) {
LOGGER.error("Statement closing failed", e);
}
try {
this.closeDB();
} catch (NullPointerException e) {
LOGGER.error("Database connection closing failed", e);
} catch (SQLException e) {
LOGGER.error("Database connection closing failed", e);
}
}
In the JSP page there is this code so the page will refresh:
<meta http-equiv="Refresh" content="10">
The catch is that, the error does not happen most of the time, only when I access the Servlet that forward to the JSP, in multiple browser or tabs, and still not always, there is just a time that the error will hit.
What could be the problem?
Stacktrace:
java.lang.IllegalStateException: Cannot forward after response has been committed
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:339)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
at com.mycompany.mywebapp.servlet.CallDetailsServlet.doRequest(CallDetailsServlet.java:103)
at com.mycompany.mywebapp.servlet.CallDetailsServlet.doGet(CallDetailsServlet.java:162)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at com.springsource.insight.collection.tcserver.request.HttpRequestOperationCollectionValve.invoke(HttpRequestOperationCollectionValve.java:84)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Dec 20, 2012 5:04:58 PM org.apache.jasper.runtime.JspFactoryImpl internalGetPageContext
SEVERE: Exception initializing page context
java.lang.IllegalStateException: Page needs a session and none is available
at org.apache.jasper.runtime.PageContextImpl._initialize(PageContextImpl.java:148)
at org.apache.jasper.runtime.PageContextImpl.initialize(PageContextImpl.java:125)
at org.apache.jasper.runtime.JspFactoryImpl.internalGetPageContext(JspFactoryImpl.java:112)
at org.apache.jasper.runtime.JspFactoryImpl.getPageContext(JspFactoryImpl.java:65)
at org.apache.jsp.error_jsp._jspService(error_jsp.java:53)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:402)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
at com.mycompany.mywebapp.servlet.Servlet.sendError(Servlet.java:56)
at com.mycompany.mywebapp.servlet.CallDetailsServlet.doRequest(CallDetailsServlet.java:57)
at com.mycompany.mywebapp.servlet.CallDetailsServlet.doGet(CallDetailsServlet.java:162)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at com.springsource.insight.collection.tcserver.request.HttpRequestOperationCollectionValve.invoke(HttpRequestOperationCollectionValve.java:84)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
12 20, 12 5:05:14 PM com.mycompany.mywebapp.servlet.CallDetailsServlet doRequest
ERROR: View failed
java.lang.IllegalStateException: Cannot forward after response has been committed
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:339)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
at com.mycompany.mywebapp.servlet.CallDetailsServlet.doRequest(CallDetailsServlet.java:103)
at com.mycompany.mywebapp.servlet.CallDetailsServlet.doGet(CallDetailsServlet.java:162)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at com.springsource.insight.collection.tcserver.request.HttpRequestOperationCollectionValve.invoke(HttpRequestOperationCollectionValve.java:84)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
12 20, 12 5:05:15 PM com.mycompany.mywebapp.servlet.CallDetailsServlet doRequest
ERROR: View failed
java.lang.IllegalStateException: Cannot forward after response has been committed
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:339)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
at com.mycompany.mywebapp.servlet.CallDetailsServlet.doRequest(CallDetailsServlet.java:103)
at com.mycompany.mywebapp.servlet.CallDetailsServlet.doGet(CallDetailsServlet.java:162)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at com.springsource.insight.collection.tcserver.request.HttpRequestOperationCollectionValve.invoke(HttpRequestOperationCollectionValve.java:84)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Dec 20, 2012 5:05:16 PM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.NullPointerException
at org.apache.catalina.connector.Request.notifyAttributeAssigned(Request.java:1552)
at org.apache.catalina.connector.Request.access$000(Request.java:105)
at org.apache.catalina.connector.Request$3.set(Request.java:3342)
at org.apache.catalina.connector.Request.setAttribute(Request.java:1504)
at org.apache.catalina.connector.RequestFacade.setAttribute(RequestFacade.java:541)
at org.apache.catalina.core.ApplicationHttpRequest.setAttribute(ApplicationHttpRequest.java:281)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:286)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:402)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
at com.mycompany.mywebapp.servlet.CallDetailsServlet.doRequest(CallDetailsServlet.java:103)
at com.mycompany.mywebapp.servlet.CallDetailsServlet.doGet(CallDetailsServlet.java:162)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at com.springsource.insight.collection.tcserver.request.HttpRequestOperationCollectionValve.invoke(HttpRequestOperationCollectionValve.java:84)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Dec 20, 2012 5:05:16 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [callDetailsServlet] in context with path [/WebCharts] threw exception
java.lang.NullPointerException
at org.apache.catalina.connector.Request.notifyAttributeAssigned(Request.java:1552)
at org.apache.catalina.connector.Request.access$000(Request.java:105)
at org.apache.catalina.connector.Request$3.set(Request.java:3342)
at org.apache.catalina.connector.Request.setAttribute(Request.java:1504)
at org.apache.catalina.connector.RequestFacade.setAttribute(RequestFacade.java:541)
at org.apache.catalina.core.ApplicationHttpRequest.setAttribute(ApplicationHttpRequest.java:281)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:286)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:402)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
at com.mycompany.mywebapp.servlet.CallDetailsServlet.doRequest(CallDetailsServlet.java:103)
at com.mycompany.mywebapp.servlet.CallDetailsServlet.doGet(CallDetailsServlet.java:162)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at com.springsource.insight.collection.tcserver.request.HttpRequestOperationCollectionValve.invoke(HttpRequestOperationCollectionValve.java:84)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
doGet:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.doGet(request, response);
doRequest(request);
}
Your doGet() is broken. You should remove the super.doGet(request, response); line. It's namely by default returning a "HTTP 405 Method Not Allowed" error page which effectively commits your response.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doRequest(request);
}
Do not call the super.doXxx() method in servlets. They return by default a HTTP 405 error indicating that the method is not available (as per the Template Method pattern).
See also:
java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed
HTTP Status 405 - HTTP method GET is not supported by this URL

Categories