javaweb简单登录界面访问mysql

概述:实现登录功能,用户输入帐号和密码,通过form表单提交至后台处理,查询数据库,如果用户名和密码均正确,则弹框提示用户登录成功,否则提示登录失败。

开发工具:eclipse Mars.2 Release (4.5.2)
服务器 :apache-tomcat-7.0.68
数据库:MySql

效果图:


项目结构图:



前台源码:用到了简单的 bootstrap 和 jquery

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@ page import="java.util.*" %>
<!DOCTYPE html >
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<!--修正IE浏览器渲染效果的问题-->
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<!--内容自适应-->
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="css/bootstrap.css" type="text/css" >
	<script type="text/javascript" src="js/jquery.js"></script>
	<title>用户登录</title>
	<!-- 点击重置按钮清空用户名和密码 -->
	<script>
		$(document).ready(function(){
			$("#reset").click(function(){
				$("#username").val("");
				$("#pwd").val("");
			});
		});
	</script>
</head>
<body>
	<div class="row text-center" style="padding-top:30px; padding-bottom:30px; background-color: #CCC; margin-top:200px;">
		<form action="LoginServlet" method="post">
			<div class="col-md-6 col-md-offset-3">
				<div>
					<label>帐号:</label> 
					<input type="text" id="username" name="username" />
				</div>
				<div>
					<label class="img-circle">密码:</label> 
					<!-- name很中要,用于后台获取值,一般class修饰样式,id在js中用 -->
					<input class="input" id="pwd" name="pwd" type="password" />
				</div>
				<div style="margin:10px 0px;">
					<input class="btn btn-primary" type="submit" value="登录" /> 
					<input class="btn btn-group" id="reset" type="button" value="重置" />
				</div>
			</div>
		</form>
	</div>
	<script type="text/javascript" src="js/jquery.js"></script>
</body>
</html>

后台代码:使用了servlet

package com.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
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.mysql.jdbc.Connection;

/**
 * Servlet implementation class LoginServlet
 */
//如果在web.xml中声明过servlet 就把这一句注释掉
//@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        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
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		
		//mysql数据库驱动
		String driver = "com.mysql.jdbc.Driver";
		//链接数据库的url test为数据库名
		String url = "jdbc:mysql://127.0.0.1:3306/test";
		//数据库用户
		String user = "root";
		//数据库密码/在这里输入数据库密码
		String password = "123456";
		
		//从前台读取到的用户名
		String username = request.getParameter("username");
		//从前台读取到的密码
		String pwd = request.getParameter("pwd");
		
		//数据库链接成功时返回的实例
		Connection conn = null;
		//查询成功时返回的记录集
		ResultSet rs = null;
		try{
			//加载驱动
			Class.forName(driver);
			//获取链接
			conn = (Connection) DriverManager.getConnection(url, user, password);
			//准备sql查询
			String sql = "select * from User where username=? and pwd=?";
			//使用PreparedStatement,可以防止sql注入
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, username);
			ps.setString(2, pwd);
			//执行查询,返回记录集 
			rs = ps.executeQuery();
			//如果查询到用户名和密码,则允许用户登录
			if (rs.next()){
				System.out.println("login ok!!");
				PrintWriter out = response.getWriter();
				out.flush();
				out.println("<script>");
				out.println("alert('恭喜,登录成功');");
				out.println("history.back();");
				out.println("</script>");
				out.close();
			}else{
				System.out.println("login fail!!");
				PrintWriter out = response.getWriter();
				out.flush();
				out.println("<script>");
				out.println("alert('很遗憾,用户名或密码错误');");
				out.println("history.back();");
				out.println("</script>");
				out.close();
			}
			//关闭PreparedStatement
			ps.close();
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			//最后一定要关闭链接
			if (conn != null){
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(rs != null){
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		doGet(request, response);
	}

}

web.xml配置文件: 用于配置写好的servlet, 如果servlet中有 @WebServlet("/LoginServlet")则不用再配置,否则会产生错误。

<?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>mysqlTest</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>
	    <description></description>
	    <display-name>LoginServlet</display-name>
	    <servlet-name>LoginServlet</servlet-name>
	    <servlet-class>com.test.LoginServlet</servlet-class>
    </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
</web-app>


源码下载:http://download.csdn.net/detail/yanglong_blog_/9880035

  • 7
    点赞
  • 79
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
要实现一个简单JavaWeb登陆界面,你需要完成以下步骤: 1. 创建一个JavaWeb项目并配置好相关的环境和依赖。 2. 在项目创建一个JSP页面用于展示登陆界面,例如login.jsp。 3. 在login.jsp页面添加用户名和密码的输入框,以及一个提交按钮。 4. 创建一个Servlet类用于处理登陆请求,例如LoginServlet。 5. 在LoginServlet获取用户输入的用户名和密码,然后对其进行验证。 6. 如果用户名和密码验证通过,则将用户信息保存在Session,并跳转到登陆成功页面;否则返回登陆失败页面。 下面是一个简单的登陆界面的示例代码: login.jsp: ```html <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>登陆</title> </head> <body> <h1>登陆界面</h1> <form action="login" method="post"> <label>用户名:</label> <input type="text" name="username"><br> <label>密码:</label> <input type="password" name="password"><br> <input type="submit" value="登陆"> </form> </body> </html> ``` LoginServlet: ```java @WebServlet("/login") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); if ("admin".equals(username) && "123".equals(password)) { // 用户名密码验证通过 HttpSession session = request.getSession(); session.setAttribute("username", username); response.sendRedirect("/success.jsp"); } else { // 用户名密码验证失败 response.sendRedirect("/fail.jsp"); } } } ``` 在上面的代码,我们使用了@WebServlet注解来标注Servlet类的访问路径,这样当用户在登陆界面点击提交按钮时,就会向LoginServlet发出POST请求,LoginServlet会获取用户名和密码并进行验证,如果验证通过就将用户信息保存在Session,然后跳转成功页面;否则跳转到失败页面。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

longger_yang

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值