我使用Servlet-JSP-MongoDB开发基本的用户管理项目。我的代码如下。在Tomcat上运行项目后,我在控制台上的异常如下。
为什么会出现这个问题,请帮助我?
package com.fatih.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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.fatih.dao.UserDAO;
import com.fatih.model.User;
import com.mongodb.MongoClient;
/**
* Servlet implementation class AddUser
*/
@WebServlet("/addUser")
public class AddUser extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddUser() {
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
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("name");
String email=request.getParameter("emailId");
String password=request.getParameter("password");
if( (name==null || name.equals(""))||
(email==null || email.equals(""))||
(password==null || password.equals(""))){
request.setAttribute("error", "All fields are required!");
RequestDispatcher dispatcher=getServletContext().getRequestDispatcher("/users.jsp");
dispatcher.forward(request, response);
}else{
User user=new User();
user.setName(name);
user.setEmail(email);
user.setPassword(password);
MongoClient mongoClient=(MongoClient) request.getServletContext().getAttribute("MONGO_CLIENT");
UserDAO userDAO=new UserDAO(mongoClient);
userDAO.createUser(user);
request.setAttribute("success", "User added");
RequestDispatcher dispatcher=getServletContext().getRequestDispatcher("/users.jsp");
dispatcher.forward(request, response);
}
System.out.println("name: "+name+"\nemail: "+email+"\npassword: "+password);
}
}
............................................... ........................
package com.fatih.conventer;
import org.bson.types.ObjectId;
import com.fatih.model.User;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DBObject;
public class UserConventer {
public static DBObject toDBObject(User user) {
BasicDBObjectBuilder builder=BasicDBObjectBuilder.start()
.append("name", user.getName())
.append("email", user.getEmail())
.append("password", user.getPassword());
if(user.getId()!=null){
builder=builder.append("_id", new ObjectId(user.getId()));
}
return builder.get();
}
}
............................................... ...........................
package com.fatih.dao;
import org.bson.types.ObjectId;
import com.fatih.conventer.UserConventer;
import com.fatih.model.User;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
public class UserDAO {
private DBCollection dbCollection;
public UserDAO(MongoClient mongoClient) {
this.dbCollection=mongoClient.getDB("usersDB").getCollection("users");
}
public User createUser(User user){
DBObject dbObject=UserConventer.toDBObject(user);
this.dbCollection.insert(dbObject);
ObjectId id=(ObjectId) dbObject.get("_id");
user.setId(id.toString());
return user;
}
}
............................................... ...........
package com.fatih.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import com.mongodb.MongoClient;
@WebListener
public class MongoDBListener implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent sce) {
MongoClient mongoClient=(MongoClient) sce.getServletContext().getAttribute("MONGO_CLIENT");
mongoClient.close();
}
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext context=sce.getServletContext();
MongoClient mongoClient=new MongoClient(context.getInitParameter("MONGO_HOST"),Integer.parseInt(context.getInitParameter("MONGO_PORT")));
sce.getServletContext().setAttribute("MONGO_CLIENT", mongoClient);
}
}
............................................... .......................
package com.fatih.model;
public class User {
private String id;
private String name;
private String email;
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>KullaniciYonetimSistemiMongoDB</display-name>
<context-param>
<param-name>MONGO_HOST</param-name>
<param-value>localhost</param-value>
</context-param>
<context-param>
<param-name>MONGO_PORT</param-name>
<param-value>27017</param-value>
</context-param>
<welcome-file-list>
<welcome-file>users.jsp</welcome-file>
</welcome-file-list>
</web-app>
Consol output is bellow:
Kas 26, 2016 4:53:23 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:KullaniciYonetimSistemiMongoDB' did not find a matching property.
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version: Apache Tomcat/8.0.36
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built: Jun 9 2016 13:55:50 UTC
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number: 8.0.36.0
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name: Windows 7
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version: 6.1
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture: amd64
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home: C:\Program Files\Java\jre1.8.0_111
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version: 1.8.0_111-b14
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor: Oracle Corporation
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE: C:\javaTools\apache-tomcat-8.0.36
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME: C:\javaTools\apache-tomcat-8.0.36
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\javaTools\apache-tomcat-8.0.36
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\javaTools\apache-tomcat-8.0.36
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\javaTools\apache-tomcat-8.0.36\wtpwebapps
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\javaTools\apache-tomcat-8.0.36\endorsed
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1254
Kas 26, 2016 4:53:23 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre1.8.0_111\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre1.8.0_111/bin/server;C:/Program Files/Java/jre1.8.0_111/bin;C:/Program Files/Java/jre1.8.0_111/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Java\jdk1.8.0_101\bin;C:\Program Files\Git\cmd;C:\Program Files (x86)\MySQL\MySQL Fabric 1.5 & MySQL Utilities 1.5\;C:\Program Files (x86)\MySQL\MySQL Fabric 1.5 & MySQL Utilities 1.5\Doctrine extensions for PHP\;C:\Program Files\nodejs\;C:\Program Files (x86)\Skype\Phone\;C:\Program Files (x86)\Calibre2\;C:\Program Files (x86)\scala\bin;C:\Program Files\Java\jdk1.8.0_101\bin\;C:\Users\mypc\AppData\Roaming\npm;C:\adb; C:\maven\apache-maven-3.3.9\bin;C:\maven\apache-maven-3.3.9\bin;C:\Users\mypc\AppData\Roaming\npm;%M2%;C:\Program Files\MongoDB\Server\3.2\bin;;C:\Users\mypc\Downloads\programlar\eclipse;;.
Kas 26, 2016 4:53:24 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Kas 26, 2016 4:53:24 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Kas 26, 2016 4:53:24 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Kas 26, 2016 4:53:24 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Kas 26, 2016 4:53:24 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2248 ms
Kas 26, 2016 4:53:24 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Kas 26, 2016 4:53:24 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.36
Kas 26, 2016 4:53:26 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Kas 26, 2016 4:53:26 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\docs
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deployment of web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\docs has finished in 35 ms
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\examples
Kas 26, 2016 4:53:27 PM org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextInitialized()
Kas 26, 2016 4:53:27 PM org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: contextInitialized()
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deployment of web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\examples has finished in 586 ms
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\host-manager
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deployment of web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\host-manager has finished in 64 ms
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\manager
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deployment of web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\manager has finished in 58 ms
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\ROOT
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deployment of web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\ROOT has finished in 33 ms
Kas 26, 2016 4:53:27 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Kas 26, 2016 4:53:27 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 2953 ms
Kas 26, 2016 4:53:28 PM com.mongodb.diagnostics.logging.JULLogger log
**INFO: Exception in monitor thread while connecting to server localhost:27017
com.mongodb.MongoSocketOpenException: Exception opening socket**
at com.mongodb.connection.SocketStream.open(SocketStream.java:63)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:116)
at java.lang.Thread.run(Unknown Source)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(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.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
... 3 more
**Kas 26, 2016 4:53:37 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by WritableServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]}. Waiting for 30000 ms before timing out**
**Kas 26, 2016 4:54:07 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.fatih.controller.AddUser] in context with path [/KullaniciYonetimSistemiMongoDB] threw exception
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches WritableServerSelector. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]**
at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:375)
at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:104)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71)
at com.mongodb.binding.ClusterBinding.getWriteConnectionSource(ClusterBinding.java:68)
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:221)
at com.mongodb.operation.BaseWriteOperation.execute(BaseWriteOperation.java:134)
at com.mongodb.operation.BaseWriteOperation.execute(BaseWriteOperation.java:61)
at com.mongodb.Mongo.execute(Mongo.java:827)
at com.mongodb.Mongo$2.execute(Mongo.java:810)
at com.mongodb.DBCollection.executeWriteOperation(DBCollection.java:333)
at com.mongodb.DBCollection.insert(DBCollection.java:328)
at com.mongodb.DBCollection.insert(DBCollection.java:319)
at com.mongodb.DBCollection.insert(DBCollection.java:289)
at com.mongodb.DBCollection.insert(DBCollection.java:255)
at com.mongodb.DBCollection.insert(DBCollection.java:192)
at com.fatih.dao.UserDAO.createUser(UserDAO.java:23)
at com.fatih.controller.AddUser.doPost(AddUser.java:69)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
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:141)
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:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
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)
***IN WEB BROWSER:***
**HTTP Status 500 - Timed out after 30000 ms while waiting for a server that matches WritableServerSelector. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]**
**type Exception report
message Timed out after 30000 ms while waiting for a server that matches WritableServerSelector. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]
description The server encountered an internal error that prevented it from fulfilling this request.
exception
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches WritableServerSelector. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]
com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:375)
com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:104)
com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75)
com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71)
com.mongodb.binding.ClusterBinding.getWriteConnectionSource(ClusterBinding.java:68)
com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:221)
com.mongodb.operation.BaseWriteOperation.execute(BaseWriteOperation.java:134)
com.mongodb.operation.BaseWriteOperation.execute(BaseWriteOperation.java:61)
com.mongodb.Mongo.execute(Mongo.java:827)
com.mongodb.Mongo$2.execute(Mongo.java:810)
com.mongodb.DBCollection.executeWriteOperation(DBCollection.java:333)
com.mongodb.DBCollection.insert(DBCollection.java:328)
com.mongodb.DBCollection.insert(DBCollection.java:319)
com.mongodb.DBCollection.insert(DBCollection.java:289)
com.mongodb.DBCollection.insert(DBCollection.java:255)
com.mongodb.DBCollection.insert(DBCollection.java:192)
com.fatih.dao.UserDAO.createUser(UserDAO.java:23)
com.fatih.controller.AddUser.doPost(AddUser.java:69)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.36 logs.**
答案 0 :(得分:0)
我解决了这个问题;我在pom.xml.Project中成功运行mongodb java驱动程序版本从3.0.1更改为2.13.3。