简单Web界面开发(数据库)
(1)首先配置好eclipse 和 SQL server 2016 的环境,下载sqljdbc4.jar。(我的eclipse是eclipse Neon )
(2)创建新的数据库
(3)创建java project ,测试是否可以成功连接数据库
package pkg; import java.sql.*; public class Main { public static void main(String [] args) { String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver"; String dbURL="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=哈哈"; String userName="sa"; String userPwd="123456"; try { Class.forName(driverName); System.out.println("加载驱动成功!"); }catch(Exception e){ e.printStackTrace(); System.out.println("加载驱动失败!"); } try{ Connection dbConn=DriverManager.getConnection(dbURL,userName,userPwd); System.out.println("连接数据库成功!"); }catch(Exception e) { e.printStackTrace(); System.out.print("SQL Server连接失败!"); } } }
(4)测试成功后,创建Web project ,在WebContent 新建 JSP File 的登陆界面和连接数据库。
(5)登陆界面NewFile.jsp 中编辑代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>登录界面</title> </head> <body > <center> <h2>登录界面</h2> <form action="check.jsp" method="post"> 用户:<input type="text" name = "username"><br> 密码:<input type="password" name="password"><br> <input type="submit" value="提交"> </form> </center> </body> </html>
(6)连接数据库check.jsp,编辑代码如下
<%@ page language="java" import="java.sql.*" import="java.util.*" contentType="text/html;; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录</title> </head> <body> <% String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver"; String dbURL="jdbc:sqlserver://localhost:1433;DatabaseName=哈哈"; String userName="sa"; String userPwd="123456"; Class.forName(driverName); Connection dbConn=DriverManager.getConnection(dbURL,userName,userPwd); String sql = "select * from userinfo where [user]=? and [pwd]=?"; PreparedStatement pstmt = dbConn.prepareStatement(sql); request.setCharacterEncoding("UTF-8"); String us = request.getParameter("username"); String pass = request.getParameter("password"); pstmt.setString(1, us); pstmt.setString(2, pass); ResultSet rs = pstmt.executeQuery(); if(rs.next()) { %><center><h1>登陆成功!</h1></center><% } else { %><center><h1>登陆失败!</h1></center><% } %> </body> <ml>
注:1.<% %> 可以输入 java 语言的代码
2."select * from userinfo where [user]=? and [pwd]=?";格式是 "select * from 数据库表的名称 where [第一列名]=? and [第二个列名]=?";
3.pstmt.setString(1, us);
pstmt.setString(2, pass);
其中 1 指第一个问号,2指第二个问号。
(7)在登陆界面中,在action后输入check.jsp。
(8)将下载好的sqljdbc4.jar添加到libz中,如图
(9)成功后如下: