jsp+Servlet的登录小例子

来源:互联网 发布:linux 多线程 sleep 编辑:程序博客网 时间:2024/05/16 12:22

最近徒弟们实训,做一个留言板,结果他们的数据操作全写在jsp页面里,我一看立即晕了,后来就出问题了,最后我给他们用jsp+servlet+javabean写了一个登录例子

login.jsp

<?xml version="1.0" encoding="UTF-8" ?><%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>Insert title here</title><script type="text/javascript">function check(){var user_name = document.getElementById("username").value;var user_pwd = document.getElementById("password").value;if(user_name==""){alert("用户名不能为空!");return false;}else if(user_pwd==""){alert("密码不能为空!");return false;}}</script></head><body><form action="CheckServlet.do" method="post" onsubmit="return check(this)">用户名:<input type="text" name="username" id="username"/><br/>密  码:<input type="password" name="password" id="password"/><br/><input type="submit" value="提交"/><input type="reset" value="重置"/></form><%String tip = (String)request.getAttribute("tip");if(tip==null || tip==""){out.print("");}else{%><%=tip %><%}%></body></html>

CheckServlet.java

package com.hncst.servlet;import java.io.IOException;import java.sql.ResultSet;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.hncst.database.DBManager;public class CheckServlet extends HttpServlet {private static final long serialVersionUID = 1L;           public CheckServlet() {        super();    }protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");String username = new String (request.getParameter("username").getBytes("ISO-8859-1"), "UTF-8");String password = new String (request.getParameter("password").getBytes("ISO-8859-1"), "UTF-8");ResultSet rs = null;String sql = "select * from tb_user where username='"+username+"' and password='"+password+"'";DBManager db = new DBManager();rs = db.getResult(sql);try {if(rs.next()){String username_db = rs.getString("username");String password_db = rs.getString("password");if(username.equals(username_db) && password.equals(password_db)){response.sendRedirect("welcome.jsp");}}else{request.setAttribute("tip", "用户名或密码错误!");request.getRequestDispatcher("login.jsp").forward(request,response);}rs.close();db.Release();} catch (SQLException e) {e.printStackTrace();}}}

项目代码在这里可以下载:liuyan.zip