
実現したいこと
①Javaの環境変数の設定ができているのか知りたいです
②エラーになっている理由が知りたいです
前提
Macを使って独学でJava、tomcat、MySQLを勉強しています。
Youtube を参考にしてJDBCを学習していたのですが、コンパイルが通っても実行結果が「null」で返ってきます。
環境の設定が間違っているのか、コードが間違っているのかわかりません。
ご教授お願いいたします。
/Library/apache-tomcat-9.0.72/webapps/dbweb ├ showname.html ├ initialize.sql ├ showname.jsp │ └ /WEB-INF/classes └ ShowNameServlet.java
mysql> use sampledb mysql> SELECT * FROM student; +----+--------+-------+ | no | name | score | +----+--------+-------+ | 1 | 菅原 | 60 | | 2 | 桜井 | 100 | | 3 | 田原 | 85 | | 4 | 中川 | 90 | | 5 | 鈴木 | 75 | | 6 | 小林 | 95 | | 7 | 藤原 | 90 | | 8 | 草野 | 85 | | 9 | 常田 | 80 | | 10 | 小橋 | 75 | +----+--------+-------+ 10 rows in set (0.00 sec)
発生している問題・エラーメッセージ
該当のソースコード
showname.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>ボタン画面</title> </head> <body> <h2>noが1の生徒名を表示します</h2> <form action="/dbweb/showname" method="post"> <input type="submit" value="実行" /> </form> </body> </html>
ShowNameServlet.java
import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; @WebServlet("/showname") public class ShowNameServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { final String URL = "jdbc:mysql://localhost/sampledb"; final String USER = "root"; final String PASS = "pass"; String sql = "SELECT name FROM student WHERE no = 1"; Connection con = null; Statement stmt = null; ResultSet rs = null; try{ con = DriverManager.getConnection(URL, USER, PASS); stmt = con.createStatement(); rs = stmt.executeQuery(sql); rs.next(); String name = rs.getString("name"); req.setAttribute("name", name); } catch(Exception e){ e.printStackTrace(); } finally { try{ if(rs != null) rs.close(); if(stmt != null) stmt.close(); if(con != null) con.close(); } catch(Exception e){ e.printStackTrace(); } } RequestDispatcher rd = req.getRequestDispatcher("/showname.jsp"); rd.forward(req, res); } public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { doPost(req, res); } }
showname.jsp
<%@page contentType="text/html;charset=utf-8" %> <html> <head> <title>表示画面</title> </head> <body> <h2>noが1の生徒名は <%= request.getAttribute("name") %> です </h2> </body> </html>
initialize.sql
DELETE FROM student; INSERT INTO student VALUES(1,'菅原',60); INSERT INTO student VALUES(2,'桜井',100); INSERT INTO student VALUES(3,'田原',85); INSERT INTO student VALUES(4,'中川',90); INSERT INTO student VALUES(5,'鈴木',75); INSERT INTO student VALUES(6,'小林',95); INSERT INTO student VALUES(7,'藤原',90); INSERT INTO student VALUES(8,'草野',85); INSERT INTO student VALUES(9,'常田',80); INSERT INTO student VALUES(10,'小橋',75);


回答2件
あなたの回答
tips
プレビュー