且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

简单的MySQL数据库连接例子

更新时间:2022-10-02 23:01:44

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