前提・実現したいこと
DBの情報を検索して結果を出力
発生している問題・エラーメッセージ
Search.jspでDBの中身を検索してSearchServlet.javaを経由してSearchResult.jspで出力をしたいのですがSearch.jspで検索したら、SearchServletでnullと出てしまいどこが違うのかが分かりません。
指摘お願いします。
該当のソースコード
jsp
1Search.jsp 2<%@ page language="java" contentType="text/html; charset=UTF-8" 3 pageEncoding="UTF-8"%> 4<!DOCTYPE html> 5<html> 6<head> 7<meta charset="UTF-8"> 8<title>Insert title here</title> 9</head> 10<body> 11 <% String id=(String)request.getAttribute("goods_name"); %> 12 13 <form action="./SearchServlet" method="POST"> 14 15 16 <div>検索したい名前を入力してください?</div> 17 <div> 18 <input type="text" name="name" maxlength="20" size="20"> 19 </div> 20 <input type="submit" value="検索"> 21 22 23 24 25 </form> 26</body> 27</html>
java
1import java.io.IOException; 2import java.sql.Connection; 3import java.sql.DriverManager; 4import java.sql.PreparedStatement; 5import java.sql.ResultSet; 6import java.sql.SQLException; 7 8import javax.servlet.ServletException; 9import javax.servlet.annotation.WebServlet; 10import javax.servlet.http.HttpServlet; 11import javax.servlet.http.HttpServletRequest; 12import javax.servlet.http.HttpServletResponse; 13 14@WebServlet("/SearchServlet") 15public class SearchServlet extends HttpServlet { 16 17 @Override 18 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, 19 IOException { 20 21 22 req.setCharacterEncoding("UTF-8"); 23 String move = "SearchResult.jsp"; 24 25 try { 26 //JDBCドライバの読込 27 Class.forName("com.mysql.cj.jdbc.Driver"); 28 //Connectionの生成 29 Connection con = DriverManager.getConnection( 30 "jdbc:mysql://127.0.0.1:3306/techdb?serverTimezone=JST", 31 "seed", 32 "Tech_123"); 33 String sql = "SELECT * FROM goods"; 34 //Statementの生成 35 PreparedStatement stmt = con.prepareStatement(sql); 36 Integer id; 37 String name = null; 38 //SQLの実行 39 ResultSet rs = stmt.executeQuery(); 40 while (rs.next()) { 41 42 } 43 44 //moveが移動先 45 req.getRequestDispatcher(move).forward(req, resp); 46 req.setAttribute("data",name ); 47 48 //Statement,Connectionの切断 49 stmt.close(); 50 con.close(); 51 52 53 54 } catch (ClassNotFoundException e) { 55 System.out.println("ドライバを読み込めませんでした"+e); 56 } catch (SQLException e) { 57 System.out.println("データベース接続エラー"+e); 58 } 59 } 60 61} 62
jsp
1Result.jsp 2<%@ page language="java" contentType="text/html; charset=UTF-8" 3 pageEncoding="UTF-8"%> 4<!DOCTYPE html> 5<html> 6<head> 7<meta charset="UTF-8"> 8<title>Insert title here</title> 9</head> 10<body> 11 <%= request.getAttribute("data") %> 12</body> 13</html> 14 15
試したこと
nullと出る前はEclipseのコンソールにjava.sql.SQLSyntaxErrorException Table 'techdb.goods_table' doesn't exist
と出てましたけどDB連携を初めからやり治りました。
補足情報(FW/ツールのバージョンなど)
JDK8Eclipse(Pleiades2018-9)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。