J2EE_登陆验证
Posted sw-p-wy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了J2EE_登陆验证相关的知识,希望对你有一定的参考价值。
新建项目
打开IDEA,并新建一个Web项目
添加Tomcat服务器,并添加包依赖
创建数据库,数据表,并添加内内容
创建Servlet,进行登陆验证
作者使用的mysql 5.6版本,并且部署于服务器,所以先要去网上下载JDBC驱动(下载地址,mysql数据库与JDBC版本对应查看地址),下载zip包并导入项目(参考博客),接下来就是新建Servlet编写代码了
1 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 2 // 获得输入流 3 PrintWriter out = response.getWriter(); 4 // 从请求对象中获得指定参数的值 5 String strName = request.getParameter("txtName"); 6 String strPwd = request.getParameter("txtPwd"); 7 //定义数据库操作所需对象 8 Connection conn=null; 9 Statement stmt; 10 ResultSet rs; 11 PreparedStatement psmt; 12 // 数据库链接需要的参数 13 String driver="com.mysql.jdbc.Driver"; 14 String url = "jdbc:mysql://49.234.222.244:3306/J2EE"; 15 String user = "root"; 16 String pwd = "990130"; 17 try { 18 Class.forName(driver); 19 conn = DriverManager.getConnection(url,user,pwd); 20 String sql = "select * from USER where username=? and pwd=?"; 21 psmt = conn.prepareStatement(sql); 22 psmt.setString(1,strName); 23 psmt.setString(2,strPwd); 24 rs = psmt.executeQuery(); 25 if(rs.next()) 26 { 27 //设置cookie 28 Cookie cooUsername = new Cookie("username",strName); 29 cooUsername.setMaxAge(60*60*24*7); 30 response.addCookie(cooUsername); 31 Cookie cooPwd = new Cookie("pwd",strPwd); 32 cooPwd.setMaxAge(60*60*24*7); 33 response.addCookie(cooPwd); 34 35 HttpSession session = request.getSession(true); 36 session.setAttribute("username",strName); 37 session.setAttribute("pwd",strPwd); 38 39 String path = request.getContextPath(); 40 String basepath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 41 String page = basepath+"/page/Online.jsp"; 42 response.sendRedirect(page); 43 } 44 else 45 { 46 out.println("错误的用户名和密码!"); 47 } 48 psmt.close(); 49 } catch (ClassNotFoundException | SQLException e) { 50 e.printStackTrace(); 51 } 52 }
编写完代码一定要记得在web.xml中注册!!!
如果用户在登录时选择保存登录信息,30天内,用户无需登录
这个功能可以通过Cookie实现,需要Servlet,同时需要修改js文件,下面贴出主要代码
1 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 2 Cookie coo = new Cookie("username", "tom");//创建一个键值对的cookie对象 3 coo.setMaxAge(60*60*24*7);//设置cookie的生命周期 4 response.addCookie(coo);//添加到response中 5 }
1 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 2 Cookie coo[] = request.getCookies();//获取request中cookie集合 3 4 //循环遍历 5 for (Cookie co : coo) { 6 System.out.println(co.getName() + ":" + co.getValue()); 7 response.getWriter().println(co.getValue()); 8 } 9 }
1 function getCookie(cname){ 2 var name = cname + "="; 3 var ca = document.cookie.split(‘;‘); 4 for(var i=0; i<ca.length; i++) { 5 var c = ca[i].trim(); 6 if (c.indexOf(name)==0) { return c.substring(name.length,c.length); } 7 } 8 return ""; 9 } 10 function checkCookie(){ 11 var user=getCookie("username"); 12 var uname=document.getElementById("input_user"); 13 var pwd=getCookie("pwd"); 14 var upwd=document.getElementById("input_password"); 15 16 17 if (user!=""){ 18 var uname=document.getElementById("input_user"); 19 uname.value=user; 20 upwd=pwd; 21 } 22 }
显示网站当前在线人数
这个功能可以通过Session实现,需要Servlet,这里采用了Listener+Session
1 private static int activeSessions = 0; //初始化在线人数 2 // Public constructor is required by servlet spec 3 4 public void sessionCreated(HttpSessionEvent se) { 5 activeSessions++; 6 } 7 8 public void sessionDestroyed(HttpSessionEvent se) { 9 if(activeSessions>0) 10 { 11 activeSessions--; 12 } 13 } 14 public static String getActiveSessions() { 15 return String.valueOf(activeSessions); 16 }
同时JSP页面添加
Online.jsp
<%@ page import="SessionOnline.ListenerSession" %> <html> <head> <title>Title</title> </head> <body> <% String name= (String)request.getSession().getAttribute("username"); String pwd=(String)request.getSession().getAttribute("pwd"); String nums = (String)ListenerSession.getActiveSessions(); %> <h1>您好!</h1> <p>用户名:<%=name%><br></p> <p>密码:<%=pwd%><br></p> <p>在线人数:<%=nums%></p>
登录时用户名为中文可能不能正常识别,解决该问题
这个功能需要使用Filter实现,新建一个Filter,并将其用web.xml注册
1 @WebFilter(filterName = "GBFilter") 2 public class GBFilter implements Filter { 3 public void destroy() { 4 } 5 6 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { 7 String encoding=req.getCharacterEncoding();//原来的编码 8 encoding="utf-8";//新编码 9 req.setCharacterEncoding(encoding); 10 resp.setContentType("text/html;charset="+encoding); 11 chain.doFilter(req, resp); 12 } 13 14 public void init(FilterConfig config) throws ServletException { 15 16 }
最后附上web.xml中代码以及运行结果图
1 <!-- 登陆验证的servlet--> 2 <servlet> 3 <servlet-name>LoginServlet</servlet-name> 4 <servlet-class>LoginServlet</servlet-class> 5 </servlet> 6 <servlet-mapping> 7 <servlet-name>LoginServlet</servlet-name> 8 <url-pattern>/login</url-pattern> 9 </servlet-mapping> 10 <!-- Cookie设置的Servlet--> 11 <servlet> 12 <servlet-name>GetCookie</servlet-name> 13 <servlet-class>GetCookie</servlet-class> 14 </servlet> 15 <servlet-mapping> 16 <servlet-name>GetCookie</servlet-name> 17 <url-pattern>/GetCookie</url-pattern> 18 </servlet-mapping> 19 20 <servlet> 21 <servlet-name>SetCookie</servlet-name> 22 <servlet-class>SetCookie</servlet-class> 23 </servlet> 24 <servlet-mapping> 25 <servlet-name>SetCookie</servlet-name> 26 <url-pattern>/SetCookie</url-pattern> 27 </servlet-mapping> 28 <!-- Session设置的Servlet--> 29 <servlet> 30 <servlet-name>GetSession</servlet-name> 31 <servlet-class>GetSession</servlet-class> 32 </servlet> 33 <servlet-mapping> 34 <servlet-name>GetSession</servlet-name> 35 <url-pattern>/GetSession</url-pattern> 36 </servlet-mapping> 37 <!-- 过滤器Filter设置--> 38 <filter> 39 <filter-name>GBFilter</filter-name>//定义名字 40 <filter-class>GBFilter</filter-class>//实现类 41 </filter> 42 <filter-mapping> 43 <filter-name>GBFilter</filter-name> 44 <url-pattern>/*</url-pattern> 45 <dispatcher>REQUEST</dispatcher> 46 <dispatcher>FORWARD</dispatcher> 47 </filter-mapping>
附上Github地址:https://github.com/WHYNOTEN/J2EE_Second
以上是关于J2EE_登陆验证的主要内容,如果未能解决你的问题,请参考以下文章