• java jsp+servlet+mysql实现登录网页设计


    涉及以下几个文件:


    1。登录页面 login.jsp

    2,成功跳转页面 success.jsp

    3,失败跳转页面 fail.jsp

    4,servlet 处理类 LoginTestServlet.java

    5,配置文件 web.xml


    ---------------------------------------------  依次看代码      --------------------------------------------

    LoginTestServlet.java 内容

    package com.test;
    
    import java.io.IOException;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import com.mysql.jdbc.Connection;
    import com.mysql.jdbc.Statement;
    
    /**
     * Servlet implementation class LoginTestServlet
     */
    @WebServlet("/LoginTestServlet")
    public class LoginTestServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public LoginTestServlet() {
            super();
            
        }
    
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		doPost(request, response);
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		response.setContentType("text/heml;charset=gb2312");
    		request.setCharacterEncoding("gb2312");
    		
    		String result = "";
    	
    		String username = request.getParameter("username");
    		String psw = request.getParameter("password");
    		
    		if(username == "" || username == null || username.length()>20){
    			try {
    				result = "请输入用户名(不能超过20个字符)";
    				request.setAttribute("message", result);
    				response.sendRedirect("login.jsp");
    				return;
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}
    		
    		if(psw == "" || psw == null || psw.length() > 20){
    			try {
    				result = "请输入password(不能超过20个字符)";
    				request.setAttribute("message", result);
    				response.sendRedirect("login.jsp");
    				return;
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}
    		
    		//登记JDBC驱动程序
    		try {
    			Class.forName("com.mysql.jdbc.Driver");
    		} catch (Exception e) {
    			System.out.print("Class Not Found Exception");
    		}
    		
    		//链接URL
    		String url = "jdbc:mysql://localhost:3306/demo";
    		Connection conn = null;
    		Statement stmt = null;
    		ResultSet rs = null;
    		
    		try {
    			conn = (Connection) DriverManager.getConnection(url,"root","root");
    			stmt = (Statement) conn.createStatement();
    			
    			String sql = "select * from userInfo where username='"+username+"' and userpsw= '"+psw+"'";
    			rs = stmt.executeQuery(sql);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		
    	HttpSession session = request.getSession();
    	session.setAttribute("username", username);
    		
    	try {
    		if(rs.next()){
    		    session.setAttribute("age",rs.getString("age")) ;
    		    session.setAttribute("sex",rs.getString("sex")) ;
    		    session.setAttribute("weight",rs.getString("weight")) ;
    		    response.sendRedirect("success.jsp") ;
    		    return;
    		}else{
    		    session.setAttribute("message", "用户名或password不匹配。

    "); response.sendRedirect("fail.jsp") ; return; } } catch (Exception e) { e.printStackTrace(); } } }


    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>用户登录</title>
    </head>
    <body>
     	<form method="POST" name="frmLogin" action="LoginTestServlet">
     		<h1 align="center">用户登录</h1>
     		<center>
     			<table border="1">
     				<tr>
     					<td>用户名:</td>
     					<td>
     					    <input type="text" name="username" value="" size="20" maxlength="20" onfocus="if (this.value=='Your name')  this.value='';" />
     					</td>
     				</tr>
     				<tr>
     					<td>密  码</td>
     					<td>
     						<input type="password" name="password" value="" size="20" maxlength="20" onfocus="if(this.value=='Your Password') this.value='';">
     					</td>
     				</tr>
     				<tr>
     					<td>
     						<input type="submit" name="Submit" value=" 提交" onclick="return validateLogin()">
     					</td>
     					<td>
     					    <input type="reset" name="Reset" value="重置" />
     					</td>
     				</tr>
     			</table>
     		</center>
     	</form>
     	
     	<script type="text/javascript">
     			   function validateLogin(){
     				 var sUserName = document.frmLogin.username.value;
     				 var sPassword = document.frmLogin.psssword.value;
     			    if (sUserName ==""){
     			     alert("请输入用户名!");
     			     return false ;
     			    }
     			    
     			    if (sPassword ==""){
     			     alert("请输入密码!");
     			     return false ;
     			    }
     		}
     	</script>
    </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>Insert title here</title>
    </head>
    <body>
    <%
       String userName = (String)session.getAttribute("username") ;
       String age = (String)session.getAttribute("age") ;
       String weight = (String)session.getAttribute("weight") ;
       String sex = (String)session.getAttribute("sex") ;
       System.out.println("性别:A" + sex +"A")  ;
       if (sex.trim().equals("M")) {
        sex ="男" ;
       }else{
        sex = "女" ;
       }
      %>
      <div align="center">
       <%=userName %>
       欢迎您,登陆成功。<br />
       <font color="blue">登陆用户信息:</font>
       <table border =1 >
        <tr>
         <td> 姓名: </td>
         <td>  <%=userName %>  </td>
        </tr>
        <tr>
         <td> 年龄: </td>
         <td>  <%=age %>  </td>
        </tr>
        <tr>
         <td> 体重: </td>
         <td>  <%=weight %> kg </td>
        </tr>
        <tr>
         <td> 性别: </td>
         <td>  <%=sex %>  </td>
        </tr>
       </table>
       <a href="login.jsp">返回</a>
      </div>
    </body>
    </html>

    fail.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>
    </head>
    <body>
    	<%
    		String userName = (String) session.getAttribute("username");
    		String msg = (String) session.getAttribute("message");
    	%>
    	<div align="center">
    		<%=userName%>
    		对不起。登陆失败!<br /> <font color="red">原因: </font>
    		<%=msg%>
    		<br /> <br /> 5秒后将返回登陆界面。

    </div> <% response.setHeader("Refresh", "5;URL=/webDemo/login.jsp"); %> </body> </html>


    -------------------------------------------------------配置数据库------------------------------------------------------

     mysql数据库中须要创建数据库demo,当中创建表userInfo 创建表语句为:
      create databasedemo;
      use demo
      create table userInfo(id int not null primary key,username char(20) not null,userpsw char(20) ,age int ,weight int ,sex enum('M','F')) ;
      
      须要把连接mysql的jar包放到项目的lib文件夹中

    ---------------------------------------------华丽的切割线----------------------------------------

    最后 web.xml 内容

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xmlns="http://java.sun.com/xml/ns/javaee"
    	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    	id="WebApp_ID" version="3.0">
    	<display-name>webDemo</display-name>
    	<welcome-file-list>
    		<welcome-file>index.html</welcome-file>
    		<welcome-file>index.htm</welcome-file>
    		<welcome-file>index.jsp</welcome-file>
    		<welcome-file>default.html</welcome-file>
    		<welcome-file>default.htm</welcome-file>
    		<welcome-file>default.jsp</welcome-file>
    	</welcome-file-list>
    	<servlet>
    		<servlet-name>LoginTestServlet</servlet-name>
    		<servlet-class>com.test.LoginTestServlet</servlet-class>
    	</servlet>
    	
    	<servlet-mapping>
    		<servlet-name>LoginTestServlet</servlet-name>
    		<url-pattern>/loginTestServlet</url-pattern>
    	</servlet-mapping>
    </web-app>


  • 相关阅读:
    关于工作习惯的一点思考
    BulkSqlCopy 批量导入数据(Ef支持)
    记录下最近项目中常用到的SQL语句
    对象化前端表单(Form)提交
    Python描述符 (descriptor) 详解
    Python装饰器之 property()
    Python魔法方法之属性访问 ( __getattr__, __getattribute__, __setattr__, __delattr__ )
    Python魔法方法总结及注意事项
    面向对象编程(二)
    面向对象编程(一)
  • 原文地址:https://www.cnblogs.com/wgwyanfs/p/6843771.html
Copyright © 2020-2023  润新知