简单的MySQL数据库连接例子

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介:

1、在项目中加入MySQL对应的JDBC的驱动jar包

LoginWeb/WebRoot/WEB-INF/lib/mysql-connector-java-3.2.0-alpha-bin.jar

 

 

配置文件

 

 
  1. 代码  
  2.  
  3. <?xml version="1.0" encoding="UTF-8"?> 
  4. <web-app version="2.5"   
  5.     xmlns="http://java.sun.com/xml/ns/javaee"   
  6.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  7.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  8.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 
  9.   <servlet> 
  10.     <description>This is the description of my J2EE component</description> 
  11.     <display-name>This is the display name of my J2EE component</display-name> 
  12.     <servlet-name>LoginSvlt</servlet-name> 
  13.     <servlet-class>com.qdu.sun.LoginSvlt</servlet-class> 
  14.   </servlet> 
  15.  
  16.   <servlet-mapping> 
  17.     <servlet-name>LoginSvlt</servlet-name> 
  18.     <url-pattern>/LoginSvlt</url-pattern> 
  19.   </servlet-mapping> 
  20.   <filter> 
  21.   <filter-name>FormFilter</filter-name> 
  22.   <filter-class>com.qdu.sun.FormFilter</filter-class> 
  23.   </filter> 
  24. <filter-mapping> 
  25. <filter-name>FormFilter</filter-name> 
  26. <url-pattern>/*</url-pattern> 
  27. </filter-mapping> 
  28.   <welcome-file-list> 
  29.     <welcome-file>index.jsp</welcome-file> 
  30.   </welcome-file-list> 
  31. </web-app> 

2、前台页面login.html

 

 
  1. 代码  
  2.  
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
  4. <html> 
  5.     <head> 
  6.         <title>登录</title> 
  7.         <meta http-equiv="content-type" content="text/html; charset=GBK"> 
  8.     </head> 
  9.     <script type="text/javascript"> 
  10. // 验证输入不为空的脚本代码  
  11. function checkForm(form) {  
  12. if(form.username.value == "") {  
  13. alert("用户名不能为空!");  
  14. form.username.focus();  
  15. return false;  
  16. }  
  17. if(form.password.value == "") {  
  18. alert("密码不能为空!");  
  19. form.password.focus();  
  20. return false;  
  21. }  
  22. return true;  
  23. }  
  24. </script> 
  25.     <body> 
  26.         请登录  
  27.         <br> 
  28.         <form action="LoginSvlt" method="post" 
  29.             onsubmit="return checkForm(this);"> 
  30.             用户名:  
  31.             <input type="text" name="username"> 
  32.             <br> 
  33.             密码:  
  34.             <input type="password" name="password"> 
  35.             <br> 
  36.             <input type="submit" value="登录" name="submit1"> 
  37.             <input type="reset" value="重置" name="reset1"> 
  38.         </form> 
  39.     </body> 
  40. </html> 

3、后台处理LoginSvlt.java登录处理

 

 
  1. 代码  
  2.  
  3. package com.qdu.sun;  
  4.  
  5. import java.io.IOException;  
  6. import java.io.PrintWriter;  
  7.  
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.http.HttpServlet;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12. import javax.servlet.http.HttpSession;  
  13. import java.sql.*;  
  14.  
  15. public class LoginSvlt extends HttpServlet {  
  16.  
  17.       
  18.     private String username;  
  19.     private String password;  
  20.     public LoginSvlt() {  
  21.         super();  
  22.     }  
  23.  
  24.      
  25.        
  26.     public void destroy() {  
  27.         super.destroy(); // Just puts "destroy" string in log  
  28.         // Put your code here  
  29.     }  
  30.  
  31.     /**  
  32.      * The doGet method of the servlet. <br> 
  33.      *  
  34.      * This method is called when a form has its tag value method equals to get.  
  35.      *   
  36.      * @param request the request send by the client to the server  
  37.      * @param response the response send by the server to the client  
  38.      * @throws ServletException if an error occurred  
  39.      * @throws IOException if an error occurred  
  40.      */  
  41.       
  42.  
  43.     /**  
  44.      * The doPost method of the servlet. <br> 
  45.      *  
  46.      * This method is called when a form has its tag value method equals to post.  
  47.      *   
  48.      * @param request the request send by the client to the server  
  49.      * @param response the response send by the server to the client  
  50.      * @throws ServletException if an error occurred  
  51.      * @throws IOException if an error occurred  
  52.      */  
  53.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  54.             throws ServletException, IOException {  
  55.              username=request.getParameter("username");  
  56.              password=request.getParameter("password");  
  57.              //先定义变量,后使用和关闭  
  58.              Connection conn = null;//声明数据库连接对象  
  59.              Statement stmt = null; //声明数据库表达式对象  
  60.              ResultSet rs = null;//声明结果集对象  
  61.              try {  
  62.                  // 载入Mysql的驱动字符串  
  63.                  Class.forName("com.mysql.jdbc.Driver");  
  64.                 // 获取数据库的连接  
  65.                  conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/login", "root", "123456");   
  66.                 // 获取表达式对象实例  
  67.                  stmt = conn.createStatement();  
  68.                  rs=stmt.executeQuery("select * from user where username='"+username+"'and password='"+password+"'");  
  69.               
  70.         if(rs.next())  
  71.             {  
  72.             HttpSession session=request.getSession(true);  
  73.             session.setAttribute("username", username);  
  74.             response.sendRedirect("welcome.jsp");  
  75.             }  
  76.         else  
  77.         {  
  78.             response.sendRedirect("error.jsp");  
  79.         }  
  80.              } catch (Exception e) {  
  81.                    
  82.                  e.printStackTrace();  
  83.                  }  
  84.     }  
  85.  
  86.     /**  
  87.      * Initialization of the servlet. <br> 
  88.      *  
  89.      * @throws ServletException if an error occurs  
  90.      */  
  91.     public void init() throws ServletException {  
  92.         // Put your code here  
  93.     }  
  94.  

FormFilter.java中文处理

 

 
  1. 代码  
  2.  
  3. package com.qdu.sun;  
  4.  
  5. import java.io.IOException;  
  6. import javax.servlet.Filter;  
  7. import javax.servlet.FilterChain;  
  8. import javax.servlet.FilterConfig;  
  9. import javax.servlet.ServletException;  
  10. import javax.servlet.ServletRequest;  
  11. import javax.servlet.ServletResponse;  
  12. import javax.servlet.http.HttpServletRequest;  
  13. import javax.servlet.http.HttpServletRequestWrapper;  
  14.  
  15. public class FormFilter implements Filter {  
  16.     /**  
  17.      * Request.java 对 HttpServletRequestWrapper 进行扩充, 不影响原来的功能并能提供所 有的  
  18.      * HttpServletRequest 接口中的功能. 它可以统一的对 Tomcat 默认设置下的中文问题进行解决而只 需要用新的 Request  
  19.      * 对象替换页面中的 request 对象即可.  
  20.      */  
  21.     class Request extends HttpServletRequestWrapper {  
  22.         public Request(HttpServletRequest request) {  
  23.             super(request);  
  24.         }  
  25.  
  26.         /**  
  27.          * 转换由表单读取的数据的内码. 从 ISO 字符转到 GBK.  
  28.          */  
  29.         public String toChi(String input) {  
  30.             try {  
  31.                 byte[] bytes = input.getBytes("ISO8859-1");  
  32.                 return new String(bytes, "GBK");  
  33.             } catch (Exception ex) {  
  34.             }  
  35.             return null;  
  36.         }  
  37.  
  38.         /**  
  39.          * Return the HttpServletRequest holded by this object.  
  40.          */  
  41.         private HttpServletRequest getHttpServletRequest() {  
  42.             return (HttpServletRequest) super.getRequest();  
  43.         }  
  44.  
  45.         /**  
  46.          * 读取参数 -- 修正了中文问题.  
  47.          */  
  48.         public String getParameter(String name) {  
  49.             return toChi(getHttpServletRequest().getParameter(name));  
  50.         }  
  51.  
  52.         /**  
  53.          * 读取参数列表 - 修正了中文问题.  
  54.          */  
  55.         public String[] getParameterValues(String name) {  
  56.             String values[] = getHttpServletRequest().getParameterValues(name);  
  57.             if (values != null) {  
  58.                 for (int i = 0; i < values.length; i++) {  
  59.                     values[i] = toChi(values[i]);  
  60.                 }  
  61.             }  
  62.             return values;  
  63.         }  
  64.     }  
  65.  
  66.     public void destroy() {  
  67.     }  
  68.  
  69.     public void doFilter(ServletRequest request, ServletResponse response,  
  70.             FilterChain chain) throws IOException, ServletException {  
  71.         HttpServletRequest httpreq = (HttpServletRequest) request;  
  72.         if (httpreq.getMethod().equals("POST")) {  
  73.             request.setCharacterEncoding("GBK");  
  74.         } else {  
  75.             request = new Request(httpreq);  
  76.         }  
  77.         chain.doFilter(request, response);  
  78.     }  
  79.  
  80.     public void init(FilterConfig filterConfig) throws ServletException {  
  81.     }  

4、成功页面

 

 
  1. 代码  
  2.  
  3. <%@ page language="java" import="java.util.*" pageEncoding="gb2312"%> 
  4. <%  
  5. String path = request.getContextPath();  
  6. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  7. %> 
  8.  
  9. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
  10. <html> 
  11.   <head> 
  12.     <base href="<%=basePath%>"> 
  13.       
  14.     <title>My JSP 'MyJsp.jsp' starting page</title> 
  15.       
  16.     <meta http-equiv="pragma" content="no-cache"> 
  17.     <meta http-equiv="cache-control" content="no-cache"> 
  18.     <meta http-equiv="expires" content="0">      
  19.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
  20.     <meta http-equiv="description" content="This is my page"> 
  21.     <!--  
  22.     <link rel="stylesheet" type="text/css" href="styles.css">  
  23.     --> 
  24.  
  25.   </head> 
  26.     
  27.   <body> 
  28.     欢迎用户:${sessionScope.username}<br> 
  29.   </body> 
  30. </html> 

 

本文转自linzheng 51CTO博客,原文链接:http://blog.51cto.com/linzheng/1080838


相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
25天前
|
分布式计算 关系型数据库 数据处理
Dataphin常见问题之没有建表的权限如何解决
Dataphin是阿里云提供的一站式数据处理服务,旨在帮助企业构建一体化的智能数据处理平台。Dataphin整合了数据建模、数据处理、数据开发、数据服务等多个功能,支持企业更高效地进行数据治理和分析。
|
1月前
|
SQL 关系型数据库 MySQL
2024年阿里云数据库创建_数据库账号密码和连接教程
阿里云数据库怎么使用?阿里云百科整理阿里云数据库从购买到使用全流程,阿里云支持MySQL、SQL Server、PostgreSQL和MariaDB等数据库引擎,阿里云数据库具有高可用、高容灾特性,阿里云提供数据库备份、恢复、迁移全套解决方案。详细阿里云数据库购买和使用流程方法如下
|
1月前
|
关系型数据库 MySQL 数据库连接
连接和管理RDS
连接和管理RDS
24 2
|
1月前
|
数据采集 Java 关系型数据库
Java代码高效连接数据库
Java代码高效连接数据库
18 2
|
28天前
|
SQL 关系型数据库 MySQL
阿里云MySQL数据库价格、购买、创建账号密码和连接数据库教程
阿里云数据库使用指南:购买MySQL、SQL Server等RDS实例,选择配置和地区,完成支付。创建数据库和账号,设置权限。通过DMS登录数据库,使用账号密码访问。同地域VPC内的ECS需将IP加入白名单以实现内网连接。参考链接提供详细步骤。
367 3
|
4天前
|
SQL 关系型数据库 MySQL
DQL语言之连接查询(mysql)
DQL语言之连接查询(mysql)
|
5天前
|
JavaScript 关系型数据库 MySQL
❤Nodejs 第二章(Node连接本地数据库)
【4月更文挑战第2天】本文介绍了如何使用Node.js连接本地MySQL数据库。首先,提到了在MySQL官网下载安装数据库和使用Navicat for MySQL进行数据库管理。接着,通过`yarn add mysql`在项目中安装数据库依赖。然后,创建`app.js`文件,设置数据库连接参数,并建立连接进行查询操作。遇到导入模块的错误后,修改导入方式为CommonJS语法。
19 1
|
7天前
|
SQL 监控 关系型数据库
PG数据库释放闲置连接
PG数据库释放闲置连接
13 0
|
7天前
|
关系型数据库 MySQL 数据安全/隐私保护
MySQL 安装及连接
MySQL 安装及连接
25 0
|
16天前
|
存储 关系型数据库 MySQL
MySQL 查询优化:提速查询效率的13大秘籍(避免使用SELECT *、分页查询的优化、合理使用连接、子查询的优化)(上)
MySQL 查询优化:提速查询效率的13大秘籍(避免使用SELECT *、分页查询的优化、合理使用连接、子查询的优化)(上)