java+jsp+servlet+jdbc 学生登录注册系统

java+jsp+servlet+jdbc 学生登录注册系统

jsp

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	index page
</body>
</html>

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	${message }<br>
	<form action="${pageContext.request.contextPath }/loginServlet" method="post">
		学号:<input type="text" name = "num"><br>
		密码:<input type="password" name = "password"><br>
		<input type="submit" value="登录">
	</form>
	<a href="${pageContext.request.contextPath }/toRegisterServlet">注册</a>
</body>
</html>

register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="${pageContext.request.contextPath }/registerServlet" method="post" >
		学号:<input type="text" name = "num"><br>
		密码:<input type="password" name = "password"><br>
		姓名:<input type="text" name = "name"><br>
		年龄:<input type="text" name = "age"><br>
		成绩:<input type="text" name = "score"><br>
		<input type="submit" value="注册">
	</form>
	
</body>
</html>

DB

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` int(5) NOT NULL,
  `num` varchar(5) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  `name` varchar(20) DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  `score` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('1', '00001', '111', 'niba', '20', '98');

servlet

servlet

loginServlet.java
package com.own.servlet;

import java.io.IOException;
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 com.own.service.IStudentService;
import com.own.service.StudentServiceImpl;
import com.own.sms.beans.Student;

public class loginServlet extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.接收请求的参数
		String num = request.getParameter("num");
		String password = request.getParameter("password");
		HttpSession session = request.getSession();
		if(num==null || "".equals(num.trim())) {
			session.setAttribute("message","用户名错误");
			response.sendRedirect(request.getContextPath()+"/login.jsp");
			return;
		}
		if(password==null || "".equals(password.trim())) {
			session.setAttribute("message","密码错误");
			//这里要用重定向 防止有人恶意刷新
			response.sendRedirect(request.getContextPath()+"/login.jsp");
			//习惯性添加一个return 虽说没啥用 但是可以提示你 下边的代码不会执行
			return;
		}
		//2.创建service对象
		IStudentService service = new StudentServiceImpl();
		//3.调用service对象的checkStudent方法对用户进行验证
		Student student = service.checkUser(num,password);
		//4.验证未通过 则跳转到登录页面 让用户再次输入登录信息 此时页面需要给用户提示信息
		if(student == null) {
			session.setAttribute("message","用户名密码错误");
			response.sendRedirect(request.getContextPath()+"/login.jsp");
			return;
		}
		//5.验证通过 则跳转到系统主页index.jsp
		response.sendRedirect(request.getContextPath()+"/index.jsp");
	}

}
RegisterServlet.java
package com.own.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.own.service.IStudentService;
import com.own.service.StudentServiceImpl;
import com.own.sms.beans.Student;

/**
 * Servlet implementation class RegisterServlet
 */
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//1.获取表单参数
		String num = request.getParameter("num");
		String password = request.getParameter("password");
		String name = request.getParameter("name");
		String ageStr = request.getParameter("age");
		String scoreStr = request.getParameter("score");
		/*if(num ==null&& "".equals(num.trim())) {
			这里省去了好多东西 比如:判断账号 密码 姓名 年龄 分数是否为空什么的
			还有逻辑判断 年龄不能超过多少岁 
		}*/
		Integer age = Integer.valueOf(ageStr);
		//类型转换 age是int类型 获取时候只能获取字符串类型
		Double score = Double.valueOf(scoreStr);
		//2.创建student对象
		Student student = new Student(num,name,age,score);
		student.setPassword(password);
		
		//3.在创建service对象
		IStudentService service  = new StudentServiceImpl();
		//4.调用service对象的saveStudent方法 写入到db+
		Integer id =  service.saveStudent(student);
		//5.写入失败则跳转到注册页面 重新注册
		if(id==null) {
			response.sendRedirect(request.getContextPath()+"/register.jsp");
			return;
		}
		//6.写入成功跳转到登录页面
		response.sendRedirect(request.getContextPath()+"/login.jsp");
	}

}
ToRegisterServlet.java
package com.own.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ToRegisterServlet
 */
public class ToRegisterServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.sendRedirect(request.getContextPath()+"/register.jsp");
	}

}

service

接口 IStudentService
package com.own.service;

import com.own.sms.beans.Student;

public interface IStudentService {
	//对用户进行验证
	Student checkUser(String num, String password);
	//向DB中添加Student
	Integer saveStudent(Student student);

}
实现 IStudentServiceImpl
package com.own.service;

import com.own.dao.IStudentDao;
import com.own.dao.StudentDaoImpl;
import com.own.service.IStudentService;
import com.own.sms.beans.Student;

public class StudentServiceImpl implements IStudentService {
	private IStudentDao dao;
	public StudentServiceImpl() {
		dao = new StudentDaoImpl();
	}


	public Student checkUser(String num, String password) {
		// TODO Auto-generated method stub
		return dao.selectStudentLogin(num,password);
	}


	@Override
	public Integer saveStudent(Student student) {
		// TODO Auto-generated method stub
		return dao.insertStudent(student);
	}

}

dao

接口IStudentDao
package com.own.dao;

import com.own.sms.beans.Student;

public interface IStudentDao {

	Student selectStudentLogin(String num, String password);

	Integer insertStudent(Student student);

}

实现 IStudentDaoImpl
package com.own.dao;

import java.sql.*;

import com.own.sms.beans.Student;
import com.own.util.jdbcUtils;

public class StudentDaoImpl implements IStudentDao {
	private Connection conn;
	private Statement stmt;
	private PreparedStatement ps;
	private ResultSet rs;
	public Student selectStudentLogin(String num, String password) {
		Student student = null;
		try {
			conn=jdbcUtils.getConnection();
			String sql = "select * from student where num =? and password=?";
			ps=conn.prepareStatement(sql);
			ps.setString(1,num);
			ps.setString(2,password);
			rs = ps.executeQuery();
			if(rs.next()) {
				student = new Student();
				student.setId(rs.getInt("id"));
				student.setNum(rs.getString("num"));
				student.setPassword(rs.getString("password"));
				student.setName(rs.getString("name"));
				student.setAge(rs.getInt("age"));
				student.setScore(rs.getDouble("score"));
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			
			try {
				jdbcUtils.close(conn,ps,rs);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return student;
	}
	@Override
	public Integer insertStudent(Student student) {
		Integer id=null;
		try {
			conn = jdbcUtils.getConnection();
			String sql = "insert into student(num,password,name,age,score)values(?,?,?,?,?)";
			ps = conn.prepareStatement(sql);
			ps.setString(3,student.getNum());
			ps.setString(2,student.getPassword());
			ps.setString(1,student.getName());
			ps.setInt(4, student.getAge());
			ps.setDouble(5,student.getScore());
			ps.executeUpdate();
			sql = "select @@identity newid";
			ps = conn.prepareStatement(sql);
			rs=ps.executeQuery();
			if(rs.next()){
				id = rs.getInt("newid");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				jdbcUtils.close(conn, stmt, null);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return id;
	}
}

bean

student
package com.own.sms.beans;

import java.io.Serializable;

public class Student implements Serializable {
	private Integer id;		//与业务无关的主键
	private String password;	//登录密码
	private String name;	//学号
	private String num;
	private int age;
	private double score;
	public Student(String name, String num, int age, double score) {
		super();
		this.name = name;
		this.num = num;
		this.age = age;
		this.score = score;
	}
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getNum() {
		return num;
	}
	public void setNum(String num) {
		this.num = num;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getScore() {
		return score;
	}
	public void setScore(double score) {
		this.score = score;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", password=" + password + ", name=" + name + ", num=" + num + ", age=" + age
				+ ", score=" + score + "]";
	}
	
}

jdbc工具

package com.own.util;

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

public class jdbcUtils {
	//注册驱动
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	private static Connection conn;
	//获取connection对象
	//注意 工具类中一般不使用try catch 因为 当你出现错误时候你找不到哪里错了
	public static Connection getConnection() throws SQLException {
			String url="jdbc:mysql://localhost:3306/表名";
			String user="用户名";
			String password="密码";
			if(conn==null || conn.isClosed()) {
			conn=DriverManager.getConnection(url, user, password);
			}
			
		return conn;
	}
	//关闭资源
	public static void close(Connection conn,Statement stmt,ResultSet rs) throws SQLException {
			//如果rs不为空并且还没有被关闭
		if(rs!=null&& !rs.isClosed()) {
			rs.close();
		}
		if(stmt!=null && !stmt.isClosed()) {
			stmt.close();
		}
		if(conn!=null && !conn.isClosed()) {
			conn.close();
		}
	}
}

XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>30-stusms</display-name>
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>loginServlet</display-name>
    <servlet-name>loginServlet</servlet-name>
    <servlet-class>com.own.servlet.loginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>loginServlet</servlet-name>
    <url-pattern>/loginServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>ToRegisterServlet</display-name>
    <servlet-name>ToRegisterServlet</servlet-name>
    <servlet-class>com.own.servlet.ToRegisterServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ToRegisterServlet</servlet-name>
    <url-pattern>/toRegisterServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>RegisterServlet</display-name>
    <servlet-name>RegisterServlet</servlet-name>
    <servlet-class>com.own.servlet.RegisterServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RegisterServlet</servlet-name>
    <url-pattern>/registerServlet</url-pattern>
  </servlet-mapping>
</web-app>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值