DBConnection.java文件
package com.TP6;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBConnection {
public static Connection dbCon;
public Statement dbStmt;
public ResultSet dbRst;
public static Connection setDBConnection() throws SQLException {
try {
System.out.println("Inside DB Connection");
Class.forName("com.mysql.jdbc.Driver");
dbCon = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/usermangment",
"root", "");
} catch (ClassNotFoundException e)
{
System.out.println(e);
}
return dbCon;
}
public void getInsertResutlSet(String sqlQuery, Connection conn)
throws SQLException {
System.out.println(sqlQuery);
String sqlquery = sqlQuery;
dbCon = conn;
try {
dbStmt = dbCon.createStatement();
dbStmt.executeUpdate(sqlquery);
} catch (SQLException se) {
System.out.println(se);
}
}
public ResultSet getResutlSet(String sqlQuery, Connection conn)
throws SQLException {
System.out.println(sqlQuery);
String sqlquery = sqlQuery;
dbCon = conn;
try {
dbStmt = dbCon.createStatement();
dbRst = dbStmt.executeQuery(sqlquery);
} catch (SQLException se) {
System.out.println(se);
}
return dbRst;
}
}
userDao.java:使用文件来获取和插入数据
package com.TP6;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class UserDao {
public List<User> getAllUsers(){
List<User> userList = null;
try {
File file = new File("Users.dat");
if (!file.exists()) {
User user = new User(1, "", "");
userList = new ArrayList<User>();
userList.add(user);
saveUserList(userList);
}
else{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
userList = (List<User>) ois.readObject();
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return userList;
}
public User getUser(int id){
List<User> users = getAllUsers();
for(User user: users){
if(user.getId() == id){
return user;
}
}
return null;
}
public int addUser(User pUser){
List<User> userList = getAllUsers();
boolean userExists = false;
for(User user: userList){
if(user.getId() == pUser.getId()){
userExists = true;
break;
}
}
if(!userExists){
userList.add(pUser);
saveUserList(userList);
return 1;
}
return 0;
}
public int updateUser(User pUser){
List<User> userList = getAllUsers();
for(User user: userList){
if(user.getId() == pUser.getId()){
int index = userList.indexOf(user);
userList.set(index, pUser);
saveUserList(userList);
return 1;
}
}
return 0;
}
public int deleteUser(int id){
List<User> userList = getAllUsers();
for(User user: userList){
if(user.getId() == id){
int index = userList.indexOf(user);
userList.remove(index);
saveUserList(userList);
return 1;
}
}
return 0;
}
private void saveUserList(List<User> userList){
try {
File file = new File("Users.dat");
FileOutputStream fos;
fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(userList);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
userService.java
package com.TP6;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import com.TP6.DBConnection;
import com.mysql.jdbc.Connection;
@Path("/UserService")
public class UserService {
DBConnection dbCoN;
Connection conn;
ResultSet rslt;
String Iuser = "user inconnu ";
String query;
UserDao userDao = new UserDao();
private static final String SUCCESS_RESULT="<result>success</result>";
private static final String FAILURE_RESULT="<result>failure</result>";
@GET
@Path("/user/ID")
@Produces(MediaType.APPLICATION_XML)
public String Usernom(@PathParam("id") String id)
throws SQLException {
query = "select nom from user where id=55";
// System.out.println("" + query);
dbCoN = new DBConnection();
try {
conn = (Connection) DBConnection.setDBConnection();
rslt = dbCoN.getResutlSet(query, conn);
if (rslt.next()) {
String nom = rslt.getString(2);
} else {
return Iuser;
}
} catch (Exception e) {
System.out.println(e);
} finally {
if (conn != null) {
conn.close();
}
}
return Iuser;
}
@GET
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
public List<User> getUsers(){
return userDao.getAllUsers();
}
@GET
@Path("/users/{userid}")
@Produces(MediaType.APPLICATION_XML)
public User getUser(@PathParam("userid") int userid){
return userDao.getUser(userid);
}
@PUT
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String createUser(@FormParam("id") int id,@FormParam("nom") String nom,@FormParam("agence") String agence, @Context HttpServletResponse servletResponse)
throws IOException{
User user = new User(id, nom, agence);
int result = userDao.addUser(user);
if(result == 1){
return SUCCESS_RESULT;
}
return FAILURE_RESULT;
}
@POST
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String updateUser(@FormParam("id") int id,
@FormParam("nom") String nom,
@FormParam("agence") String agence,
@Context HttpServletResponse servletResponse) throws IOException{
User user = new User(id, nom, agence);
int result = userDao.updateUser(user);
if(result == 1){
return SUCCESS_RESULT;
}
return FAILURE_RESULT;
}
@DELETE
@Path("/users/{userid}")
@Produces(MediaType.APPLICATION_XML)
public String deleteUser(@PathParam("userid") int userid){
int result = userDao.deleteUser(userid);
if(result == 1){
return SUCCESS_RESULT;
}
return FAILURE_RESULT;
}
@OPTIONS
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
public String getSupportedOperations(){
return "<operations>GET, PUT, POST, DELETE</operations>";
}
}
实际上我只想知道问题是什么,当我建立数据库连接时它停止工作。
这个控制台:
20:26:51,986 INFO [org.jboss.modules] (main) JBoss Modules version 1.3.0.Final
20:26:52,235 INFO [org.jboss.msc] (main) JBoss MSC version 1.2.0.Final
20:26:52,327 INFO [org.jboss.as] (MSC service thread 1-6) JBAS015899: WildFly 8.0.0.Final "WildFly" starting
20:26:53,805 INFO [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) JBAS015003: Found UserManagment.war in deployment directory. To trigger deployment create a file called UserManagment.war.dodeploy
20:26:53,827 INFO [org.jboss.as.server] (Controller Boot Thread) JBAS015888: Creating http management service using socket-binding (management-http)
20:26:53,856 INFO [org.xnio] (MSC service thread 1-7) XNIO version 3.2.0.Final
20:26:53,868 INFO [org.xnio.nio] (MSC service thread 1-7) XNIO NIO Implementation Version 3.2.0.Final
20:26:53,966 INFO [org.jboss.as.connector.subsystems.datasources] (ServerService Thread Pool -- 28) JBAS010403: Deploying JDBC-compliant driver class org.h2.Driver (version 1.3)
20:26:53,976 INFO [org.jboss.as.connector.subsystems.datasources] (ServerService Thread Pool -- 28) JBAS010404: Deploying non-JDBC-compliant driver class com.mysql.jdbc.Driver (version 5.1)
20:26:54,053 INFO [org.wildfly.extension.undertow] (ServerService Thread Pool -- 49) JBAS017502: Undertow 1.0.0.Final starting
20:26:54,037 INFO [org.jboss.as.naming] (ServerService Thread Pool -- 41) JBAS011800: Activating Naming Subsystem
20:26:54,060 INFO [org.jboss.as.security] (ServerService Thread Pool -- 46) JBAS013171: Activating Security Subsystem
20:26:54,061 INFO [org.wildfly.extension.undertow] (MSC service thread 1-2) JBAS017502: Undertow 1.0.0.Final starting
20:26:54,063 INFO [org.jboss.as.security] (MSC service thread 1-2) JBAS013170: Current PicketBox version=4.0.20.Final
20:26:54,095 INFO [org.jboss.as.webservices] (ServerService Thread Pool -- 50) JBAS015537: Activating WebServices Extension
20:26:54,099 INFO [org.jboss.as.jsf] (ServerService Thread Pool -- 39) JBAS012615: Activated the following JSF Implementations: [main]
20:26:54,138 INFO [org.jboss.as.clustering.infinispan] (ServerService Thread Pool -- 33) JBAS010280: Activating Infinispan subsystem.
20:26:54,180 INFO [org.jboss.as.connector.logging] (MSC service thread 1-3) JBAS010408: Starting JCA Subsystem (IronJacamar 1.1.3.Final)
20:26:54,202 INFO [org.jboss.as.naming] (MSC service thread 1-5) JBAS011802: Starting Naming Service
20:26:54,222 INFO [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-2) JBAS010417: Started Driver service with driver-name = mysql
20:26:54,223 INFO [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-2) JBAS010417: Started Driver service with driver-name = h2
20:26:54,214 INFO [org.jboss.as.mail.extension] (MSC service thread 1-5) JBAS015400: Bound mail session [java:jboss/mail/Default]
20:26:54,505 INFO [org.jboss.as.connector.subsystems.datasources] (MSC service thread 1-4) JBAS010400: Bound data source [java:/DsBibliotheque]
20:26:54,506 INFO [org.jboss.as.connector.subsystems.datasources] (MSC service thread 1-4) JBAS010400: Bound data source [java:/DsBanque]
20:26:54,661 INFO [org.wildfly.extension.undertow] (ServerService Thread Pool -- 49) JBAS017527: Creating file handler for path C:\Users\Emel\wildfly-8.0.0.Final/welcome-content
20:26:54,689 INFO [org.wildfly.extension.undertow] (MSC service thread 1-4) JBAS017525: Started server default-server.
20:26:54,699 INFO [org.wildfly.extension.undertow] (MSC service thread 1-4) JBAS017531: Host default-host starting
20:26:54,781 INFO [org.jboss.remoting] (MSC service thread 1-7) JBoss Remoting version 4.0.0.Final
20:26:54,981 INFO [org.jboss.as.server.deployment.scanner] (MSC service thread 1-4) JBAS015012: Started FileSystemDeploymentService for directory C:\Users\Emel\wildfly-8.0.0.Final\standalone\deployments
20:26:54,987 INFO [org.jboss.as.server.deployment] (MSC service thread 1-7) JBAS015876: Starting deployment of "UserManagment.war" (runtime-name: "UserManagment.war")
20:26:55,191 INFO [org.wildfly.extension.undertow] (MSC service thread 1-8) JBAS017519: Undertow HTTP listener default listening on localhost/127.0.0.1:8180
20:26:55,399 INFO [org.jboss.as.connector.subsystems.datasources] (MSC service thread 1-6) JBAS010400: Bound data source [java:jboss/datasources/ExampleDS]
20:26:55,728 INFO [org.jboss.ws.common.management] (MSC service thread 1-8) JBWS022052: Starting JBoss Web Services - Stack CXF Server 4.2.3.Final
20:26:56,055 ERROR [org.jboss.remoting.remote.connection] (XNIO-1 I/O-1) JBREM000200: Remote connection failed: java.io.IOException: Une connexion établie a été abandonnée par un logiciel de votre ordinateur hôte
20:26:56,057 ERROR [org.jboss.remoting.remote.connection] (XNIO-1 I/O-2) JBREM000200: Remote connection failed: java.io.IOException: Une connexion établie a été abandonnée par un logiciel de votre ordinateur hôte
20:26:56,571 INFO [org.jboss.resteasy.spi.ResteasyDeployment] (MSC service thread 1-3) Deploying javax.ws.rs.core.Application: class com.TP6.RestApplicationConfig
20:26:56,615 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-3) MSC000001: Failed to start service jboss.undertow.deployment.default-server.default-host./UserManagment: org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./UserManagment: Failed to start service
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1904) [jboss-msc-1.2.0.Final.jar:1.2.0.Final]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [rt.jar:1.8.0_91]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [rt.jar:1.8.0_91]
at java.lang.Thread.run(Unknown Source) [rt.jar:1.8.0_91]
Caused by: java.lang.NoClassDefFoundError: Lcom/mysql/jdbc/Connection;
at java.lang.Class.getDeclaredFields0(Native Method) [rt.jar:1.8.0_91]
at java.lang.Class.privateGetDeclaredFields(Unknown Source) [rt.jar:1.8.0_91]
at java.lang.Class.getDeclaredFields(Unknown Source) [rt.jar:1.8.0_91]
at org.jboss.resteasy.spi.metadata.ResourceBuilder.processDeclaredFields(ResourceBuilder.java:867)
at org.jboss.resteasy.spi.metadata.ResourceBuilder.processFields(ResourceBuilder.java:849)
at org.jboss.resteasy.spi.metadata.ResourceBuilder.fromAnnotations(ResourceBuilder.java:755)
at org.jboss.resteasy.spi.metadata.ResourceBuilder.rootResourceFromAnnotations(ResourceBuilder.java:700)
at org.jboss.resteasy.plugins.server.resourcefactory.POJOResourceFactory.<init>(POJOResourceFactory.java:29)
at org.jboss.resteasy.core.ResourceMethodRegistry.addPerRequestResource(ResourceMethodRegistry.java:75)
at org.jboss.resteasy.spi.ResteasyDeployment.registration(ResteasyDeployment.java:400)
at org.jboss.resteasy.spi.ResteasyDeployment.start(ResteasyDeployment.java:241)
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.init(ServletContainerDispatcher.java:112)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.init(HttpServletDispatcher.java:36)
at io.undertow.servlet.core.ManagedServlet$DefaultInstanceStrategy.start(ManagedServlet.java:208)
at io.undertow.servlet.core.ManagedServlet.createServlet(ManagedServlet.java:116)
at io.undertow.servlet.core.DeploymentManagerImpl.start(DeploymentManagerImpl.java:496)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:87)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.start(UndertowDeploymentService.java:71)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948) [jboss-msc-1.2.0.Final.jar:1.2.0.Final]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881) [jboss-msc-1.2.0.Final.jar:1.2.0.Final]
... 3 more
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Connection from [Module "deployment.UserManagment.war:main" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:197) [jboss-modules.jar:1.3.0.Final]
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:443) [jboss-modules.jar:1.3.0.Final]
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:431) [jboss-modules.jar:1.3.0.Final]
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:373) [jboss-modules.jar:1.3.0.Final]
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:118) [jboss-modules.jar:1.3.0.Final]
... 23 more
20:26:56,630 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) JBAS014613: Operation ("deploy") failed - address: ([("deployment" => "UserManagment.war")]) - failure description: {"JBAS014671: Failed services" => {"jboss.undertow.deployment.default-server.default-host./UserManagment" => "org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./UserManagment: Failed to start service
Caused by: java.lang.NoClassDefFoundError: Lcom/mysql/jdbc/Connection;
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Connection from [Module \"deployment.UserManagment.war:main\" from Service Module Loader]"}}
20:26:56,667 INFO [org.jboss.as.server] (ServerService Thread Pool -- 29) JBAS018559: Deployed "UserManagment.war" (runtime-name : "UserManagment.war")
20:26:56,671 INFO [org.jboss.as.controller] (Controller Boot Thread) JBAS014774: Service status report
JBAS014777: Services which failed to start: service jboss.undertow.deployment.default-server.default-host./UserManagment: org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./UserManagment: Failed to start service
20:26:56,866 INFO [org.jboss.as] (Controller Boot Thread) JBAS015961: Http management interface listening on http://127.0.0.1:10090/management
20:26:56,866 INFO [org.jboss.as] (Controller Boot Thread) JBAS015951: Admin console listening on http://127.0.0.1:10090
20:26:56,867 ERROR [org.jboss.as] (Controller Boot Thread) JBAS015875: WildFly 8.0.0.Final "WildFly" started (with errors) in 5188ms - Started 257 of 314 services (2 services failed or missing dependencies, 90 services are lazy, passive or on-demand)
20:26:56,931 INFO [org.hibernate.validator.internal.util.Version] (MSC service thread 1-2) HV000001: Hibernate Validator 5.0.3.Final
20:26:56,982 INFO [org.jboss.as.server.deployment] (MSC service thread 1-6) JBAS015877: Stopped deployment UserManagment.war (runtime-name: UserManagment.war) in 81ms
20:26:57,176 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS018558: Undeployed "UserManagment.war" (runtime-name: "UserManagment.war")
20:26:57,178 INFO [org.jboss.as.controller] (DeploymentScanner-threads - 2) JBAS014774: Service status report
JBAS014775: New missing/unsatisfied dependencies:
service jboss.deployment.unit."UserManagment.war".component."com.sun.faces.config.ConfigureListener".START (missing) dependents: [service jboss.deployment.unit."UserManagment.war".deploymentCompleteService]
service jboss.deployment.unit."UserManagment.war".component."javax.faces.webapp.FacetTag".START (missing) dependents: [service jboss.deployment.unit."UserManagment.war".deploymentCompleteService]
service jboss.deployment.unit."UserManagment.war".component."javax.servlet.jsp.jstl.tlv.PermittedTaglibsTLV".START (missing) dependents: [service jboss.deployment.unit."UserManagment.war".deploymentCompleteService]
service jboss.deployment.unit."UserManagment.war".component."javax.servlet.jsp.jstl.tlv.ScriptFreeTLV".START (missing) dependents: [service jboss.deployment.unit."UserManagment.war".deploymentCompleteService]
service jboss.undertow.deployment.default-server.default-host./UserManagment (missing) dependents: [service jboss.deployment.unit."UserManagment.war".deploymentCompleteService]
JBAS014777: Services which failed to start: service jboss.undertow.deployment.default-server.default-host./UserManagment
20:27:01,705 INFO [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 2) JBAS015003: Found UserManagment.war in deployment directory. To trigger deployment create a file called UserManagment.war.dodeploy
PS:我使用eclipse,wildfly 8.0作为服务器,postman尝试url,我已经创建了mysql数据库。 当我删除数据库连接文件和用户服务中的数据库代码块时,它再次工作,这就是为什么我确定问题出在数据库连接上。
以防万一你想知道我的目标是什么,我正在开发一个Android应用程序,它消耗了一个从数据库中获取数据的宁静的web服务!
感谢您帮助我!
答案 0 :(得分:0)
当我们看到NoClassDefFoundError
,ClassNotFoundException
,NoSuchMethodException
之类的错误时,这意味着JVM在没有找到它的情况下搜索了一个类/方法。
但是等等,我的项目编译得很好,为什么它找不到它们?!!!
要回答我必须解释运行时依赖性和编译时依赖性之间的区别。
当A使用B.jar时(在你的情况下A是你的项目而B.jar是mysql.jar)我们说A依赖于B(B是A的依赖),如果A不能编译没有B但可以在没有它的情况下运行我们说B是编译时依赖,通常IDE不会将这些库复制到最终结果(jar或war文件)。
当A不能在没有B的情况下运行时,我们说B是运行时依赖,通常IDE包括那些进入最终结果(jar或war文件)。
在您的情况下,mysql.jar是一个运行时依赖项,但我希望您将其配置为编译时依赖项,这就是您的项目编译但无法运行的原因。
为了解决这个问题,我们在IDE中正确配置它,对于eclipse我们这样做(假设你已经将mysql.jar添加到了库中):
Build Path
下选择Configure Build Path
。 Deployment Assembly
。 Java Build Path Entries
。 mysql.jar
如果这些步骤开始如我所料,eclipse会将mysql.jar
复制到WEB-INF/lib
文件夹中,您的问题将会解决(我的eclipse版本是Neon,我希望这些说明适用于您的版本)。
一些建议: