Servelt的注册和登录以及跳转功能

Servelt的注册和登录以及跳转功能

1:创建一个项目先把sqljdbc4.jar导入并且部署

在这里插入图片描述

2:创建一个项目并创建包进行分层架构并创建需要的类

在这里插入图片描述

3:然后完成DBUtil工具类的代码

package top.xinsir.util;

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

public class DBUtil {
	public static Connection getConn() {
		Connection conn = null;
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			conn = DriverManager.getConnection(
					"jdbc:sqlserver://localhost:1433;databaseName=MyDB", "sa",
					"1");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	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:然后再model里面创建用户表模型

package top.xinsir.model;

public class Users {
	private Integer id;
	private String name;
	private String userName;
	private Integer age;
	private String pwd;

	public Integer getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getUserName() {
		return userName;
	}

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

	public Integer getAge() {
		return age;
	}

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

	public String getPwd() {
		return pwd;
	}

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

	public Users(Integer id, String name, String userName, Integer age,
			String pwd) {
		super();
		this.id = id;
		this.name = name;
		this.userName = userName;
		this.age = age;
		this.pwd = pwd;
	}

	public Users(String name, String userName, Integer age, String pwd) {
		super();
		this.name = name;
		this.userName = userName;
		this.age = age;
		this.pwd = pwd;
	}

	public Users() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public String toString() {
	// 输出查询时页面的美化效果
		return "<tr>"
		+"<td class='left'>"+id+"</td>"
		+"<td class='left'>"+name+"</td>"
		+"<td class='left'>"+age+"</td>"
		+"<td class='left'>"+userName+"</td>"
		+"<td class='left'>"+pwd+"</td>"
	+"</tr>";
	}
}

5:然后在service里面创建三个Servelt类,分别实现登录、注册、查询

(1)LoginServelt登录功能Java代码:

package top.xinsir.service;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

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

import top.xinsir.util.DBUtil;

public class LoginServelt 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 {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		// 获取输入的用户名和密码
		String userName = request.getParameter("userName");
		String pwd = request.getParameter("pwd");

		// 获取驱动
		Connection conn = DBUtil.getConn();
		// 准备sql语句
		String sql = "SELECT * FROM users WHERE user_name=? AND pwd=?";

		boolean isTrue = false;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			// 与数据库交互
			ps = conn.prepareStatement(sql);
			ps.setString(1, userName);
			ps.setString(2, pwd);

			// 执行sql语句并存储到ResultSet集合中
			rs = ps.executeQuery();

			// 判断数据库中是否有输入的账号密码
			if (rs.next()) {
				isTrue = true;
			} else {
				isTrue = false;
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 关闭资源
		DBUtil.close(conn, ps, rs);
		
		// 处理响应
		if (isTrue) {
			response.sendRedirect("select");
		} else {
			response.sendRedirect("login.jsp");
		}
	}

}
创建一个login.jsp页面,来完成登录的页面效果,代码:
<%@ 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">
		.left{
			width:100px;
			text-align: center;
		}
		.right{
			width: 200px;
		}
		table{
			margin: 0 auto;
		}
		th{
			font-size: 30px;
			color: red;
		}
		td{
			height: 50px;
		}
		.login{
			width: 80px;
			height: 30px;
		}
		.class{
			text-align: center;
		}
		a{
			text-decoration: none;
			display: block;
			color: white;
			width: 160;
			height: 30;
			background-color: red;
			text-align: center;
			line-height: 30px;
			margin: 0 auto;
		}
		input{
			margin-left: 5px;
		}
	</style>
	</head>

	<body>
		<form action="login" method="post">

			<table border="1" cellspacing="0" cellpadding="0">
				<tr>
					<th colspan="2">登录页面</th>
				</tr>
				<tr>
					<td class="left">用户名:</td>
					<td class="right"><input type="text" name="userName" /></td>
				</tr>
				<tr>
					<td class="left">&nbsp;&nbsp;码:</td>
					<td class="right"><input type="password" name="pwd" /></td>
				</tr>
				<tr class="class">
					<td colspan="2" class="submit"><input class="login" type="submit" value="登录" /></td>
				</tr>
			</table>
		</form>
		<a href="reg.jsp">没有账号?立即注册!</a>
	</body>

</html>

(2)RegServelt注册功能Java代码:

package top.xinsir.service;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

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

import top.xinsir.util.DBUtil;

public class RegServelt 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 {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		// 获取输入的姓名 年龄 用户名和密码
		String name = request.getParameter("name");
		Integer age = Integer.parseInt(request.getParameter("age"));
		String userName = request.getParameter("userName");
		String pwd = request.getParameter("pwd");

		boolean isTrue = false;//判断是否正确

		try {
			Connection conn = DBUtil.getConn();

			// 准备一个sql语句
			String sql = "INSERT INTO users VALUES(?,?,?,?)";

			// 用PreparedStatement交互数据库
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, name);
			ps.setString(2, userName);
			ps.setInt(3, age);
			ps.setString(4, pwd);

			// 用count显示影响的行数
			int count = ps.executeUpdate();

			// 展示页面
			if (count > 0) {
				isTrue = true;
			} else {
				isTrue = false;
			}

			// 关闭资源
			DBUtil.close(conn, ps, null);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 处理响应
		if (isTrue) {
			response.sendRedirect("login.jsp");
		} else {
			response.sendRedirect("reg.jsp");
		}
	}

}
创建一个reg.jsp页面,来完成注册的页面效果,代码:
<%@ 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">
		.left{
			width:100px;
			text-align: center;
		}
		.right{
			width: 200px;
		}
		table{
			margin: 0 auto;
		}
		th{
			font-size: 30px;
			color: red;
		}
		td{
			height: 50px;
		}
		.login{
			width: 80px;
			height: 30px;
		}
		.class{
			text-align: center;
		}
		a{
			text-decoration: none;
			display: block;
			color: white;
			width: 160;
			height: 30;
			background-color: red;
			text-align: center;
			line-height: 30px;
			margin: 0 auto;
		}
		input{
			margin-left: 5px;
		}
	</style>
	</head>

	<body>
		<form action="reg" method="post">

			<table border="1" cellspacing="0" cellpadding="0">
				<tr>
					<th colspan="2">注册页面</th>
				</tr>
				<tr>
					<td class="left">姓名:</td>
					<td class="right"><input type="text" name="name" /></td>
				</tr>
				<tr>
					<td class="left">年龄:</td>
					<td class="right"><input type="number" name="age" /></td>
				</tr>
				<tr>
					<td class="left">用户名:</td>
					<td class="right"><input type="text" name="userName" /></td>
				</tr>
				<tr>
					<td class="left">&nbsp;&nbsp;码:</td>
					<td class="right"><input type="password" name="pwd" /></td>
				</tr>
				<tr>
					<td class="left">确认密码</td>
					<td class="right"><input type="password" name="pwd" /></td>
				</tr>
				<tr class="class">
					<td colspan="2" class="submit"><input class="login" type="submit" value="注册" /></td>
				</tr>
			</table>
		</form>
		<a href="login.jsp">已有账号?立即登录!</a>
	</body>

</html>

(3)SelectServelt登录成功之后的Java代码:

package top.xinsir.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

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

import top.xinsir.model.Users;
import top.xinsir.util.DBUtil;

public class SelectServelt extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		try {
			// 加载驱动
			Connection conn = DBUtil.getConn();

			// 准备sql语句
			String sql = "SELECT * FROM users";

			// 用PreparedStatement和数据库交互
			PreparedStatement ps = conn.prepareStatement(sql);

			// 用ResultSet存储查询的值
			ResultSet rs = ps.executeQuery();

			// 展示页面
			ArrayList<Users> usersList = new ArrayList<Users>();
			while (rs.next()) {
				Users users = new Users();
				users.setId(rs.getInt("id"));
				users.setName(rs.getString("name"));
				users.setUserName(rs.getString("user_name"));
				users.setPwd(rs.getString("pwd"));
				users.setAge(rs.getInt("age"));
				usersList.add(users);
			}

			// 关闭资源
			DBUtil.close(conn, ps, rs);

			// 响应
			resp.setContentType("text/html");
			PrintWriter out = resp.getWriter();
			out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
			out.println("<HTML>");
			out.println("  <HEAD><TITLE>A Servlet</TITLE>");
			out.println("<style type=\"text/css\">"
					+ ".left{width:100px;text-align: center;}"
					+ ".right{width: 200px;}" + "table{margin: 0 auto;}"
					+ "th{font-size: 30px;color: red;}" + "td{height: 50px;}"
					+ "h1{text-align: center;}</style>");
			out.println("</HEAD>");
			out.println("  <BODY>");
			out.println("<h1>登录成功!!!</h1>");
			out.println("<h1>查询所有用户信息</h1>");
			out.println("<table border=\"1\" cellspacing=\"0\" cellpadding=\"0\">"
					+ "<tr>"
					+ "	<td class=\"left\">id</td>"
					+ " <td class=\"left\">姓名</td>"
					+ "	<td class=\"left\">年龄</td>"
					+ "	<td class=\"left\">用户名</td>"
					+ "	<td class=\"left\">密码</td>" + "</tr>");
			for (Users users : usersList) {
				out.println(users.toString());
			}
			out.println("</table>");
			out.println("  </BODY>");
			out.println("</HTML>");
			out.flush();
			out.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
创建一个select.jsp页面,来实现登录之后与SelectServelt代码交互,从而在网页上显示用户表的内容:
<%@ 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">
	-->
  </head>
  
  <body>
   <form action="select" method="post">
   </form>
  </body>
</html>

(4)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>top.xinsir.service.LoginServelt</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>top.xinsir.service.RegServelt</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>select</servlet-name>
    <servlet-class>top.xinsir.service.SelectServelt</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>
  <servlet-mapping>
    <servlet-name>select</servlet-name>
    <url-pattern>/select</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
</web-app>

6:写完之后部署到Tomcat中并运行,打开浏览器预览效果如下:

(1)注册页面

在这里插入图片描述

(1)输入注册的信息之后

在这里插入图片描述

(2)点击注册按钮跳转到登录页面

在这里插入图片描述

(2)登录页面:

在这里插入图片描述

(1)输入用户名密码之后点击登录

在这里插入图片描述

(2)点击登录之后

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值