天天看點

簡單的MySQL資料庫連接配接例子

1、在項目中加入MySQL對應的JDBC的驅動jar包

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

配置檔案

代碼  

<?xml version="1.0" encoding="UTF-8"?> 

<web-app version="2.5"   

    xmlns="http://java.sun.com/xml/ns/javaee"   

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   

    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 

  <servlet> 

    <description>This is the description of my J2EE component</description> 

    <display-name>This is the display name of my J2EE component</display-name> 

    <servlet-name>LoginSvlt</servlet-name> 

    <servlet-class>com.qdu.sun.LoginSvlt</servlet-class> 

  </servlet> 

  <servlet-mapping> 

    <url-pattern>/LoginSvlt</url-pattern> 

  </servlet-mapping> 

  <filter> 

  <filter-name>FormFilter</filter-name> 

  <filter-class>com.qdu.sun.FormFilter</filter-class> 

  </filter> 

<filter-mapping> 

<filter-name>FormFilter</filter-name> 

<url-pattern>/*</url-pattern> 

</filter-mapping> 

  <welcome-file-list> 

    <welcome-file>index.jsp</welcome-file> 

  </welcome-file-list> 

</web-app> 

2、前台頁面login.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 

<html> 

    <head> 

        <title>登入</title> 

        <meta http-equiv="content-type" content="text/html; charset=GBK"> 

    </head> 

    <script type="text/javascript"> 

// 驗證輸入不為空的腳本代碼  

function checkForm(form) {  

if(form.username.value == "") {  

alert("使用者名不能為空!");  

form.username.focus();  

return false;  

}  

if(form.password.value == "") {  

alert("密碼不能為空!");  

form.password.focus();  

return true;  

</script> 

    <body> 

        請登入  

        <br> 

        <form action="LoginSvlt" method="post" 

            onsubmit="return checkForm(this);"> 

            使用者名:  

            <input type="text" name="username"> 

            <br> 

            密碼:  

            <input type="password" name="password"> 

            <input type="submit" value="登入" name="submit1"> 

            <input type="reset" value="重置" name="reset1"> 

        </form> 

    </body> 

</html> 

3、背景處理LoginSvlt.java登入處理

package com.qdu.sun;  

import java.io.IOException;  

import java.io.PrintWriter;  

import javax.servlet.ServletException;  

import javax.servlet.http.HttpServlet;  

import javax.servlet.http.HttpServletRequest;  

import javax.servlet.http.HttpServletResponse;  

import javax.servlet.http.HttpSession;  

import java.sql.*;  

public class LoginSvlt extends HttpServlet {  

    private String username;  

    private String password;  

    public LoginSvlt() {  

        super();  

    }  

    public void destroy() {  

        super.destroy(); // Just puts "destroy" string in log  

        // Put your code here  

    /**  

     * The doGet method of the servlet. <br> 

     *  

     * This method is called when a form has its tag value method equals to get.  

     *   

     * @param request the request send by the client to the server  

     * @param response the response send by the server to the client  

     * @throws ServletException if an error occurred  

     * @throws IOException if an error occurred  

     */  

     * The doPost method of the servlet. <br> 

     * This method is called when a form has its tag value method equals to post.  

    public void doPost(HttpServletRequest request, HttpServletResponse response)  

            throws ServletException, IOException {  

             username=request.getParameter("username");  

             password=request.getParameter("password");  

             //先定義變量,後使用和關閉  

             Connection conn = null;//聲明資料庫連接配接對象  

             Statement stmt = null; //聲明資料庫表達式對象  

             ResultSet rs = null;//聲明結果集對象  

             try {  

                 // 載入Mysql的驅動字元串  

                 Class.forName("com.mysql.jdbc.Driver");  

                // 擷取資料庫的連接配接  

                 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/login", "root", "123456");   

                // 擷取表達式對象執行個體  

                 stmt = conn.createStatement();  

                 rs=stmt.executeQuery("select * from user where username='"+username+"'and password='"+password+"'");  

        if(rs.next())  

            {  

            HttpSession session=request.getSession(true);  

            session.setAttribute("username", username);  

            response.sendRedirect("welcome.jsp");  

            }  

        else  

        {  

            response.sendRedirect("error.jsp");  

        }  

             } catch (Exception e) {  

                 e.printStackTrace();  

                 }  

     * Initialization of the servlet. <br> 

     * @throws ServletException if an error occurs  

    public void init() throws ServletException {  

FormFilter.java中文處理

import javax.servlet.Filter;  

import javax.servlet.FilterChain;  

import javax.servlet.FilterConfig;  

import javax.servlet.ServletRequest;  

import javax.servlet.ServletResponse;  

import javax.servlet.http.HttpServletRequestWrapper;  

public class FormFilter implements Filter {  

     * Request.java 對 HttpServletRequestWrapper 進行擴充, 不影響原來的功能并能提供所 有的  

     * HttpServletRequest 接口中的功能. 它可以統一的對 Tomcat 預設設定下的中文問題進行解決而隻 需要用新的 Request  

     * 對象替換頁面中的 request 對象即可.  

    class Request extends HttpServletRequestWrapper {  

        public Request(HttpServletRequest request) {  

            super(request);  

        /**  

         * 轉換由表單讀取的資料的内碼. 從 ISO 字元轉到 GBK.  

         */  

        public String toChi(String input) {  

            try {  

                byte[] bytes = input.getBytes("ISO8859-1");  

                return new String(bytes, "GBK");  

            } catch (Exception ex) {  

            return null;  

         * Return the HttpServletRequest holded by this object.  

        private HttpServletRequest getHttpServletRequest() {  

            return (HttpServletRequest) super.getRequest();  

         * 讀取參數 -- 修正了中文問題.  

        public String getParameter(String name) {  

            return toChi(getHttpServletRequest().getParameter(name));  

         * 讀取參數清單 - 修正了中文問題.  

        public String[] getParameterValues(String name) {  

            String values[] = getHttpServletRequest().getParameterValues(name);  

            if (values != null) {  

                for (int i = 0; i < values.length; i++) {  

                    values[i] = toChi(values[i]);  

                }  

            return values;  

    public void doFilter(ServletRequest request, ServletResponse response,  

            FilterChain chain) throws IOException, ServletException {  

        HttpServletRequest httpreq = (HttpServletRequest) request;  

        if (httpreq.getMethod().equals("POST")) {  

            request.setCharacterEncoding("GBK");  

        } else {  

            request = new Request(httpreq);  

        chain.doFilter(request, response);  

    public void init(FilterConfig filterConfig) throws ServletException {  

4、成功頁面

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%> 

<%  

String path = request.getContextPath();  

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  

%> 

  <head> 

    <base href="<%=basePath%>"> 

    <title>My JSP 'MyJsp.jsp' starting page</title> 

    <meta http-equiv="pragma" content="no-cache"> 

    <meta http-equiv="cache-control" content="no-cache"> 

    <meta http-equiv="expires" content="0">      

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 

    <meta http-equiv="description" content="This is my page"> 

    <!--  

    <link rel="stylesheet" type="text/css" href="styles.css">  

    --> 

  </head> 

  <body> 

    歡迎使用者:${sessionScope.username}<br> 

  </body> 

本文轉自linzheng 51CTO部落格,原文連結:http://blog.51cto.com/linzheng/1080838

下一篇: C#生成GUID