使用servlet实现简单用户登录(代码加路径结构)

完整代码下载链接

点击打开链接

1.首先是VO层,定义一个user类

public class User implements Serializable {
    private int id;
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getId() {
        return id;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

2.进行数据库连接,DB层,数据库是MySQL,其中test1是我的数据库名称,

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

public class DB {
    private static Connection conn;

    public static Connection getConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test1?useUnicode=true&characterEncoding=utf-8", "root", "root");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return conn;
    }
    public static void closeConnection(){
        if (conn!=null){

            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }
}

3.DAO层,只进行了简单的登陆注册逻辑处理

public interface IUserDAO {
    public boolean add(User user);
    public User login(User user);

}

public class UserDAOimpl implements IUserDAO{
    //public Connection conn=null;
    public UserDAOimpl(){
        //conn= DB.getConnection();
        System.out.println("lianjie");
    }
    //登陆
    @Override
    public User login(User user) {
        Connection conn=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;

        try {
            conn=DB.getConnection();
            String sql="select * from user where username=? and password=?";
            pstmt=conn.prepareStatement(sql);
            pstmt.setString(1,user.getUsername());
            pstmt.setString(2,user.getPassword());
            rs=pstmt.executeQuery();
            User users=null;
            if (rs.next()){
                users=new User();
                users.setId(rs.getInt("id"));
                users.setUsername(rs.getString("username"));
                users.setPassword(rs.getString("password"));
                return user;
            }else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("有错误");
        }
        return null;
    }
    //注册
    @Override
    public boolean add(User user) {
        Connection conn=null;
        PreparedStatement pstmt=null;
        boolean flag=false;
        String sql="insert into user(username,password) values(?,?)";

        try {
            conn= DB.getConnection();
            pstmt=conn.prepareStatement(sql);
            pstmt.setString(1,user.getUsername());
            pstmt.setString(2,user.getPassword());
            flag=pstmt.executeUpdate()>0?true:false;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(pstmt!=null){
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        //DB.closeConnection();
        return flag;
    }

}

4.然后是前端页面,这个你可以提前做好。

这个是登录页面index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>


  <title>练习</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">

</head>

<body>
<div align="center"> <font size=" 2" color="#FF6633">用户登录</font>
</div>
<form id="form1" name="form1" method="post" action="user/userlogin">
  <table width="357" border="0" align="center">
    <tr>
      <td width="128">用户名:</td>
      <td width="219"><label>
        <input name="username" type="text" id="username" />
      </label></td>
    </tr>
    <tr>
      <td>密 码:</td>
      <td><label>
        <input name="password" type="password" id="pwd" />
      </label></td>
    </tr>
    <tr>
      <td><label>
        <input type="submit" name="Submit" value="登录" />
      </label></td>
      <td><label><a href="addUser.jsp">用户注册</a></label></td>
    </tr>
  </table>
  <p> </p>
</form>
</body>
</html>

这个是注册页面adduser.jsp

<html>
<head>


    <title>练习</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">

</head>

<body>
<div align="center"> <font size=" 2" color="#FF6633">注册</font>
</div>
<form id="form1" name="form1" method="post" action="user/userregister">
    <table width="357" border="0" align="center">
        <tr>
            <td width="128">用户名:</td>
            <td width="219"><label>
                <input name="username" type="text" id="username" />
            </label></td>
        </tr>
        <tr>
            <td>密 码:</td>
            <td><label>
                <input name="password" type="password" id="pwd" />
            </label></td>
        </tr>
        <tr>
            <td><label>
                <input type="submit" name="Submit" value="注册" />
            </label></td>
            <td><label><a href="index.jsp">登陆</a></label></td>
        </tr>
    </table>
    <p> </p>
</form>
</body>
</html>

图省事,省略了service层。直接在servlet上写。

首先是对index.jsp进行响应

@WebServlet("/user/userlogin")
public class UserLoginServlet extends HttpServlet {

        private static final long serialVersionUID = 1L;

        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            this.doPost(request, response);
        }

        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            User user=new User();
            //获取index.jsp页面提交的账号和密码
            String username=request.getParameter("username");
            String password=request.getParameter("password");
            //测试数据
            System.out.println(username+" "+password);
            //获取login.jsp页面提交的账号和密码设置到实体类User中
            user.setUsername(username);
            user.setPassword(password);

            //引入数据交互层
            IUserDAO dao=new UserDAOimpl();
            User us=dao.login(user);
            //测试返回的值
            System.out.println(us);
            if(us!=null){
                //request.setAttribute("info", "登陆成功");
                request.getRequestDispatcher("/in.jsp").forward(request, response);
            }else{
                //request.setAttribute("info", "登录失败");
                request.getRequestDispatcher("/shibai.jsp").forward(request, response);
            }

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



    }

然后是注册页面

@WebServlet("/user/userregister")
public class UserRegisterServlet extends HttpServlet {//注册

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        User user=new User();
        //获取login.jsp页面提交的账号和密码
        String username=request.getParameter("username");
        String password=request.getParameter("password");


        //获取register.jsp页面提交的账号和密码设置到实体类User中
        user.setUsername(username);
        user.setPassword(password);


        //引入数据交互层
        IUserDAO dao=new UserDAOimpl();
        boolean flag=dao.add(user);
        if(flag){
            request.setAttribute("info", "注册成功");
        }else{
            request.setAttribute("info", "注册失败");
        }

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

}

emmmmm,学的也不是太明白,就在servlet里满足条件,比如注册成功就跳转到注册成功info.jsp页面上。如果登陆成功就跳转到in,jsp页面。失败就跳转到shibai.jsp页面上。反正我的没弄注册失败的情况所以就没有注册失败的jsp页面了。

比如in.jsp

<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>登陆成功</h1>
</body>
</html>
info.jsp和shibai.jsp和这个一样。。里面中文改一下。。。。

----------------

路径结构图


lib下面是需要另外引的jar包,我引了两个一个是连接数据库的jar包,一个是servlet的jar包。

运行效果


这个前端代码是网上抄的,,,这个项目就好使了。数据库那边插入用户名和密码也没问题。哦,忘了数据库了


test1里有一个user表,如图。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值