用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>