eclipse配置Servlet連線Mysql要注意的幾個地方
阿新 • • 發佈:2018-11-25
用Servlet即把jdbc那套放到繼承於HttpServlet的派生類之內,那段程式碼很簡單
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("Unicode"); PrintWriter out=response.getWriter(); String name=request.getParameter("username"); String passwd=request.getParameter("passwd"); try { Class.forName("com.mysql.jdbc.Driver"); // Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/stu", "root", "root");//Statement stmt=conn.createStatement(); //ResultSet rs=stmt.executeQuery(sql); //查詢 java.sql.PreparedStatement pstmt=conn.prepareStatement("select * from tb_user where name=? and password=?"); pstmt.setString(1, name); pstmt.setString(2, passwd); //System.out.println();ResultSet rs=pstmt.executeQuery(); rs.beforeFirst(); if(rs.next()) { out.println(rs.getString(1)+":"+rs.getString(2)); } else{ out.println("不存在該使用者!"); } rs.close(); conn.close(); } catch (ClassNotFoundException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
但注意要把jdbc放到tomcat目錄中的lib中,不然報的那種錯誤,確實有點讓人看不懂
還有編碼的格式需要注意一下,有時候Mysql資料表中的編碼,會與介面的編碼格式不一致,比如我這是Unicode的
response.setCharacterEncoding("Unicode");
把Web.xml的配置檔案也放上吧
<servlet> <servlet-name>Login</servlet-name> <servlet-class>com.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>/ServerCoding1/aaa</url-pattern> </servlet-mapping>
呼叫類似
<a href="aaa">跳轉<a/>
或
<form action="ServerCoding1/aaa" method="post"> <input type="submit" value="跳轉"> </form>