怎么用Servlet连接mysql数据库 给个例题

怎么用Servlet连接mysql数据库 给个例题,第1张

package com.jsp.Database

import java.sql.*

import javax.sql.*

import java.io.*

import javax.servlet.*

import javax.servlet.http.*

import com.microsoft.jdbc.sqlserver.SQLServerDriver

public class JDBCServlet extends HttpServlet

{

/* 连接数据库属性*/

String driver

String password,url,user

/*处理doGet */

public void doGet(HttpServletRequest request,HttpServletResponse response)

throws IOException,ServletException

{

response.setContentType("text/htmlcharset=gb2312")

PrintWriter out=response.getWriter()

try

{

Connection con=getConnection()

Statement stmt=con.createStatement()

ResultSet rst=stmt.executeQuery("select * from user_info")

while(rst.next())

{

out.println(rst.getString("userid"))

out.println("<br>")

}

rst.close()

stmt.close()

con.close()

}

catch(SQLException e)

{

e.printStackTrace()

}

}

/*处理doPost请求*/

public void doPost(HttpServletRequest request,HttpServletResponse response)

throws IOException,ServletException

{

doGet(request,response)

}

public void init()throws ServletException

{

driver=getInitParameter("DRIVER")

password=getInitParameter("PASSWORD")

url=getInitParameter("URL")

user=getInitParameter("USER")

}

private Connection getConnection()

{

Connection con=null

try

{

Class.forName(driver)

con=DriverManager.getConnection(url,user,password)

}

catch(Exception e )

{

e.printStackTrace()

}

return con

}

}

======== web.xml文件配置========

<servlet>

<servlet-name>JDBCServlet</servlet-name>

<servlet-class>com.jsp.Database.JDBCServlet</servlet-class>

<init-param>

<param-name>DRIVER</param-name>

<param-value>com.microsoft.jdbc.sqlserver.SQLServerDriver</param-value>

</init-param>

<init-param>

<param-name>URL</param-name>

<param-value>jdbc:jdbc:mysql://127.0.0.1:3306/数据库名</param-value>

</init-param>

<init-param>

<param-name>USER</param-name>

<param-value>用户名</param-value>

</init-param>

<init-param>

<param-name>PASSWORD</param-name>

<param-value>密码</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>JDBCServlet</servlet-name>

<url-pattern>/init_servlet</url-pattern>

</servlet-mapping>

WEB.XML在你的tomcat/webapp/你的目录/WEB-INF/下..

或者复制tomcat/webapp/ROOT/WEB-INF/下的,,做一下修改就行了.

第一步:web.xml

Java code?

<?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">

    <welcome-file-list>

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

    </welcome-file-list>

 

    <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>loginServlet</servlet-name>

        <servlet-class>com.servlet.loginServlet</servlet-class>

    </servlet>

 

    <servlet-mapping>

        <servlet-name>loginServlet</servlet-name>

        <url-pattern>/loginServlet</url-pattern>

    </servlet-mapping>

</web-app>

第二步:数据库

Java code?

/*

SQLyog Ultimate v8.32 

MySQL - 5.5.23 : Database - student

*********************************************************************

*/

 

 

/*!40101 SET NAMES utf8 */

 

/*!40101 SET SQL_MODE=''*/

 

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */

/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */

/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */

/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */

CREATE DATABASE /*!32312 IF NOT EXISTS*/`student` /*!40100 DEFAULT CHARACTER SET utf8 */

 

USE `student`

 

/*Table structure for table `user` */

 

DROP TABLE IF EXISTS `user`

 

CREATE TABLE `user` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `user` varchar(50) NOT NULL,

  `pwd` varchar(50) NOT NULL,

  `name` varchar(50) NOT NULL,

  `age` int(50) NOT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8

 

/*Data for the table `user` */

 

insert  into `user`(`id`,`user`,`pwd`,`name`,`age`) values (1,'zhangsan','123','张三',21)

 

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */

/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */

/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */

/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */

第三步:登录login.jsp

Java code?

<%@ page language="java" contentType="text/html charset=UTF-8" pageEncoding="UTF-8"%>

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

    <html>

    <head>

        <title>xx系统</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>

        <div align="center"> <font size=" 2" color="#FF6633">用户登录</font>

    </div>

    <form id="form1" name="form1" method="post" action="loginServlet">

    <table width="357" border="0" align="center">

        <tr>

          <td width="128">用户名:</td>

          <td width="219"><label>

            <input name="user" type="text" id="user" />

          </label></td>

        </tr>

        <tr>

          <td>密 码:</td>

          <td><label>

            <input name="pwd" type="password" id="pwd" />

          </label></td>

        </tr>

        <tr>

          <td><label>

            <input type="submit" name="Submit" value="登录" />

          </label></td>

          

        </tr>

    </table>

    <p>&nbsp</p>

    </form>

    </body>

    </html>

第四步:success.jsp

Java code

<%@ page language="java" contentType="text/html charset=ISO-8859-1"

    pageEncoding="ISO-8859-1"%>

<!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=ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

    ${address }</br>

    ${port }</br>

     

</body>

</html>

第五步:loginServlet.java

Java code

package com.servlet

import java.io.IOException

import java.io.PrintWriter

import java.net.InetAddress

import java.sql.SQLException

 

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 com.dao.Dao

 

public class loginServlet extends HttpServlet {

    public void destroy() {

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

 

        // Put your code here

 

    }

 

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8")

        response.setContentType("text/html")

        PrintWriter out = response.getWriter()

        String name = new String(request.getParameter("user").getBytes(

                "ISO8859_1"), "GBK")

        String pwd = new String(request.getParameter("pwd").getBytes(

                "ISO8859_1"), "UTF-8")

        User user = new User()

        user.setUser(name)

        user.setPwd(pwd)

        Dao dao = new Dao()

        boolean isLogin

        try {

            isLogin = dao.logoin(user)

 

            if (isLogin) {

                InetAddress inetAddress = InetAddress.getLocalHost()

                String m = inetAddress.getHostAddress()

                int n = request.getRemotePort()

                System.out.println(m+"*********"+ n)

                HttpSession session = request.getSession() 

                session.setAttribute("address", m)

                session.setAttribute("port", n)

                response.sendRedirect("success.jsp")

            } else {

                response.sendRedirect("index.jsp")

            }

 

        } catch (SQLException e) {

            e.printStackTrace()

        }

    }

 

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        doPost(request, response)

    }

 

    public void init() throws ServletException {

    }

 

}

Java code

package com.servlet

 

public class User {

    private String user

    private String pwd

    private String name

 

    private int age

 

    public String getUser() {

        return user

    }

 

    public void setUser(String user) {

        this.user = user

    }

 

    public String getPwd() {

        return pwd

    }

 

    public void setPwd(String pwd) {

        this.pwd = pwd

    }

 

    public String getName() {

        return name

    }

 

    public void setName(String name) {

        this.name = name

    }

 

    public int getAge() {

        return age

    }

 

    public void setAge(int age) {

        this.age = age

    }

}

Java code?

package com.util

 

import java.sql.Connection

import java.sql.DriverManager

import java.sql.SQLException

 

public class GetConnection {

    //通过静态方法注册驱动,获得连接

 

    public static Connection getConnection(){

       String driver = "com.mysql.jdbc.Driver"

       String url = "jdbc:mysql://localhost/student"

       Connection con = null

       try {

        Class.forName(driver)

        try {

         con = DriverManager.getConnection(url,"root","123456")

        } catch (SQLException e) {

         e.printStackTrace()

        }

       } catch (ClassNotFoundException e) {

        e.printStackTrace()

       }

       System.out.println("已获得数据库的连接")

       return con

    }

    /*public static void main(String args[]){

       getConnection()

    }*/

    }

Java code?

package com.dao

import java.sql.Connection

import java.sql.PreparedStatement

import java.sql.ResultSet

import java.sql.SQLException

 

import com.servlet.User

import com.util.GetConnection

 

public class Dao {

    private Connection conn

    private PreparedStatement pstat

    String sql = ""

 

    /**

     *

     * 用户登录

     */

    public boolean logoin(User user) throws SQLException {

        conn = GetConnection.getConnection()

        boolean i = false

        sql = "select * from user where user=? and pwd=?"

 

        pstat = conn.prepareStatement(sql)

 

        pstat.setString(1, user.getUser())

        pstat.setString(2, user.getPwd())

 

        ResultSet rs1 = (ResultSet) pstat.executeQuery()

        if (rs1.next()) {

            i = true

            rs1.close()

            pstat.close()

        } else {

            i = false

            rs1.close()

            pstat.close()

        }

        conn.close()

        return i

    }

 

    /**

     * 用户注册

     */

    public void addUser(User user) {

        conn = GetConnection.getConnection()

        sql = "insert into user values(?,?,?,?)"

        try {

            pstat = conn.prepareStatement(sql)

            pstat.setString(1, user.getUser())

            pstat.setString(2, user.getPwd())

            pstat.setString(3, user.getName())

 

            pstat.setInt(5, user.getAge())

            pstat.executeUpdate()

            pstat.close()

            conn.close()

 

        } catch (SQLException e) {

            e.printStackTrace()

        }

 

    }

}

注意事项:1.数据库用户密码;2.访问地址。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/sjk/6670850.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-03-26
下一篇2023-03-26

发表评论

登录后才能评论

评论列表(0条)

    保存