JavaEE作业-实验一

目录

1 实验内容

2 思路

3 核心代码

(1)前端核心代码:

(2)后端核心代码:

4 实验结果


1 实验内容

用Servlet + JSP + JavaBean实现登录功能

2 思路

①建好web项目,创建数据库

②建立两个简单的前端页面,用于登录和验证是否成功登录

③创建五个包,bean用于作为数据的载体,dao、service、control用于实现前端与数据库的交互,util为JDBC工具包

④前端输入数据,通过访问数据库实现登录,并向前端页面提供相应反馈

3 核心代码

(1)前端核心代码:

①提交数据与失败反馈:

<form action="login" method="post">
    <p>登录页面p>
    <p>账号p>
    <input type="text" class="form-control" name="user_account" style="width: 200px">
    <p>密码p>
    <input type="password" class="form-control" name="user_password" style="width: 200px">
    <p>p>
    <button type="submit">登录button>
form>
<span style="color: #F00;">${info}span>

②成功登录反馈:

<p>尊敬的${name},欢迎您p>

(2)后端核心代码:

①前端与后端交互:

@WebServlet("/login")
public class LoginControl extends HttpServlet{
    UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String user_account = request.getParameter("user_account");
        String user_password = request.getParameter("user_password");
        User user = new User(user_account, user_password, null);
        String result = userService.login(user);
        if(result != null) {
            request.getSession().setAttribute("name", result);
            response.sendRedirect("success.jsp");
        }else {
            request.setAttribute("info", "账号或密码错误");
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
    }
}

②后端与数据库交互:

public class UserDaoImpl implements UserDao {
    @Override
    public String login(User user) {
        Connection conn = JDBCUtil.getConn();
        String sql = "select user_name from experiment1.user where user_account=? and user_password = ?";
        String userName = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, user.getUserAccount());
            pstmt.setString(2, user.getUserPassword());
            rs = pstmt.executeQuery();
            if(rs.next()){
                userName = rs.getString(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userName;
    }
}

4 实验结果

已知数据库中的数据为:

JavaEE作业-实验一_第1张图片

(1)输入正确账号和密码并成功登录时:

输入正确数据:

JavaEE作业-实验一_第2张图片

成功跳转:

JavaEE作业-实验一_第3张图片

(2)账号或密码有问题为能成功登录时:

输入错误数据:

JavaEE作业-实验一_第4张图片

失败反馈:

JavaEE作业-实验一_第5张图片

你可能感兴趣的:(作业,java-ee,java)