質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
MySQL

MySQL(マイエスキューエル)は、TCX DataKonsultAB社などが開発するRDBMS(リレーショナルデータベースの管理システム)です。世界で最も人気の高いシステムで、オープンソースで開発されています。MySQLデータベースサーバは、高速性と信頼性があり、Linux、UNIX、Windowsなどの複数のプラットフォームで動作することができます。

JSP

JSP(Java Server Pages)とは、ウェブアプリケーションの表示レイヤーに使われるサーバーサイドの技術のことです。

servlet

Servletとは、Webページの動的な生成やデータ処理などをサーバ上で実行するために、Javaで作成されたプログラムです。 ショッピングサイトやオンラインバンキングといった、動的なウェブサイトの構築に用いられています。

Tomcat

TomcatはApache Software Foundation (ASF)で開発されたオープンソースのWebコンテナです。

Q&A

2回答

11457閲覧

MySQLSyntaxErrorExceptionというエラー

l_l_l_l_l_l_l_l

総合スコア38

MySQL

MySQL(マイエスキューエル)は、TCX DataKonsultAB社などが開発するRDBMS(リレーショナルデータベースの管理システム)です。世界で最も人気の高いシステムで、オープンソースで開発されています。MySQLデータベースサーバは、高速性と信頼性があり、Linux、UNIX、Windowsなどの複数のプラットフォームで動作することができます。

JSP

JSP(Java Server Pages)とは、ウェブアプリケーションの表示レイヤーに使われるサーバーサイドの技術のことです。

servlet

Servletとは、Webページの動的な生成やデータ処理などをサーバ上で実行するために、Javaで作成されたプログラムです。 ショッピングサイトやオンラインバンキングといった、動的なウェブサイトの構築に用いられています。

Tomcat

TomcatはApache Software Foundation (ASF)で開発されたオープンソースのWebコンテナです。

0グッド

0クリップ

投稿2016/06/13 00:50

###前提・実現したいこと
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

Login.jsp

###Servlet

loginservlet

1package servlet; 2 3import java.io.IOException; 4import java.sql.Connection; 5import java.sql.PreparedStatement; 6import java.sql.ResultSet; 7 8import javax.naming.Context; 9import javax.naming.InitialContext; 10import javax.servlet.ServletException; 11import javax.servlet.annotation.WebServlet; 12import javax.servlet.http.HttpServlet; 13import javax.servlet.http.HttpServletRequest; 14import javax.servlet.http.HttpServletResponse; 15import javax.servlet.http.HttpSession; 16import javax.sql.DataSource; 17 18/** 19 * Servlet implementation class loginservlet 20 */ 21@WebServlet("/loginservlet") 22public class loginservlet extends HttpServlet { 23 private static final long serialVersionUID = 1L; 24 25 /** 26 * @see HttpServlet#HttpServlet() 27 */ 28 public loginservlet() { 29 super(); 30 // TODO Auto-generated constructor stub 31 } 32 33 /** 34 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse 35 * response) 36 */ 37 protected void doGet(HttpServletRequest request, 38 HttpServletResponse response) throws ServletException, IOException { 39 // TODO Auto-generated method stub 40 } 41 42 /** 43 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 44 * response) 45 */ 46 protected void doPost(HttpServletRequest request, 47 HttpServletResponse response) throws ServletException, IOException { 48 // TODO Auto-generated method stub 49 Connection con = null; 50 PreparedStatement ps = null; 51 String sql = null; 52 ResultSet rs = null; 53 54 String userid = request.getParameter("userid"); 55 String pass = request.getParameter("pass"); 56 57 if (userid == null || userid.length() == 0) { 58 59 request.setAttribute("errorMessage", "ユーザ名が未入力です"); 60 61 this.getServletContext().getRequestDispatcher("/Login.jsp") 62 .forward(request, response); 63 } else if (pass == null || pass.length() == 0) { 64 65 request.setAttribute("errorMessage", "パスワードが未入力です"); 66 67 this.getServletContext().getRequestDispatcher("/Login.jsp") 68 .forward(request, response); 69 } else { 70 try { 71 72 Context initContext = new InitialContext(); 73 Context envContext = (Context) initContext 74 .lookup("java:comp/env"); 75 DataSource ds = (DataSource) envContext.lookup("jdbc/Library"); 76 con = ds.getConnection(); 77 78 sql = "SELECT user_id,password FROM user"; 79 80 ps = con.prepareStatement(sql); 81 82 rs = ps.executeQuery(); 83 84 boolean userResult = false; 85 boolean ad = false; 86 while (rs.next()) { 87 88 String dbuserid = rs.getString("user_id"); 89 String dbpassword = rs.getString("password"); 90 91 if (dbuserid.equals(userid) && dbpassword.equals(pass)) { 92 userResult = true; 93 /* 94 * if ("管理者".equals(rs.getString("admin"))) { ad = true; 95 * } 96 */ 97 98 } 99 } 100 101 if (userResult) { 102 103 HttpSession session = request.getSession(); 104 105 session.setAttribute("userResult", userResult); 106 session.setAttribute("admin", ad); 107 108 this.getServletContext().getRequestDispatcher("/a.jsp") 109 .forward(request, response); 110 } else { 111 112 request.setAttribute("errorMessage", "ユーザ名またはパスワードが違います"); 113 114 this.getServletContext().getRequestDispatcher("/Login.jsp") 115 .forward(request, response); 116 } 117 } catch (Exception e) { 118 119 request.setAttribute("errorMessage", "システムエラーが発生しました。"); 120 121 this.getServletContext().getRequestDispatcher("/Login.jsp") 122 .forward(request, response); 123 124 throw new ServletException(e); 125 } finally { 126 try { 127 if (rs != null) { 128 rs.close(); 129 } 130 if (ps != null) { 131 ps.close(); 132 } 133 if (con != null) { 134 con.close(); 135 } 136 } catch (Exception e) { 137 } 138 } 139 } 140 141 } 142 143} 144 145

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

例外メッセージをたどると「Access denied for user ''@'localhost' to database 'library'」

データベース接続はJNDIルックアップで取得しているデータソースですので、データベースの接続を記述している設定に問題があります。
user ''@'localhost'と出ていますので、データベース接続ユーザ名が指定されていません。

投稿2016/06/13 01:01

A-pZ

総合スコア12011

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

Exceptionのメッセージを見る限り、SQL実行以前にデータベースへの接続(コネクションプールの作成)に失敗しているようです。それは、接続ユーザの設定に誤りがあるからのようです。(エラーメッセージより確認)

tomcatの設定(server.xml)におけるJNDIの設定にミスがありそうです。
JNDI設定のDB接続用ユーザ名、パスワードの部分を再確認ください。

もし解決しない場合、server.xmlを質問文に追記することは可能ですか?
ユーザ名やパスワードは、セキュリティを考慮し伏字としてください。

投稿2016/06/13 00:59

takyafumin

総合スコア2335

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

l_l_l_l_l_l_l_l

2016/06/13 01:08 編集

<?xml Version="1.0" Encoding="UTF-8"?> <!-- 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 &quot;%r&quot; %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>
takyafumin

2016/06/13 01:38

server.xmlの追記ありがとうございます。 コメント欄ではなく、質問文にコードタグで囲って追記いただけると他の方も含め見やすくてよいですね。 内容確認したところ、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情報など)も追記いただけるとさらに良いと思います。
l_l_l_l_l_l_l_l

2016/06/13 02:11

ご回答に沿ってやってみたのですがTomcatが始動しませんでした。 というエラーが出てきてしまうようになってしまいました。 リンク先の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から行っています。
takyafumin

2016/06/14 11:07

リンク先HPの記述そのままでは動作しません。 既にアプリケーション用の<Context>タグがあるようですので、その中に<Resource>タグとしてJDBCデータソースの定義を追加してみてください。 またurl=""で指定するjdbc接続文字列はご自身の環境に合わせてホスト名、ポート番号、DB名を正しく指定するようにしてください。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問