JavaWeb学习之路(三)--- 使用servlet

使用servlet写一个登录的例子:
在登录页面输入用户名、密码,发送请求,通过数据库数据判断该用户是否存在,存在则跳转到成功页面,不存在则跳转到失败页面;

servlet详解:http://www.cnblogs.com/xdp-gacl/p/3760336.html

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>Insert title here</title>
<style type="text/css">
body {
    color: #000;
    font-size: 14px;
    margin: 20px auto;
}
</style>
<script>
    function check(form) {
        if (document.forms.loginForm.uname.value=="") {
            alert("请输入用户名!");
            document.forms.loginForm.uname.focus();
            return false;
        }
        if (document.forms.loginForm.upwd.value=="") {
            alert("请输入密码!");
            document.forms.loginForm.upwd.focus();
            return false;
        }
    }
</script>
</head>
<body>
    <form action="<%= request.getContextPath() %>/checkServlet" method="post" name="loginForm">
         <table border="1" cellspacing="0" cellpadding="5" bordercolor="silver" align="center">
            <tr>
                <td colspan="2" align="center" bgcolor="#e8e8e8">用户登录</td>
            </tr>
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="uname"/></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" name="upwd"/></td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <input type="submit" name="submit" onclick="return check(this);" />
                    <input type="reset" name="Reset"/>
                </td>
            </tr>
         </table>
    </form>
</body>
</html>
error.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>


<style type="text/css">
body {
    color: #000;
    font-size: 14px;
    margin: 20px auto;
}

#message {
    text-align: center
}
</style>

</head>
<body>
    <div id="message">
        登录失败。<br /> 
        您提交的信息为:<br /> 
        <%
            Object obj = request.getAttribute("msg");
            if (obj != null) {
                out.println(obj.toString());
            } else {
                out.println("无");
            }
        %>
        <br/>
        用户名:<%=request.getParameter("uname")%><br />
        密码:<%=request.getParameter("upwd")%><br /> 
        <a href="<%= request.getContextPath() %>/LoginServlet2/login.jsp">返回登录页面</a>
    </div>
</body>
</html>
success.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>
<style type="text/css">
body {
    color: #000;
    font-size: 14px;
    margin: 20px auto;
}

#message {
    text-align: center
}
</style>
</head>
<body>
    <div id="message">
        登录成功。<br /> 您提交的信息为:<br /> 用户名:<%=request.getParameter("uname")%><br />
        密码:<%=request.getParameter("upwd")%><br /> <a href="<%= request.getContextPath() %>/LoginServlet2/login.jsp">返回登录页面</a>
    </div>
</body>
</html>
CheckUserService.java 
// 验证登录提交的数据在数据库中是否正确
package com.package.service;

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

import com.package.dao.UserDao;
import com.package.dao.impl.UserDaoImpl;
import com.package.entity.User;
import com.package.util.ConnectionFactory;
public class CheckUserService {
    private UserDao userDao = new UserDaoImpl();
    public boolean check(User user) {
        Connection conn = null;
        try {
            conn = ConnectionFactory.getInstance().makeConnection();
            conn.setAutoCommit(false);

            ResultSet resultSet = userDao.get(conn, user);
            while(resultSet.next()) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (Exception e2) {
                e2.printStackTrace();
            } finally {
                try {
                    conn.close();
                } catch (Exception e3) {
                    e3.printStackTrace();
                }
            }
        }
        return false;
    }
}
CheckServlet.java
// 对登录提交的数据进行处理,然后跳转到响应的反馈页面
package com.package.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.package.entity.User;
import com.package.service.CheckUserService;
public class CheckServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
     private CheckUserService cku = new CheckUserService();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String uname = request.getParameter("uname");
        String passwd = request.getParameter("upwd");
        RequestDispatcher rd = null;

        if (uname == null || passwd == null) {
            request.setAttribute("msg", "用户名或者密码为空!");
            rd = request.getRequestDispatcher("/LoginServlet2/error.jsp");
            rd.forward(request, response);
        } else {
            User user = new User();
            user.setName(uname);
            user.setPassword(passwd);
            if (cku.check(user)) {
                rd = request.getRequestDispatcher("/LoginServlet2/successed.jsp");
            } else {
                request.setAttribute("msg", "用户名或者密码不正确!");
                rd = request.getRequestDispatcher("/LoginServlet2/error.jsp");
            }       
            rd.forward(request, response);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值