Did anyone encountered this exception while using Jena in Java Web Application... Please Kindly help me ..
Here is my servlet code
package com.mycompany.servlet;
import java.io.IOException;
import java.util.Iterator;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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 com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.ontology.*;
/**
* Servlet implementation class GreetingServlet
*/
#WebServlet("/GreetingServlet")
public class GreetingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public GreetingServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String SOURCE ="file:E:\\healthcare.owl";
OntModel base = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM );
base.read( SOURCE );
for (Iterator<OntClass> i = base.listClasses(); i.hasNext(); )
{
OntClass c = i.next();
//System.out.println( "Class" + c.getLocalName());
}
}
}
Exception is
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Error instantiating servlet class com.mycompany.servlet.GreetingServlet
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
root cause
java.lang.NoClassDefFoundError: com/hp/hpl/jena/rdf/model/Model
java.lang.Class.getDeclaredConstructors0(Native Method)
java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
java.lang.Class.getConstructor0(Unknown Source)
java.lang.Class.newInstance0(Unknown Source)
java.lang.Class.newInstance(Unknown Source)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
root cause
java.lang.ClassNotFoundException: com.hp.hpl.jena.rdf.model.Model
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
java.lang.Class.getDeclaredConstructors0(Native Method)
java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
java.lang.Class.getConstructor0(Unknown Source)
java.lang.Class.newInstance0(Unknown Source)
java.lang.Class.newInstance(Unknown Source)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.11 logs.
root cause
java.lang.ClassNotFoundException: com.hp.hpl.jena.rdf.model.Model
That means that tomcat can't find the Jena libraries. Make sure you have all the right jars in the right place.
You need to copy each of the *.jar files from $JENA/lib (where $JENA is the directory you installed your local installation of Jena into) to the WEB-INF/lib directory of your servlet application.
just copy the jena jars declared on the build path project to the lib directory of tomcat, in my case it is located at
C:\Apache Software Foundation\Tomcat 6.0\lib
Related
Expected Output:
- Get the Supplier Details by Entering the ZipCode as Input
Issue:
- Error showing at 3rd line of try catch block in SupplierDetail.java
- While unmarshaling it throws the Exception. See error log
javax.xml.bind.UnmarshalException - with linked exception:
[org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1;
Content is not allowed in prolog.]
WSDL:
Endpoint
http://www.webservicex.net/medicareSupplier.asmx?WSDL
Use GetSupplierByZipCode Method to the Supplier Details from given WSDL
Step 1: Using wsimport tool generate stubs
wsimport -keep -d "path"
http://www.webservicex.net/medicareSupplier.asmx?WSDL
Step 2: Created a Dynamic Web Project
1. Added the generated files to project
Below is the Code
index.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>MediCare SOAP Client </title>
</head>
<body>
<h2>Hello JSP</h2>
<form method="post" action="supplierdetail">
<label>Zip Code</label>
<input type="text" name="searchBarInputId">
<input type="submit" value="Get Supplier">
</form>
</body>
</html>
SupplierDetail.java
package com.supplier;
import java.io.IOException;
import java.io.StringReader;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import net.webservicex.MediCareSupplier;
import net.webservicex.MediCareSupplierSoap;
import net.webservicex.SupplierData;
public class SupplierDetail extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String cityZipCode = request.getParameter("searchBarInputId");
System.out.println("doPost:"+ cityZipCode);
MediCareSupplier mediCareObj = new MediCareSupplier();
MediCareSupplierSoap mediCareSupplier = mediCareObj.getMediCareSupplierSoap();
mediCareSupplier.getSupplierByZipCode(cityZipCode, null, null);
try {
JAXBContext jAXBContext = JAXBContext.newInstance(SupplierData.class);
Unmarshaller unmarshaller = jAXBContext.createUnmarshaller();
SupplierData data = (SupplierData)unmarshaller.unmarshal(new StringReader(response.toString()));
System.out.println("SupplierDAta: "+data+':'+ data.getSupplierNumber()+ "\n"+data.getAddress1());
/* RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/SupplierDetails.jsp");
dispatcher.forward(request, response);*/
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Error Log:
INFO: Server startup in 610 ms doPost:61244
javax.xml.bind.UnmarshalException
- with linked exception: [org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.] at
javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(Unknown
Source) at
com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(Unknown
Source) at
com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(Unknown
Source) at
com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(Unknown
Source) at
javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(Unknown
Source) at
javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(Unknown
Source) at com.supplier.SupplierDetail.doPost(SupplierDetail.java:36)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:742) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source) Caused by:
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content
is not allowed in prolog. at
com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown
Source) at
com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(Unknown
Source) at
com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown
Source) at
com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown
Source) at
com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(Unknown
Source) at
com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown
Source) at
com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown
Source) at
com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown
Source) at
com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown
Source) at
com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown
Source) at
com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown
Source) at
com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown
Source) at
com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown
Source) at
com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown
Source) ... 28 more
Please help.. Thanks in Advance
Why are you trying to Unmarshall response ? What is the point of below code ?SupplierData data = (SupplierData)unmarshaller.unmarshal(new StringReader(response.toString()));
if your purpose is getting SOAP respose you already have it, by this mediCareSupplier.getSupplierByZipCode(cityZipCode, null, null);.( I presume your code execute properly until try block).
Found another solution
Returning Multiple values
With SOAP it is possible to return multiple values in a single request. This is impossible in Java as a method can only return one object.
JAX-WS solves this problem with the concept of Holders. A javax.xml.ws.Holder is a simple wrapper object that can be passed into the #WebService method as a parameter. The application sets the value of the holder during the request and the server will send the value back as an OUT parameter.
MediCareSupplier mediCare = new MediCareSupplier();
MediCareSupplierSoap mediCareSOAP = mediCare.getMediCareSupplierSoap();
Holder<Boolean> getSupplierByZipCodeResult = new Holder<Boolean>();
Holder<SupplierDataList> supplierDataLists = new Holder<SupplierDataList>();
mediCareSOAP.getSupplierByZipCode(zip, getSupplierByZipCodeResult, supplierDataLists);
List<SupplierData> supplierDataList = supplierDataLists.value.getSupplierDatas().getSupplierData();
loop through the supplierDataList and get all the data
When executing a SQL native query with SQLQuery q = session.createSQLQuery(query).addEntity("edu", StudentEduPojo.class); JVM throws a null pointer exception.
DBConnectionDao.class
package com.ms.avalon.master.dao.rdbms;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
#Repository
public class DBConnectionDao {
protected Session session;
protected DataSource dataSource;
protected SessionFactory sessionFactory;
protected HibernateTemplate hibernateTemplate=null;
protected NamedParameterJdbcTemplate namedJdbcTemplate=null;
#Autowired
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
namedJdbcTemplate=new NamedParameterJdbcTemplate(dataSource);
}
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
System.out.println("session created");
this.sessionFactory = sessionFactory;
session = sessionFactory.getCurrentSession();
hibernateTemplate=new HibernateTemplate(sessionFactory);
}
}
PlacementDaoRdbms.class
package com.ms.avalon.master.dao.rdbms;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.DetachedCriteria;
import com.ms.avalon.master.beans.PlacementCaseBean;
import com.ms.avalon.master.dao.PlacementDao;
import com.ms.avalon.master.formbeans.PlacementFormBean;
import com.ms.avalon.master.pojos.studentpojos.StudentEduPojo;
import com.ms.avalon.master.pojos.studentpojos.StudentTestPojo;
public class PlacementDaoRdbms extends DBConnectionDao implements PlacementDao {
#Override
public List<StudentEduPojo> searchWithCases(PlacementCaseBean caseBean, PlacementFormBean placementBean) {
String query = "Some complicated SQL query";
SQLQuery q = session.createSQLQuery(query)
.addEntity("edu", StudentEduPojo.class);
List<StudentEduPojo> list = q.list();
return list;
}
}
When using the function createSqlQuery on session in PlacementDaoRdbms, I get a NPE.
Following is the stack trace:
May 11, 2016 8:52:17 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/Avalon-1.0] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.ms.avalon.master.dao.rdbms.PlacementDaoRdbms.searchWithCases(PlacementDaoRdbms.java:108)
at com.ms.avalon.master.business.TalentCaseHandler.searchForCases(TalentCaseHandler.java:61)
at com.ms.avalon.master.service.impl.PlacementServiceImpl.searchForTalent(PlacementServiceImpl.java:26)
at com.ms.avalon.master.controllers.PlacementController.searchForTalent(PlacementController.java:29)
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:427)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:415)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:788)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:717)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at com.opensymphony.module.sitemesh.filter.PageFilter.parsePage(PageFilter.java:119)
at com.opensymphony.module.sitemesh.filter.PageFilter.doFilter(PageFilter.java:55)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Also, is this the correct way to use session from the parent class?
Thanks for the help :)
The method searchWithCases in PlacementDaoRdbms was being called from another class (let's call that A). I was creating A's object using new keyword, which was causing DI and #Autowired to not work. I know I should have posted the full code but still, thanks for the help and advice. Let me know if you've got a similar problem :)
I try to connect to mysql database on my Java EE project but i get an error and I do not know where is the problem.
And this is SERVLET, CLASS AND ERRORS
The Java EE Servlet:
package com.hopital.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.hopital.database.Recup_Insert;
import com.hopital.forms.Connections;
#WebServlet("/hopital")
public class hopital extends HttpServlet {
private static final long serialVersionUID = 1L;
public hopital() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//extrait les cookies
Cookie[] cookies= request.getCookies();
if(cookies != null){
for(Cookie cookie: cookies){
if(cookie.getName().equals("login")){
request.setAttribute("login", cookie.getValue());
}
}
}
//session
HttpSession session= request.getSession();
String login= (String) session.getAttribute("login");
request.setAttribute("login", login);
//extrait les chambers
Recup_Insert tableChamber= new Recup_Insert();
request.setAttribute("chambres",tableChamber.recup_chmabre());
this.getServletContext().getRequestDispatcher("/WEB-INF/home.jsp").forward(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//verification de champs
Connections form= new Connections();
form.verifie(request);
request.setAttribute("form", form);
//stocke les champs entre
String login=request.getParameter("login");
String pass=request.getParameter("pass");
//cree un cookies
Cookie cookie=new Cookie("login",login);
cookie.setMaxAge(60*60*24*30);
response.addCookie(cookie);
// cree un session sur login et mot de passe
HttpSession session= request.getSession();
session.setAttribute("login", login);
session.setAttribute("pass", pass);
this.getServletContext().getRequestDispatcher("/WEB-INF/home.jsp").forward(request,response);
}
}
My class that contain the database connexion:
package com.hopital.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import com.hopital.projet.chamber;
public class Recup_Insert {
public List<chamber> recup_chmabre(){
List<chamber> chambers= new ArrayList<chamber>();
//charger les drivers
try{
Class.forName("com.mysql.jdbc.Driver");
}catch( ClassNotFoundException e){
}
//Connexion
Connection connexion=null;
Statement statement=null;
ResultSet resultat = null;
try {
connexion = DriverManager.getConnection("jdbc:mysql://localhost:3306/hopital", "root", "3636");
statement= connexion.createStatement();
resultat= statement.executeQuery("SELECT * FROM CHAMBER;");
while(resultat.next()){
int etage = resultat.getInt("etage");
int ID_pat = resultat.getInt("ID_pat");
int num = resultat.getInt("num");
int nom_lits = resultat.getInt("nom_lits");
int occupee = resultat.getInt("occupee");
chamber chamber = new chamber();
chamber.setEtage(etage);
chamber.setID_pat(ID_pat);
chamber.setNum(num);
chamber.setOccupee(occupee);
chamber.setNom_lits(nom_lits);
chambers.add(chamber);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try{
if(resultat != null)resultat.close();
if(statement != null)statement.close();
if(connexion != null)connexion.close();
}catch(SQLException ignore){
}
}
return chambers;
}
}
AND THIS IS THE ERRORS AFTER RUNING:
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:983)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:339)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2252)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2285)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2084)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:795)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:400)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:327)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.hopital.database.Recup_Insert.recup_chmabre(Recup_Insert.java:29)
at com.hopital.servlet.hopital.doGet(hopital.java:44)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:214)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:298)
... 39 more
Check connection URL and credentials. Try connecting with the same parameters using some SQL client.
You got this error because you cannot connect to database.
Most probably you didn't start you server. Check either it running or not, then double check port where it is running. Also check spelling on table name in database it should be "hopital".
Check For mysql-connector-java-5.1.21-bin.jar file added to Properties=>libraries=>
if not then add external jar=>mysql-connector-java-5.1.21-bin.jar
also check port number of tomcat server and mysql.
I am trying to configure a Freemarker template from a Servlet like so:
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
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 freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
#WebServlet("/Controller")
public class Controller extends HttpServlet {
// class fields
private static final long serialVersionUID = 1L;
private static final String views = "/WEB-INF/views/";
public Controller(){
}
// used to handle any get requests i.e. webpage navigation
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Configuration conf = new Configuration();
conf.setClassForTemplateLoading(Controller.class, views);
conf.setDefaultEncoding("UTF-8");
Template indexTemplate = conf.getTemplate("index.ftl");
StringWriter writer = new StringWriter();
Map<String, Object> indexMap = new HashMap<String, Object>();
indexMap.put("name", "Chris");
try {
indexTemplate.process(indexMap, writer);
} catch (TemplateException e) {
e.printStackTrace();
}
System.out.println(writer);
}
}
But I get the following error when I startup the Tomcat server:
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/webapp]]
at java.util.concurrent.FutureTask.report(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1122)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:819)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
at java.util.concurrent.FutureTask.run(Unknown Source)
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: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/webapp]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
... 6 more
Here is the file structure:
What am I doing wrong here?
I am using Guava 14.0 jar and following is my code
package org.user.module.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.Cache;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class test
*/
#WebServlet("/test")
public class test extends HttpServlet {
private static final long serialVersionUID = 1L;
Cache<String, Integer> map;
public test() {
super();
// TODO Auto-generated constructor stub
}
public void init() throws ServletException
{
map=CacheBuilder.newBuilder().
maximumSize(100).
expireAfterAccess(10, TimeUnit.MINUTES).
build();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
String p=request.getParameter("v");
Integer a=map.getIfPresent(p);
if(a==null){
map.put(p, 1);
out.println("Putting The Integer:"+a);
}
else{
map.put(p,a++);
out.println("A is already present and the value is:"+a);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
Error:
SEVERE: Allocate exception for servlet org.user.module.test.test
java.lang.ClassNotFoundException: com.google.common.cache.Cache at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1701)
at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1546)
at java.lang.Class.getDeclaredFields0(Native Method) at
java.lang.Class.privateGetDeclaredFields(Class.java:2317) at
java.lang.Class.getDeclaredFields(Class.java:1762) at
org.apache.catalina.core.DefaultInstanceManager.populateAnnotationsCache(DefaultInstanceManager.java:276)
at
org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:143)
at
org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:125)
at
org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1136)
at
org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:857)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
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.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:307)
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:722)
downloaded jar from here Downlaod Link
Link to my project folder(Project name:test2) LINK
Obvious answer is that;
The Google guava jar is not found from the classpath dictated by the application server. The jar should be present in either WEB-INF/classes or WEB-INF/lib. Apache Tomcat also loads common classes from $CATALINA_HOME/lib folder.