servlet中Java连接数据库后的基本操作

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了servlet中Java连接数据库后的基本操作相关的知识,希望对你有一定的参考价值。

servlet中Java连接数据库后的基本操作

 

  1. 在eclipse中新建一个工程:login
  2. 在Server中新建一个服务器,基本的操作不用说了,在前两天的笔记中可以找到;
  3. 需要知道数据库的用户名和密码:用户名:user.密码:yufei
  4. 需要改变的地方:

地方一:web.xml                        

   

         
   
   

<?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_2_5.xsd" id="WebApp_ID" version="2.5">

   

  <display-name>login</display-name>

   

    <welcome-file-list>

   

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

   

  </welcome-file-list>

   

 

   

   <!-- 注册servlet -->

   

 <servlet>

   

  <!-- servlet的名字 (名字可以随便取)但是约定俗成的名字是开发的servlet的名字 -->

   

    <servlet-name>LoginServlet</servlet-name>

   

      <!-- 配置servlet的包名 (不要带上后缀) -->

   

    <servlet-class>login.com.LoginServlet</servlet-class>

   

 </servlet>

   

 

   

  <!-- 映射servlet -->

   

  <servlet-mapping>

   

  <!-- 映射servlet的名字     必须和你注册的servlet的名字一样 -->

   

    <servlet-name>LoginServlet</servlet-name>

   

  <!-- 配置servlet处理的路径(路径可以随便取)但是约定俗成的名字是开发的servlet的名字 -->

   

  <url-pattern>/LoginServlet</url-pattern>

   

  </servlet-mapping>

   

</web-app>

   
   

 

地方二:在Java Resources 里面新建包和html文件比如:login.com(包),LoginServlet.java文件

 

下面是:LoginServlet.java里面的内容:

   

         
package     login.com;
import     java.io.IOException;      

import     java.io.PrintWriter;

import java.sql.Connection;   

import     java.sql.DriverManager;   

import     java.sql.PreparedStatement;

import     java.sql.ResultSet;   

import     java.sql.SQLException;

import     java.util.ArrayList;

import     java.util.List;

import     javax.servlet.ServletException;   

import     javax.servlet.http.HttpServlet;

import     javax.servlet.http.HttpServletRequest;

import     javax.servlet.http.HttpServletResponse;

public class     LoginServlet extends HttpServlet{

            @Override

   

            protected void     doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,     IOException {

                       // TODO     Auto-generated method stub

                       //处理中文的乱码

                          resp.setContentType("text/html;charset=utf-8");//响应

                       req.setCharacterEncoding("utf-8");     //请求

                          String name =     req.getParameter("username"); //username是输入框对应的name                          String pwd =     req.getParameter("pwd");                          try {   

                                   try {

                                                  //表单填写的都是字符串   

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

   

                                               Connection     connection =     DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/login",     "root", "yufei");

   

//                                             System.out.println(connection);

   

                                               String     sql = "select * from conn where name=? and pwd=? ;";

   

                                               PreparedStatement     preparedStatement = connection.prepareStatement(sql);

   

                                               System.out.println("name:"+name+"============"     +"pwd" + pwd);

                                                  preparedStatement.setString(1,     name);   

                                               preparedStatement.setString(2,     pwd);

                                                 ResultSet     re = preparedStatement.executeQuery();   

                                               PrintWriter     out = resp.getWriter();

   

                                               out.print("<h1>==========</h1>");   

                                               String     sql1 = "select * from student";

                                               PreparedStatement     sprint = connection.prepareStatement(sql1);

   

                                               ResultSet     studinf = sprint.executeQuery();

   

                                              

   

                                               while(re.next()){                                                  

   

                                                          out.print("<h1>登录成功</h1>");

   

                                                          out.print("<h5>学生的信息是:</h5>");

   

                                                         

   

                                                          while(studinf.next()){

   

                                                                      out.print("<p>学生的姓名是:"+     studinf.getString("name")+"===id号:"+studinf.getString("id")+"===性别是:"+studinf.getString("gender")+"===年龄是:"+studinf.getString("age")+"</p>");

   

                                                          }

   

                                                          return;//终止程序

   

                                               }

   

                                               out.print("<h1>登录失败</h1>");

   

                                   } catch     (SQLException e) {

   

                                               //     TODO Auto-generated catch block

   

                                               e.printStackTrace();

   

                                   }

   

                       } catch     (ClassNotFoundException e) {

   

                                   // TODO     Auto-generated catch block

   

                                   e.printStackTrace();

   

                       }

   

            }

   

           

   

            //form默认的提交方式是get

   

            @Override

   

            protected void doGet(HttpServletRequest     req, HttpServletResponse resp) throws ServletException, IOException {

   

                       // TODO     Auto-generated method stub

   

                       doPost(req,resp);

   

            }

   

}

   
   

 

地方三:在文件WebContent里面新建一个html文件,比如:login.html

 

下面是:login.html内容:

   

         
   
   

<!DOCTYPE html>

   

<html>

   

<head>

   

<meta charset="UTF-8">

   

<title>login</title>

   

</head>

   

<body>

   

    <h1>&nbsp;welcome to login</h1>

   

    <div style=‘outline:1px black solid;width:340px;  text-align: center;‘>

   

        <h1>登录页面</h1>

   

        <!--   <a href=‘HelloServer‘>获得连接</a>     -->

   

        <!-- <%=request.getContextPath()%>/ -->

   

        <form action=‘LoginServlet‘ method=‘post‘>

   

        <p>用户名:<input type=‘text‘     name=‘username‘/></p>

   

        <p>密码: <input type=‘password‘     name=‘pwd‘/></p>

   

        <button>login</button>

   

        </form>

   

    </div>

   

</body>

   

</html>

   
   

 

地方四:添加夹包-在文件夹WEB-INF的lib里面加上夹包Server和mysql

 

以上是关于servlet中Java连接数据库后的基本操作的主要内容,如果未能解决你的问题,请参考以下文章

关于JavaWeb项目中Servlet中无法创建数据库连接池问题

servlet连接mysql小程序

怎么在servlet中连接数据库?

servlet中连接数据库问题: exception java.lang.NullPointerException

java servlet在java servlet中配置数据库连接池的配置(在server.xml)

是否可以通过Servlet或类似方法将Java桌面应用程序与MySQL连接起来?