MySQLSyntaxErrorExceptionというエラー
受付中
回答 2
投稿
- 評価
- クリップ 0
- VIEW 5,422
前提・実現したいこと
JSP/Servletを使いログイン画面を作成しているのですが、
表題のエラーが発生し例外処理が実行されてしまいます。
サーバ:Tomcat
DB:MYSQL
SQLが間違えているとは思うのですが、
どこが間違えているか分かりません。
発生している問題・エラーメッセージ
エラーメッセージ
重大: Servlet.service() for servlet [servlet.loginservlet] in context with path [/Library] threw exception [java.sql.SQLException: Cannot create PoolableConnectionFactory (Access denied for user ''@'localhost' to database 'library')] with root cause
JSP
<%@ page import="java.sql.*,javax.naming.*,javax.sql.*"
contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/login.css">
<title>ログイン</title>
</head>
<body>
<form method="POST" action="loginservlet">
<br>
<div>
ユーザ I D : <input type="text" name="userid" />
</div>
<br>
<div>
パスワード : <input type="password" name="pass" />
</div>
<br>
<div>
<button class="button" type="submit" style="float: left">ログイン</button>
<button class="button" type="reset">クリア</button>
</div>
</form>
<c:if test="${!empty requestScope['errorMessage']}">
<div>${requestScope['errorMessage']}</div>
</c:if>
</body>
Servlet
package servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
/**
* Servlet implementation class loginservlet
*/
@WebServlet("/loginservlet")
public class loginservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public loginservlet() {
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
Connection con = null;
PreparedStatement ps = null;
String sql = null;
ResultSet rs = null;
String userid = request.getParameter("userid");
String pass = request.getParameter("pass");
if (userid == null || userid.length() == 0) {
request.setAttribute("errorMessage", "ユーザ名が未入力です");
this.getServletContext().getRequestDispatcher("/Login.jsp")
.forward(request, response);
} else if (pass == null || pass.length() == 0) {
request.setAttribute("errorMessage", "パスワードが未入力です");
this.getServletContext().getRequestDispatcher("/Login.jsp")
.forward(request, response);
} else {
try {
Context initContext = new InitialContext();
Context envContext = (Context) initContext
.lookup("java:comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/Library");
con = ds.getConnection();
sql = "SELECT user_id,password FROM user";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
boolean userResult = false;
boolean ad = false;
while (rs.next()) {
String dbuserid = rs.getString("user_id");
String dbpassword = rs.getString("password");
if (dbuserid.equals(userid) && dbpassword.equals(pass)) {
userResult = true;
/*
* if ("管理者".equals(rs.getString("admin"))) { ad = true;
* }
*/
}
}
if (userResult) {
HttpSession session = request.getSession();
session.setAttribute("userResult", userResult);
session.setAttribute("admin", ad);
this.getServletContext().getRequestDispatcher("/a.jsp")
.forward(request, response);
} else {
request.setAttribute("errorMessage", "ユーザ名またはパスワードが違います");
this.getServletContext().getRequestDispatcher("/Login.jsp")
.forward(request, response);
}
} catch (Exception e) {
request.setAttribute("errorMessage", "システムエラーが発生しました。");
this.getServletContext().getRequestDispatcher("/Login.jsp")
.forward(request, response);
throw new ServletException(e);
} finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (con != null) {
con.close();
}
} catch (Exception e) {
}
}
}
}
}
-
気になる質問をクリップする
クリップした質問は、後からいつでもマイページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
クリップを取り消します
-
良い質問の評価を上げる
以下のような質問は評価を上げましょう
- 質問内容が明確
- 自分も答えを知りたい
- 質問者以外のユーザにも役立つ
評価が高い質問は、TOPページの「注目」タブのフィードに表示されやすくなります。
質問の評価を上げたことを取り消します
-
評価を下げられる数の上限に達しました
評価を下げることができません
- 1日5回まで評価を下げられます
- 1日に1ユーザに対して2回まで評価を下げられます
質問の評価を下げる
teratailでは下記のような質問を「具体的に困っていることがない質問」、「サイトポリシーに違反する質問」と定義し、推奨していません。
- プログラミングに関係のない質問
- やってほしいことだけを記載した丸投げの質問
- 問題・課題が含まれていない質問
- 意図的に内容が抹消された質問
- 過去に投稿した質問と同じ内容の質問
- 広告と受け取られるような投稿
評価が下がると、TOPページの「アクティブ」「注目」タブのフィードに表示されにくくなります。
質問の評価を下げたことを取り消します
この機能は開放されていません
評価を下げる条件を満たしてません
質問の評価を下げる機能の利用条件
この機能を利用するためには、以下の事項を行う必要があります。
- 質問回答など一定の行動
-
メールアドレスの認証
メールアドレスの認証
-
質問評価に関するヘルプページの閲覧
質問評価に関するヘルプページの閲覧
+1
Exceptionのメッセージを見る限り、SQL実行以前にデータベースへの接続(コネクションプールの作成)に失敗しているようです。それは、接続ユーザの設定に誤りがあるからのようです。(エラーメッセージより確認)
tomcatの設定(server.xml)におけるJNDIの設定にミスがありそうです。
JNDI設定のDB接続用ユーザ名、パスワードの部分を再確認ください。
もし解決しない場合、server.xmlを質問文に追記することは可能ですか?
ユーザ名やパスワードは、セキュリティを考慮し伏字としてください。
投稿
-
回答の評価を上げる
以下のような回答は評価を上げましょう
- 正しい回答
- わかりやすい回答
- ためになる回答
評価が高い回答ほどページの上位に表示されます。
-
回答の評価を下げる
下記のような回答は推奨されていません。
- 間違っている回答
- 質問の回答になっていない投稿
- スパムや攻撃的な表現を用いた投稿
評価を下げる際はその理由を明確に伝え、適切な回答に修正してもらいましょう。
+1
例外メッセージをたどると「Access denied for user ''@'localhost' to database 'library'」
データベース接続はJNDIルックアップで取得しているデータソースですので、データベースの接続を記述している設定に問題があります。
user ''@'localhost'
と出ていますので、データベース接続ユーザ名が指定されていません。
投稿
-
回答の評価を上げる
以下のような回答は評価を上げましょう
- 正しい回答
- わかりやすい回答
- ためになる回答
評価が高い回答ほどページの上位に表示されます。
-
回答の評価を下げる
下記のような回答は推奨されていません。
- 間違っている回答
- 質問の回答になっていない投稿
- スパムや攻撃的な表現を用いた投稿
評価を下げる際はその理由を明確に伝え、適切な回答に修正してもらいましょう。
15分調べてもわからないことは、teratailで質問しよう!
- ただいまの回答率 88.37%
- 質問をまとめることで、思考を整理して素早く解決
- テンプレート機能で、簡単に質問をまとめられる
2016/06/13 10:07 編集
<!--
Licensed To The Apache Software Foundation (ASF) Under One Or More
Contributor License Agreements. See The NOTICE File Distributed With
This Work For Additional Information Regarding Copyright Ownership.
The ASF Licenses This File To You Under The Apache License, Version 2.0
(the "License"); You May Not Use This File Except In Compliance With
The License. You May Obtain A Copy Of The License At
Http://www.apache.org/licenses/LICENSE-2.0
Unless Required By Applicable Law Or Agreed To In Writing, Software
Distributed Under The License Is Distributed On An "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, Either Express Or Implied.
See The License For The Specific Language Governing Permissions And
Limitations Under The License.
--><!-- Note: A "Server" Is Not Itself A "Container", So You May Not
Define Subcomponents Such As "Valves" At This Level.
Documentation At /docs/config/server.html
--><Server Port="8005" Shutdown="SHUTDOWN">
<Listener ClassName="org.apache.catalina.startup.VersionLoggerListener"/>
<!-- Security Listener. Documentation At /docs/config/listeners.html
<Listener ClassName="org.apache.catalina.security.SecurityListener" />
-->
<!--APR Library Loader. Documentation At /docs/apr.html -->
<Listener SSLEngine="on" ClassName="org.apache.catalina.core.AprLifecycleListener"/>
<!-- Prevent Memory Leaks Due To Use Of Particular Java/javax APIs-->
<Listener ClassName="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
<Listener ClassName="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
<Listener ClassName="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>
<!-- Global JNDI Resources
Documentation At /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable User Database That Can Also Be Used By
UserDatabaseRealm To Authenticate Users
-->
<Resource Auth="Container" Description="User Database That Can Be Updated And Saved" Factory="org.apache.catalina.users.MemoryUserDatabaseFactory" Name="UserDatabase" Pathname="conf/tomcat-users.xml" Type="org.apache.catalina.UserDatabase"/>
</GlobalNamingResources>
<!-- A "Service" Is A Collection Of One Or More "Connectors" That Share
A Single "Container" Note: A "Service" Is Not Itself A "Container",
So You May Not Define Subcomponents Such As "Valves" At This Level.
Documentation At /docs/config/service.html
-->
<Service Name="Catalina">
<!--The Connectors Can Use A Shared Executor, You Can Define One Or More Named Thread Pools-->
<!--
<Executor Name="tomcatThreadPool" NamePrefix="catalina-exec-"
MaxThreads="150" MinSpareThreads="4"/>
-->
<!-- A "Connector" Represents An Endpoint By Which Requests Are Received
And Responses Are Returned. Documentation At :
Java HTTP Connector: /docs/config/http.html (blocking & Non-blocking)
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define A Non-SSL/TLS HTTP/1.1 Connector On Port 8080
-->
<Connector ConnectionTimeout="20000" Port="8080" Protocol="HTTP/1.1" RedirectPort="8443"/>
<!-- A "Connector" Using The Shared Thread Pool-->
<!--
<Connector Executor="tomcatThreadPool"
Port="8080" Protocol="HTTP/1.1"
ConnectionTimeout="20000"
RedirectPort="8443" />
-->
<!-- Define A SSL/TLS HTTP/1.1 Connector On Port 8443
This Connector Uses The NIO Implementation That Requires The JSSE
Style Configuration. When Using The APR/native Implementation, The
OpenSSL Style Configuration Is Required As Described In The APR/native
Documentation -->
<!--
<Connector Port="8443" Protocol="org.apache.coyote.http11.Http11NioProtocol"
MaxThreads="150" SSLEnabled="true" Scheme="https" Secure="true"
ClientAuth="false" SslProtocol="TLS" />
-->
<!-- Define An AJP 1.3 Connector On Port 8009 -->
<Connector Port="8009" Protocol="AJP/1.3" RedirectPort="8443"/>
<!-- An Engine Represents The Entry Point (within Catalina) That Processes
Every Request. The Engine Implementation For Tomcat Stand Alone
Analyzes The HTTP Headers Included With The Request, And Passes Them
On To The Appropriate Host (virtual Host).
Documentation At /docs/config/engine.html -->
<!-- You Should Set JvmRoute To Support Load-balancing Via AJP Ie :
<Engine Name="Catalina" DefaultHost="localhost" JvmRoute="jvm1">
-->
<Engine DefaultHost="localhost" Name="Catalina">
<!--For Clustering, Please Take A Look At Documentation At:
/docs/cluster-howto.html (simple How To)
/docs/config/cluster.html (reference Documentation) -->
<!--
<Cluster ClassName="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->
<!-- Use The LockOutRealm To Prevent Attempts To Guess User Passwords
Via A Brute-force Attack -->
<Realm ClassName="org.apache.catalina.realm.LockOutRealm">
<!-- This Realm Uses The UserDatabase Configured In The Global JNDI
Resources Under The Key "UserDatabase". Any Edits
That Are Performed Against This UserDatabase Are Immediately
Available For Use By The Realm. -->
<Realm ClassName="org.apache.catalina.realm.UserDatabaseRealm" ResourceName="UserDatabase"/>
</Realm>
<Host AppBase="webapps" AutoDeploy="true" Name="localhost" UnpackWARs="true">
<!-- SingleSignOn Valve, Share Authentication Between Web Applications
Documentation At: /docs/config/valve.html -->
<!--
<Valve ClassName="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- Access Log Processes All Example.
Documentation At: /docs/config/valve.html
Note: The Pattern Used Is Equivalent To Using Pattern="common" -->
<Valve ClassName="org.apache.catalina.valves.AccessLogValve" Directory="logs" Pattern="%h %l %u %t "%r" %s %b" Prefix="localhost_access_log" Suffix=".txt"/>
<Context DocBase="Library" Path="/Library" Reloadable="true" Source="org.eclipse.jst.jee.server:Library"/></Host>
</Engine>
</Service>
</Server>
2016/06/13 10:38
コメント欄ではなく、質問文にコードタグで囲って追記いただけると他の方も含め見やすくてよいですね。
内容確認したところ、JNDIリソースの設定がされていないようですね。
JNDIを用いてデータベースに接続するには以下のような手続きが必要です。
1.JDBCドライバの入手
2.server.xmlにJNDIリソースの設定を記述
3.web.xmlにJNDIリソースを参照する設定を記述
4.JDNIルックアップを使ってデータソースを取得
具体的な記述内容の回答は質問の丸投げになってしまうので、
まずはこちらのページを参考に設定にトライしてみてください。
http://open-groove.net/tomcat/connection-tomcat-mysql/
解決しない場合は追加で行ったことと、変更後のserver.xml、javaソース、mysqlのサーバ情報を追記いただくと良いかと思います。
あわせて環境情報(java, tomcat, mysqlのバージョンやOS情報など)も追記いただけるとさらに良いと思います。
2016/06/13 11:11
というエラーが出てきてしまうようになってしまいました。
リンク先のHPのように下記のコードをserver.xml,web.xmlに
追記しました。
<Context path="/JDBCtest" reloadable="true" docBase="/JDBCSample" workDir="/JDBCtest/work">
<Resource name="jdbc/Library" auth="Container" type="javax.sql.DataSource"
maxActive="150" maxIdle="50" maxWait="15000"
username="myuser" password="mypassword" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mydb"/>
</Context>
<resource-ref>
<res-ref-name>jdbc/Library</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
バージョンは
エクリプス4.4
tomcat8
mysqlはxamppから行っています。
2016/06/14 20:07
既にアプリケーション用の<Context>タグがあるようですので、その中に<Resource>タグとしてJDBCデータソースの定義を追加してみてください。
またurl=""で指定するjdbc接続文字列はご自身の環境に合わせてホスト名、ポート番号、DB名を正しく指定するようにしてください。