计应143罗世芳
1.新建一个web项目
2.根据MVC创建四个包
(1)entity
(2)servlet
(3)tools
(4)DAO
3.在包下创建类
4. 写主页面和创建登录页面的代码
下面是我的程序,如下:
package entity;
public class User {
private String userID;
private String userName;
private String password;
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package DAO;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import entity.User;
import DBHelper.DBHelper;
public class UserDao {
public List getAlluser() {
try
{
String SQL="SELECT *FROM user";
ResultSet rs=DBHelper.getResultSet(SQL);
List users=new ArrayList();
while(rs.next()){
User u=new User();
u.setUserID(rs.getString("userID"));
u.setUserName(rs.getString("userName"));
u.setPassword(rs.getString("password"));
users.add(u);
}
return users;
}
catch(Exception ex){
ex.printStackTrace();
return null;}
}
}
package servlet;
import java.awt.List;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import DAO.UserDao;
public class UserServlet extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserDao dao=new UserDao();
java.util.List users=dao.getAlluser();
request.getSession().setAttribute("users", users);
response.sendRedirect("../user.jsp");
}
}
package DBHelper;
import java.io.Console;
import java.sql.*;
import java.util.Enumeration;
//import java.util.logging.*;
//import javax.swing.table.*;
/**
* SQL 基本操作
* 通过它,可以很轻松的使用 JDBC 来操纵数据库
* @author Null
*/
public class DBHelper
{
/**
* 驱动
*/
//public static String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
public static String driver = "com.mysql.jdbc.Driver";
/**
* 连接字符串
*/
//public static String url = "jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=st";
public static String url = "jdbc:mysql://localhost:3306/test";
/**
* 用户名
*/
public static String user = "root";
/**
* 密码
*/
public static String password = "root";
/**
* 不允许实例化该类
*/
private DBHelper()
{
}
/**
* 获取一个数据库连接
* 通过设置类的 driver / url / user / password 这四个静态变量来 设置数据库连接属性
* @return 数据库连接
*/
public static Connection getConnection()
{
try
{
//获取驱动
Class.forName(driver);
} catch (ClassNotFoundException ex)
{
//Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
}
try
{
return DriverManager.getConnection(url, user, password);
} catch (SQLException ex)
{
//Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
return null;
}
}
/**
* 获取一个 Statement
* 该 Statement 已经设置数据集 可以滚动,可以更新
* @return 如果获取失败将返回 null,调用时记得检查返回值
*/
public static Statement getStatement()
{
Connection conn = getConnection();
if (conn == null)
{
return null;
}
try
{
return conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
// 鐠佸墽鐤嗛弫鐗堝祦闂嗗棗褰叉禒銉︾泊閸旓拷閸欘垯浜掗弴瀛樻煀
} catch (SQLException ex)
{
//Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
close(conn);
}
return null;
}
/**
* 获取一个 Statement
* 该 Statement 已经设置数据集 可以滚动,可以更新
* @param conn 数据库连接
* @return 如果获取失败将返回 null,调用时记得检查返回值
*/
public static Statement getStatement(Connection conn)
{
if (conn == null)
{
return null;
}
try
{
return conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
// 设置数据集可以滚动,可以更新
} catch (SQLException ex)
{
//Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
return null;
}
}
/**
* 获取一个带参数的 PreparedStatement
* 该 PreparedStatement 已经设置数据集 可以滚动,可以更新
* @param cmdText 需要 ? 参数的 SQL 语句
* @param cmdParams SQL 语句的参数表
* @return 如果获取失败将返回 null,调用时记得检查返回值
*/
public static PreparedStatement getPreparedStatement(String cmdText, Object[] cmdParams)
{
Connection conn = getConnection();
if (conn == null)
{
return null;
}
PreparedStatement pstmt = null;
try
{
pstmt = conn.prepareStatement(cmdText, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
int i = 1;
for (Object item : cmdParams) //java foreach遍历集合,要求集合类实现Enumeration接口
{
pstmt.setObject(i, item);
i++;
}
} catch (SQLException e)
{
e.printStackTrace();
close(conn);
}
return pstmt;
}
/**
* 获取一个带参数的 PreparedStatement
* 该 PreparedStatement 已经设置数据集 可以滚动,可以更新
* @param conn 数据库连接
* @param cmdText 需要 ? 参数的 SQL 语句
* @param cmdParams SQL 语句的参数表
* @return 如果获取失败将返回 null,调用时记得检查返回值
*/
public static PreparedStatement getPreparedStatement(Connection conn, String cmdText, Object[] cmdParams)
{
if (conn == null)
{
return null;
}
PreparedStatement pstmt = null;
try
{
pstmt = conn.prepareStatement(cmdText, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
int i = 1;
for (Object item : cmdParams)
{
pstmt.setObject(i, item);
i++;
}
} catch (SQLException ex)
{
System.out.println(ex.getMessage());
//ex.printStackTrace();
close(pstmt);
}
return pstmt;
}
/**
* 执行 SQL 语句,返回结果为整型
* 主要用于执行非查询语句
* @param cmdText SQL 语句
* @return 非负数:正常执行; -1:执行错误; -2:连接错误
*/
public static int ExecSql(String cmdText)
{
Statement stmt = getStatement();
if (stmt == null)
{
return -2;
}
int i;
try
{
i = stmt.executeUpdate(cmdText);
} catch (SQLException ex)
{
//Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null,ex);
System.out.println(ex.getMessage());
i = -1;
}
closeConnection(stmt);
return i;
}
/**
* 执行 SQL 语句,返回结果为整型
* 主要用于执行非查询语句
* @param cmdText SQL 语句
* @return 非负数:正常执行; -1:执行错误; -2:连接错误
*/
public static int ExecSql(Connection conn, String cmdText)
{
Statement stmt = getStatement(conn);
if (stmt == null)
{
return -2;
}
int i;
try
{
i = stmt.executeUpdate(cmdText);
} catch (SQLException ex)
{
//Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
i = -1;
}
close(stmt);
return i;
}
/**
* 执行 SQL 语句,返回结果为整型
* 主要用于执行非查询语句
* @param cmdText 需要 ? 参数的 SQL 语句
* @param cmdParams SQL 语句的参数表
* @return 非负数:正常执行; -1:执行错误; -2:连接错误
*/
public static int ExecSql(String cmdText, Object[] cmdParams)
{
PreparedStatement pstmt = getPreparedStatement(cmdText, cmdParams);
if (pstmt == null)
{
return -2;
}
int i;
try
{
i = pstmt.executeUpdate();
} catch (SQLException ex)
{
//Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
i = -1;
}
closeConnection(pstmt);
return i;
}
/**
* 执行 SQL 语句,返回结果为整型
* 主要用于执行非查询语句
* @param conn 数据库连接
* @param cmdText 需要 ? 参数的 SQL 语句
* @param cmdParams SQL 语句的参数表
* @return 非负数:正常执行; -1:执行错误; -2:连接错误
*/
public static int ExecSql(Connection conn, String cmdText, Object[] cmdParams)
{
PreparedStatement pstmt = getPreparedStatement(conn, cmdText, cmdParams);
if (pstmt == null)
{
return -2;
}
int i;
try
{
i = pstmt.executeUpdate();
} catch (SQLException ex)
{
//Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
i = -1;
}
close(pstmt);
return i;
}
/**
* 返回结果集的第一行的一列的值,其他忽略
* @param cmdText SQL 语句
* @return
*/
public static Object ExecScalar(String cmdText)
{
ResultSet rs = getResultSet(cmdText);
Object obj = getScalar(rs);
closeConnection(rs);
return obj;
}
/**
* 返回结果集的第一行的一列的值,其他忽略
* @param conn 数据库连接
* @param cmdText SQL 语句
* @return
*/
public static Object ExecScalar(Connection conn, String cmdText)
{
ResultSet rs = getResultSet(conn, cmdText);
Object obj = getScalar(rs);
closeEx(rs);
return obj;
}
/**
* 返回结果集的第一行的一列的值,其他忽略
* @param cmdText 需要 ? 参数的 SQL 语句
* @param cmdParams SQL 语句的参数表
* @return
*/
public static Object ExecScalar(String cmdText, Object[] cmdParams)
{
ResultSet rs = getResultSet(cmdText, cmdParams);
Object obj = getScalar(rs);
closeConnection(rs);
return obj;
}
/**
* 返回结果集的第一行的一列的值,其他忽略
* @param conn 数据库连接
* @param cmdText 需要 ? 参数的 SQL 语句
* @param cmdParams SQL 语句的参数表
* @return
*/
public static Object ExecScalar(Connection conn, String cmdText, Object[] cmdParams)
{
ResultSet rs = getResultSet(conn, cmdText, cmdParams);
Object obj = getScalar(rs);
closeEx(rs);
return obj;
}
/**
* 返回一个 ResultSet
* @param cmdText SQL 语句
* @return
*/
public static ResultSet getResultSet(String cmdText)
{
Statement stmt = getStatement();
if (stmt == null)
{
return null;
}
try
{
return stmt.executeQuery(cmdText);
} catch (SQLException ex)
{
//Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
closeConnection(stmt);
}
return null;
}
/**
* 返回一个 ResultSet
* @param conn
* @param cmdText SQL 语句
* @return
*/
public static ResultSet getResultSet(Connection conn, String cmdText)
{
Statement stmt = getStatement(conn);
if (stmt == null)
{
return null;
}
try
{
return stmt.executeQuery(cmdText);
} catch (SQLException ex)
{
//Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
close(stmt);
}
return null;
}
/**
* 返回一个 ResultSet
* @param cmdText 需要 ? 参数的 SQL 语句
* @param cmdParams SQL 语句的参数表
* @return
*/
public static ResultSet getResultSet(String cmdText, Object[] cmdParams)
{
PreparedStatement pstmt = getPreparedStatement(cmdText, cmdParams);
if (pstmt == null)
{
return null;
}
try
{
return pstmt.executeQuery();
} catch (SQLException ex)
{
//Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
closeConnection(pstmt);
}
return null;
}
/**
* 返回一个 ResultSet
* @param conn 数据库连接
* @param cmdText 需要 ? 参数的 SQL 语句
* @param cmdParams SQL 语句的参数表
* @return
*/
public static ResultSet getResultSet(Connection conn, String cmdText, Object[] cmdParams)
{
PreparedStatement pstmt = getPreparedStatement(conn, cmdText, cmdParams);
if (pstmt == null)
{
return null;
}
try
{
return pstmt.executeQuery();
} catch (SQLException ex)
{
//Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
close(pstmt);
}
return null;
}
public static Object getScalar(ResultSet rs)
{
if (rs == null)
{
return null;
}
Object obj = null;
try
{
if (rs.next())
{
obj = rs.getObject(1);
}
} catch (SQLException ex)
{
//Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
}
return obj;
}
private static void close(Object obj)
{
if (obj == null)
{
return;
}
try
{
if (obj instanceof Statement)
{
((Statement) obj).close();
} else if (obj instanceof PreparedStatement)
{
((PreparedStatement) obj).close();
} else if (obj instanceof ResultSet)
{
((ResultSet) obj).close();
} else if (obj instanceof Connection)
{
((Connection) obj).close();
}
} catch (SQLException ex)
{
//Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
}
}
private static void closeEx(Object obj)
{
if (obj == null)
{
return;
}
try
{
if (obj instanceof Statement)
{
((Statement) obj).close();
} else if (obj instanceof PreparedStatement)
{
((PreparedStatement) obj).close();
} else if (obj instanceof ResultSet)
{
((ResultSet) obj).getStatement().close();
} else if (obj instanceof Connection)
{
((Connection) obj).close();
}
} catch (SQLException ex)
{
//Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
}
}
private static void closeConnection(Object obj)
{
if (obj == null)
{
return;
}
try
{
if (obj instanceof Statement)
{
((Statement) obj).getConnection().close();
} else if (obj instanceof PreparedStatement)
{
((PreparedStatement) obj).getConnection().close();
} else if (obj instanceof ResultSet)
{
((ResultSet) obj).getStatement().getConnection().close();
} else if (obj instanceof Connection)
{
((Connection) obj).close();
}
} catch (SQLException ex)
{
//Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex.getMessage());
}
}
}
<%@page import="org.apache.taglibs.standard.tag.common.xml.ForEachTag"%>
<%@ page language="java" import="java.util.*,entity.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'user.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
List<User> users=(List<User>)session.getAttribute("users");
out.print("<table border=1>");
out.print("<tr><td>用户ID</td><td>用户名</td><td>密码</td></tr>");
for(User u:users){
out.print("<tr>");
out.print("<td>"+u.getUserID()+"</td>");
out.print("<td>"+u.getUserName()+"</td>");
out.print("<td>"+u.getPassword()+"</td>");
out.print("<tr>");
}
out.print("</table>");
%>
</body>
</html>