• Jsp、Servlet、jdbc 完成简单登录注册


    基于MVC模式开发JAVA WEB,实现简单登录注册,在以后会不断优化

    开发环境:windows 7,jdk1.7

    开发工具:Eclipse,tomcat7,MySQL server 5.7

    依赖包:

    项目结构

    登录页面login.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=UTF-8">
    <title>用户登陆</title>
    </head>
    <body>
    <form action="login" method="post">
    用户账号<input type="text" name="userName"><br>
    用户密码<input type="password" name="passWord">
    <input type="submit" value="登录">
    <a href="register.jsp">注册</a>
    </form>
    </body>
    </html>

    注册页面register.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=UTF-8">
    <title>用户注册</title>
    </head>
    <body>
    <form action="register" method="post">
    用户账号<input type="text" name="userName"><br>
    用户密码<input type="password" name="passWord">
    <input type="submit" value="注册">
    <a href="login.jsp">返回</a>
    </form>
    </body>
    </html>

    登录进入管理页面manager.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=UTF-8">
    <title>管理界面</title>
    </head>
    <body>
    管理界面......
    </body>
    </html>

    web.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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <display-name>day_22</display-name>
    <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>login.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
    <servlet-name>login</servlet-name>
    <servlet-class>com.ants.service.LoginService</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>login</servlet-name>
    <url-pattern>/login</url-pattern>
    </servlet-mapping>

    <servlet>
    <servlet-name>register</servlet-name>
    <servlet-class>com.ants.service.RegisterService</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>register</servlet-name>
    <url-pattern>/register</url-pattern>
    </servlet-mapping>

    </web-app>

    DBUtil.java

    package com.ants.util;

    import java.sql.Connection;
    import java.sql.ResultSet;

    import java.sql.Statement;

    import org.apache.commons.dbcp.BasicDataSource;

    public class DBUtil {
    private static BasicDataSource dataSource;

    static{
    //数据库连接池
    dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/test_4");
    dataSource.setUsername("root");
    dataSource.setPassword("123456");
    //设置连接池的初始大小
    dataSource.setInitialSize(5);
    //设置连接池的最大值
    dataSource.setMaxActive(20);
    //设置最大的空闲时间,60秒之后自动回收空闲的数据库连接
    dataSource.setMaxIdle(60);
    //maxWait代表当connection用尽以后多久进行回收丢失连接
    dataSource.setMaxWait(900);

    }
    //获取数据库连接
    public static Connection getConnection() throws Exception{
    return dataSource.getConnection();
    }

    public static void releseDataSource() throws Exception{
    //释放数据库连接池
    if(dataSource!=null){
    dataSource.close();
    }
    }
    //关闭以后释放数据库资源
    public static void closeResource(Connection connection,Statement statement,ResultSet resultSet) throws Exception{
    if(connection!=null){
    connection.close();
    }if(statement!=null){
    statement.close();
    }if(resultSet!=null){
    resultSet.close();
    }
    }
    }

    UserDAO.java

    package com.ants.dao;

    import java.sql.Connection;

    import java.sql.PreparedStatement;

    import java.sql.ResultSet;
    import java.util.ArrayList;
    import java.util.List;

    import com.ants.entity.User;
    import com.ants.util.DBUtil;

    public class UserDao {
    public void save(User user){
    Connection connection = null;
    PreparedStatement statement=null;
    try {
    connection = DBUtil.getConnection();
    //准备语句
    String sql = "insert into tb_user(username,password) VALUES(?,?)";
    statement=connection.prepareStatement(sql);
    //绑定数据
    statement.setString(1, user.getUsername());
    statement.setString(2,user.getPassword());
    //执行语句
    statement.execute();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    finally{
    try {
    DBUtil.closeResource(connection, statement, null);
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }

    public void deleteUser(User user){
    Connection connection = null;
    PreparedStatement statement=null;
    try {
    connection = DBUtil.getConnection();
    //准备语句
    String sql = "DELETE FROM tb_user where id=?";
    statement=connection.prepareStatement(sql);
    //4.绑定数据,索引是从1开始
    //这是删除的绑定
    statement.setInt(1, user.getId());
    //5.执行语句
    statement.execute();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    finally{
    try {
    DBUtil.closeResource(connection, statement, null);
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }

    public void updateUser(User user){
    Connection connection = null;
    PreparedStatement statement=null;
    try {
    connection = DBUtil.getConnection();
    //准备语句
    String sql = "update tb_user SET `username`=? where id=?";
    statement=connection.prepareStatement(sql);
    //4.绑定数据,索引是从1开始
    //这是修改的绑定语句
    statement.setString(1, user.getUsername());
    statement.setInt(2, user.getId());
    //5.执行语句
    statement.execute();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    finally{
    try {
    DBUtil.closeResource(connection, statement, null);
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }

    public List<User> fidAll(String username){
    ResultSet resultSet = null;
    Connection connection=null;
    //因为数据是从外面传进来的,所以我们使用占位符
    PreparedStatement statement=null;
    try {
    connection = DBUtil.getConnection();
    //3.准备语句
    //这是查询的数据库语句
    String sql = "SELECT * from tb_user where username = ?";
    //创建预编译的,1指语句第一个?占位符
    statement = connection.prepareStatement(sql);
    statement.setString(1, username);
    //5.执行语句
    resultSet = statement.executeQuery();
    List<User> au =new ArrayList<User>();

    while (resultSet.next()) {
    User user = new User();
    user.setId(resultSet.getInt("id"));
    user.setUsername(resultSet.getString("username"));
    user.setPassword(resultSet.getString("password"));

    au.add(user);
    }
    return au;
    } catch (Exception e) {

    e.printStackTrace();
    }
    finally{
    try {
    DBUtil.closeResource(connection, statement, resultSet);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    return null;
    }

    }

    User.java

    package com.ants.entity;

    import java.io.Serializable;

    public class User implements Serializable{

    private static final long serialVersionUID = 1L;

    private Integer id;
    private String username;
    private String password;
    public Integer getId() {
    return id;
    }
    public void setId(Integer id) {
    this.id = id;
    }
    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;
    }

    @Override
    public String toString() {
    return "User [id=" + id + ", userName=" + username + ", password=" + password + "]";
    }
    }

    LoginServlet.java

    package com.ants.service;

    import java.io.IOException;
    import java.util.List;

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

    import com.ants.dao.UserDao;
    import com.ants.entity.User;

    public class LoginService extends HttpServlet{
    private static final long serialVersionUID = 1L;

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    //设置post请求的编码格式
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");

    String name = request.getParameter("userName");
    String pass = request.getParameter("passWord");
    UserDao dao = new UserDao();
    List<User> list = dao.fidAll(name);

    for(User user1:list){
    if(name.equals(user1.getUsername())&&pass.equals(user1.getPassword())){
    request.getRequestDispatcher("/manager.jsp").forward(request, response);
    return;
    }else{
    request.getRequestDispatcher("/login.jsp").forward(request, response);
    return;
    }
    }
    }
    }

    RegisterServlet.java

    package com.ants.service;

    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.ants.dao.UserDao;
    import com.ants.entity.User;

    public class RegisterService extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void service(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    //设置post请求信息的编码格式
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    //得到用户名和密码 从jsp页面获取
    String username = request.getParameter("userName");
    String password = request.getParameter("passWord");
    //验证用户
    System.err.println(username+password);

    UserDao userDao = new UserDao();
    User user = new User();

    user.setUsername(username);
    user.setPassword(password);

    userDao.save(user);

    request.getRequestDispatcher("/login.jsp").forward(request, response);

    }

    }

     DBUtilTest.java

    package com.ants.test;

    import java.sql.Connection;

    import com.ants.util.DBUtil;

    public class DBUtilTest {
    public static void main(String[] args) {
    try {
    Connection connection = DBUtil.getConnection();
    System.out.println(connection);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }

    UserDaoTest.java

    package com.ants.test;

    import org.junit.Test;

    import com.ants.dao.UserDao;
    import com.ants.entity.User;

    public class UserDaoTest {
    @Test
    public void save(){
    UserDao userDao = new UserDao();
    User user = new User();
    user.setUsername("古威");
    user.setPassword("456");

    userDao.save(user);
    }
    }

    生活就要逢山开路遇水搭桥,愿共勉!
  • 相关阅读:
    Photoshop 图文并茂常用快捷键
    程序员放松的8个好网站推荐
    Ehcache详细解读
    IT人士必去的10个网站
    [javascript]避免悲剧 密码生成器
    jQuery创建实例与原型继承揭秘
    [javascript]快速交换javascript变量的值
    [javascript]web216安全色拾色器colorpicker 支持浏览器边缘碰撞翻转(原生js)
    [Javascript]单例模式(singleton )
    duffsDevice 高速版
  • 原文地址:https://www.cnblogs.com/TianMu/p/7650811.html
Copyright © 2020-2023  润新知