Java(Servlet) 登录

1、建一个index.jsp页面来加载登录页面;这样的好处是方便后面做权限功能

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'index.jsp' starting page</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">
	/*加载的路径*/
	<meta http-equiv="refresh" content="0;url=<%=path%>/servlet/LoginServIer?type=toLogin">
  </head>
  <body>
      加载层<br>
  </body>
</html>

2、从index.jsp页面获取加载登录页面路径<meta http-equiv="refresh" content="0;url=<%=path%>/servlet/LoginServIer?type=toLogin">

package com.xmg.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServIer extends HttpServlet{
	private static final long serialVersionUID = 8656302855411063031L;
	@Override
	public  void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}	
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String type=request.getParameter("type");
		if ("toLogin".equals(type)) {
			toLogin(request, response);
		}else {
			response.sendRedirect("../index.jsp");//重定向
		}
	}
	/*登录*/
	public void toLogin(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
        String token = TokenProccessor.getInstance().makeToken();
		request.getSession().setAttribute("token", token);
		/*转发到登录页面*/
		request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
	}
}

3、servlet层转发到登录页面login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set value="${pageContext.request.contextPath}" scope="page" var="ctx"></c:set>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <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">
	<link rel="stylesheet" href="css/icon/iconfont.css" type="text/css"></link>
  </head>
  <body>
    <div id="box">
	   <div id="box1">
	       <div class="dlr"></div>
	       <div class="dlz">
	         <div style="width: 100%;height: 13.9%;"></div>
	         <div style="width: 100%;height: 86.1%;">
	         <h2 class="wenzi">欢迎登录管理平台</h2>
	             <form action="${ctx}/servlet/LoginServIer" method="post">
	             <input type="hidden" name="type" value="login"/>
	             <input type="hidden" name="token" value="${token}"/>
	                 <p style="margin-top: 37px;">
	                    <span class="iconfont icon-dengluming"></span>
	                 	<input class="wengben" type="text" placeholder="用户名" name="UserMC">
	                 </p>
	                 <p>
	                    <span class="iconfont icon-yonghuleixing" style="font-size: 61px;position: relative;top:-8px;left: 0px;"></span>
		                <select  class="xiala" placeholder="用户类型" name="UserTypeID">
		                 	<option value="">请选择</option> 
		                 	<option value="1">董事长</option> 
		                 	<option value="9">管理员</option> 
		                 	<option value="3">前台人员</option> 
		                </select>   
	                 </p>
		             <p>
		                <span class="iconfont icon-mima" style="font-size: 27px;"></span>
		                <input class="wengben" type="password" placeholder="密码" name="Password">
		             </p>
		             <p style="height:45px;width:300x;background: #fff;border-radius:50px;margin-left: 45px;">
		                <input type="text" id="wenben" name="codekey" placeholder="输入验证码"/>
		                <jsp:useBean id="now" class="java.util.Date" scope="page"/>
		                <img id="codekey" alt="" src="${ctx}/servlet/IdentityServlet?t=${now}" onclick="refcodekey()">
		             </p>
		             <label class="checkbox">
		                <input style="outline: none;" type="checkbox">记住密码
		                <a href="#" style="margin-left:25px;">忘记密码?</a>
		             </label>
		             <p class="dlu"><button type="submit">登录</button></p>
	             </form>
	         </div>
	       </div>
	    </div>
    </div>
  <script type="text/javascript" src="js/jquery-2.0.3.min.js"></script>
  <script type="text/javascript" src="js/Particleground.js"></script>
  <script type="text/javascript" src="../js/layer.js"></script>
  <script type="text/javascript">
     /*加载验证码*/
       function refcodekey(){
            document.getElementById("codekey").src="${ctx}/servlet/IdentityServlet?t="+new Date();
        }
       $(document).ready(function () {
            //粒子背景特效
            $('body').particleground({
                dotColor: '#fff',//#9cea98
                lineColor: '#CFD6E5'//线颜色
            });
        });  
        /*锁定div大小*/
        function bodyScale() {
            var i = screen.width;//获取电脑屏幕的宽度
            var width = window.innerWidth;//获取浏览器当前的宽度
            var scales = width / i;
            var box = document.getElementById("box");
            box.style.zoom = scales;//zoom缩放           
        }
        window.onload = window.onresize = function () {
            bodyScale();            
        };
  </script>
  </body>
</html>

4、从login.jsp获取登录信息加载到servlet层进行信息的验证

package com.xmg.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xmg.po.UserPo;
import com.xmg.service.IUserService;
import com.xmg.service.impl.UserSerivceImpl;
import com.xmg.utli.MD5Util;
import com.xmg.utli.TokenProccessor;

public class LoginServIer extends HttpServlet{
	private static final long serialVersionUID = 8656302855411063031L;
	@Override
	public  void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}	
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String type=request.getParameter("type");
	   if ("login".equals(type)) {
			login(request, response);
		}else {
			response.sendRedirect("../index.jsp");//重定向
		}
	}
	public void login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String UserMC=request.getParameter("UserMC");
		String Password=request.getParameter("Password");
		String codekey=request.getParameter("codekey");
		String token = request.getParameter("token");
		int UserTypeID=Integer.parseInt(request.getParameter("UserTypeID")) ;
		response.setCharacterEncoding("utf-8");
		PrintWriter out=response.getWriter();//初始化out对象
		//session
		String sessionCodekey= (String) request.getSession().getAttribute("randomString");
		String sessiontoken = (String) request.getSession().getAttribute("token");		
		/*if (token !=null && token.equals(sessiontoken)) {
			request.getSession().removeAttribute("token");*/
			//equalsIgnoreCase:忽略大小写
			if (codekey !=null && codekey.equalsIgnoreCase(sessionCodekey)) {
				IUserService userService =new UserSerivceImpl();
				UserPo dbUserPo = userService.login(UserMC);/*查询的结果*/
				if (dbUserPo !=null && UserMC.equalsIgnoreCase(UserMC)) {
					if (dbUserPo.getUserTypeID()== UserTypeID) {
						Password=MD5Util.getMD5(Password);
						if (dbUserPo.getPassword().equals(Password)) {
							request.getSession().setAttribute("UserMC", dbUserPo);
							request.getSession().setAttribute("UserTypeID", dbUserPo);
							request.getRequestDispatcher("/jsp/Main.jsp").forward(request, response);
						} else {
							out.print("<html><head><meta charset='utf-8'></head><script>alert('密码错误');window.location.href = '../index.jsp';</script>");
						}	
					} else {
						out.print("<html><head><meta charset='utf-8'></head><script>alert('用户类型不对');window.location.href = '../index.jsp';</script>");
					}
				} else {
					out.print("<html><head><meta charset='utf-8'></head><script>alert('没有此用户');window.location.href = '../index.jsp';</script>");
				}
			} else {
				out.print("<html><head><meta charset='utf-8'></head><script>alert('验证码错误');window.location.href = '../index.jsp';</script>");
			}
		} /*else {
			out.print("<html><head><meta charset='utf-8' http-equiv='refresh' content='0';></head><script>alert('重复提交');</script>");
		}
	}*/
}

5、查询数据库用户信息的数据传到servlet

package com.xmg.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.xmg.dao.IUserDao;
import com.xmg.po.OutStopCheck;
import com.xmg.po.UserPo;
import com.xmg.utli.DBUtil;

public class UserDaoImpl implements IUserDao {
    private Connection con =null;
	private PreparedStatement ps=null;
	private ResultSet rs= null;
	private String login1="SELECT *FROM tb_user,tb_usertype WHERE tb_user.UserMC=?  AND tb_user.UserTypeID=tb_usertype.UserTypeID";
	/*登录*/
	@Override
	public UserPo login(String name) {
		UserPo user = null;
		try {
			con=DBUtil.getConnection();
			ps=con.prepareStatement(login1);
			ps.setString(1, name);
			rs=ps.executeQuery();
			while (rs.next()) {
				user =new UserPo();
				user.setUserID(rs.getInt("userID"));
				user.setUserTypeID(rs.getInt("userTypeID"));
				user.setUserMC(rs.getString("userMC"));
				user.setPassword(rs.getString("password"));
				user.setRemarks(rs.getString("remarks"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DBUtil.close(con, ps, rs);
		}
		return user;
	}
}

6、效果图
在这里插入图片描述

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Text extends JFrame implements ActionListener,TextListener { private JLabel username,password,email,telephone; private JTextField usernameField,emailField; private TextField teleField; private JPasswordField passwordField; private JButton registButton,cancelButton; public Text() { super("用户注册"); Container container = getContentPane(); container.setLayout(new FlowLayout()); username = new JLabel("用户名"); username.setToolTipText("请输入用户名"); password = new JLabel("密 码"); password.setToolTipText("密码不能少于6位"); email = new JLabel("邮 箱"); email.setToolTipText("邮箱中必须包含@字符"); telephone = new JLabel("电 话"); telephone.setToolTipText("电话只能为数字"); usernameField = new JTextField(15); usernameField.addActionListener(this); passwordField = new JPasswordField(15); passwordField.addActionListener(this); emailField = new JTextField(15); emailField.addActionListener(this); teleField = new TextField(21); teleField.addActionListener(this); teleField.addTextListener(this); registButton = new JButton("注册"); cancelButton = new JButton("取消"); container.add(username); container.add(usernameField); container.add(password); container.add(passwordField); container.add(email); container.add(emailField); container.add(telephone); container.add(teleField); container.add(registButton); container.add(cancelButton); registButton.addActionListener(this); cancelButton.addActionListener(this); setSize(250,200); setVisible(true); setResizable(false); } public void textValueChanged(TextEvent event) { if (event.getSource() == teleField) { /*if (!checkNumber(teleField.getText())) { JOptionPane.showMessageDialog(this,"电话必须为数字","温馨提示",JOptionPane.INFORMATION_MESSAGE); teleField.setText(""); } */ } } public void actionPerformed(ActionEvent event) { if (event.getSource() == usernameField) { if (usernameField.getText().equals("")) { JOptionPane.showMessageDialog(null,"用户名不能为空","温馨提示",JOptionPane.INFORMATION_MESSAGE); } } if (event.getSource() == passwordField) { if (passwordField.getPassword().length == 0) { JOptionPane.showMessageDialog(this,"密码不能为空","温馨提示",JOptionPane.INFORMATION_MESSAGE); } else if (passwordField.getPassword().length < 6) { JOptionPane.showMessageDialog(this,"密码长度不能小于6位","温馨提示",JOptionPane.INFORMATION_MESSAGE); passwordField.setText(""); } } if (event.getSource() == emailField) { if (emailField.getText().indexOf("@") < 0 || emailField.getText().indexOf("@") >= (emailField.getText().length() - 1) || emailField.getText().equals("")) { JOptionPane.showMessageDialog(this,"您的邮箱格式不正确","温馨提示",JOptionPane.INFORMATION_MESSAGE); emailField.setText(""); } } if (event.getSource() == teleField) { if (teleField.getText().equals("")) { JOptionPane.showMessageDialog(this,"联系电话不能为空","温馨提示",JOptionPane.INFORMATION_MESSAGE); } else if (!checkNumber(teleField.getText())) { JOptionPane.showMessageDialog(this,"电话必须为数字","温馨提示",JOptionPane.INFORMATION_MESSAGE); teleField.setText(""); } } if (event.getSource() == registButton) { if (usernameField.getText().equals("") || passwordField.getPassword().length == 0 || emailField.getText().equals("") || teleField.getText().equals("")) { JOptionPane.showMessageDialog(this, "您填写的信息不完整","温馨提示",JOptionPane.INFORMATION_MESSAGE); usernameField.setText(""); passwordField.setText(""); emailField.setText(""); teleField.setText(""); } else if (passwordField.getPassword().length < 6) { JOptionPane.showMessageDialog(this,"密码长度不能小于6位","温馨提示",JOptionPane.INFORMATION_MESSAGE); passwordField.setText(""); } else if (emailField.getText().indexOf("@") < 0 || emailField.getText().indexOf("@") >= (emailField.getText().length() - 1)) { JOptionPane.showMessageDialog(this,"您的邮箱格式不正确","温馨提示",JOptionPane.INFORMATION_MESSAGE); emailField.setText(""); } else if (!checkNumber(teleField.getText())) { JOptionPane.showMessageDialog(this,"电话必须为数字","温馨提示",JOptionPane.INFORMATION_MESSAGE); teleField.setText(""); } else JOptionPane.showMessageDialog(this,"恭喜您,注册成功","温馨提示",JOptionPane.INFORMATION_MESSAGE); } if (event.getSource() == cancelButton) { usernameField.setText(""); passwordField.setText(""); emailField.setText(""); teleField.setText(""); } } public boolean checkNumber(String str) { for (int i=0;i<str.length();i++) { return false; } return true; } public static void main(String args[]) { Text application = new Text(); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值