网页登录和注册页面以及session的简单运用

6 篇文章 0 订阅

DBUtil工具类

package org.simple.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {

	// 1:静态代码段
	static {
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		} catch (ClassNotFoundException e) {

			e.printStackTrace();
		}
	}

	// 2:连接数据库
	public static Connection getConn() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(
					"jdbc:sqlserver://localhost:1433;databaseName=MyDB", "sa",
					"1");
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return conn;

	}

	// 3:关闭资源
	public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
		try {
			if (conn != null)
				conn.close();
			if (ps != null)
				ps.close();
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// 4:更新操作
	public static int update(String sql, Object objs[]) {
		PreparedStatement ps = null;
		int count = 0;
		Connection conn = getConn();
		try {
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < objs.length; i++) {
				ps.setObject(i + 1, objs[i]);
			}
			count = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(conn, ps, null);
		}
		return count;

	}

}

User用户类

package org.simple.model;

public class User {
	private int id;
	private String userName;
	private String pwd;
	private String sex;
	private int age;
	private String tel;
	private String address;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getTel() {
		return tel;
	}

	public void setTel(String tel) {
		this.tel = tel;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public User(int id, String userName, String pwd, String sex, int age,
			String tel, String address) {
		super();
		this.id = id;
		this.userName = userName;
		this.pwd = pwd;
		this.sex = sex;
		this.age = age;
		this.tel = tel;
		this.address = address;
	}

	public User() {
		super();
	}

	@Override
	public String toString() {
		return "User [address=" + address + ", age=" + age + ", id=" + id
				+ ", pwd=" + pwd + ", sex=" + sex + ", tel=" + tel
				+ ", userName=" + userName + "]";
	}

}

SelectManager查询操作

package org.simple.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import org.simple.model.User;

public class SelectManager {

	public static ArrayList<User> getUser(String userName, String pwd) {
		PreparedStatement ps = null;
		ResultSet rs = null;
		ArrayList<User> users = new ArrayList<User>();
		Connection conn = DBUtil.getConn();
		String sql = "select * from users where user_name=? and pwd=?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, userName);
			ps.setString(2, pwd);
			rs = ps.executeQuery();
			while (rs.next()) {
				User user = new User();
				user.setId(rs.getInt("id"));
				user.setUserName(rs.getString("user_name"));
				user.setPwd(rs.getString("pwd"));
				user.setSex(rs.getString("sex"));
				user.setAge(rs.getInt("age"));
				user.setTel(rs.getString("tel"));
				user.setAddress(rs.getString("address"));
				users.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return users;

	}

	// 获取所有用户信息
	public static ArrayList<User> UserManager() {
		PreparedStatement ps = null;
		ResultSet rs = null;
		ArrayList<User> users = new ArrayList<User>();
		Connection conn = DBUtil.getConn();
		String sql = "select * from users";
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				User user = new User();
				user.setId(rs.getInt("id"));
				user.setUserName(rs.getString("user_name"));
				user.setPwd(rs.getString("pwd"));
				user.setSex(rs.getString("sex"));
				user.setAge(rs.getInt("age"));
				user.setTel(rs.getString("tel"));
				user.setAddress(rs.getString("address"));
				users.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return users;

	}

}

login登录页面

<%@ page language="java" import="java.util.*" 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 'index.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">
	-->
		<style type="text/css">
table {
	margin: 0 auto;
}

.login {
	margin: 0 auto;
}

a {
	text-decoration: none;
}
</style>
	</head>

	<body>
		<form action="login" method="post">
			<table>
				<tr>
					<td>
						用户名:
					</td>
					<td>
						<input type="text" name="userName" />
					</td>
				</tr>
				<tr>
					<td>
						密码:
					</td>
					<td>
						<input type="password" name="pwd" />
					</td>
				</tr>
				<tr>
					<td colspan="2">
						<input type="submit" value="登录" />
						<a href="reg.jsp"> <input type="button" value="注册" /> </a>
					</td>
				</tr>
			</table>
		</form>
	</body>
</html>

web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>login</servlet-name>
    <servlet-class>org.simple.test.LoginServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>reg</servlet-name>
    <servlet-class>org.simple.test.RegServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>login</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>reg</servlet-name>
    <url-pattern>/reg</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

LoginServlet页面

package org.simple.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.simple.model.User;
import org.simple.util.SelectManager;

public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1:设置编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html");

		// :2:获取参数
		String userName = request.getParameter("userName");
		String pwd = request.getParameter("pwd");

		// 登录代码
		ArrayList<User> users = SelectManager.getUser(userName, pwd);

		HttpSession session = request.getSession();

		if (users != null) {

			// 判断是否登录成功如果users不是空值0注册成功重定向到用户列表页面
			users = SelectManager.UserManager();

			// 通过session来存储用户信息
			session.setAttribute("users", users);
			response.sendRedirect("userList.jsp");
		} else
			// 登录失败重定向到登录页面
			response.sendRedirect("login.jsp");
	}

}

reg注册页面

<%@ page language="java" import="java.util.*" 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 'reg.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">
	-->
		<style type="text/css">
table {
	margin: 0 auto;
}

.login {
	margin: 0 auto;
}

a {
	text-decoration: none;
}
</style>
	</head>

	<body>
		<form action="reg" method="post">
			<table>
				<tr>
					<td>
						用户名:
					</td>
					<td>
						<input type="text" name="userName" />
					</td>
				</tr>
				<tr>
					<td>
						密码:
					</td>
					<td>
						<input type="password" name="pwd" />
					</td>
				</tr>
				<tr>
					<td>
						性别:
					</td>
					<td>
						<input type="text" name="sex" />
					</td>
				</tr>
				<tr>
					<td>
						年龄:
					</td>
					<td>
						<input type="text" name="age" />
					</td>
				</tr>
				<tr>
					<td>
						电话:
					</td>
					<td>
						<input type="text" name="tel" />
					</td>
				</tr>
				<tr>
					<td>
						地址:
					</td>
					<td>
						<input type="text" name="address" />
					</td>
				</tr>
				<tr>
					<td colspan="2">
						<input type="submit" value="注册" />
						<a href="login.jsp"> <input type="button" value="登录" /> </a>
					</td>
				</tr>
			</table>
		</form>
	</body>
</html>

RegServlet页面

package org.simple.test;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.simple.model.User;
import org.simple.util.DBUtil;
import org.simple.util.SelectManager;

public class RegServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1:设置编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html");

		// :2:获取参数
		String userName = request.getParameter("userName");
		String pwd = request.getParameter("pwd");
		String sex = request.getParameter("sex");
		String ageStr = request.getParameter("age");
		Integer age = Integer.parseInt(ageStr);
		String tel = request.getParameter("tel");
		String address = request.getParameter("address");

		// 注册代码
		String sql = "insert into users values(?,?,?,?,?,?)";
		Object objs[] = { userName, pwd, sex, age, tel, address };
		int count = DBUtil.update(sql, objs);

		// 3:响应
		if (count > 0) {
			// 判断是否注册成功如果count>0注册成功重定向到登录页面
			response.sendRedirect("login.jsp");
		} else
			// 注册失败重定向到注册页面
			response.sendRedirect("reg.jsp");
	}

}

userList用户列表页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="org.simple.model.User"%>
<%
	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 'userList.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>
		<table>
			<thead>
				<tr>
					<th>
						编号
					</th>
					<th>
						用户名
					</th>
					<th>
						密码
					</th>
					<th>
						性别
					</th>
					<th>
						年龄
					</th>
					<th>
						电话
					</th>
					<th>
						地址
					</th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<%
						ArrayList<User> users = (ArrayList<User>) session
								.getAttribute("users");
						if (users == null) {
							response.sendRedirect("login.jsp");
						} else
							//遍历users
							for (User user : users) {
					%>
					<td><%=user.getId()%></td>
					<td><%=user.getUserName()%></td>
					<td><%=user.getPwd()%></td>
					<td><%=user.getSex()%></td>
					<td><%=user.getAge()%></td>
					<td><%=user.getTel()%></td>
					<td><%=user.getAddress()%></td>
				</tr>
				<%
					}
				%>

			</tbody>
		</table>
	</body>
</html>

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值