idea中Javaweb链接数据库

第一步首先我们当然要创建Javaweb的项目在这里插入图片描述
创建好了以后在web-inf目录下创建两个director分别叫classes和lib,其中classes是存放src中类编译好的字节码文件,而lib则是存放连接器jar包的地方。因为在实际项目中服务器并不会是客户端,所以tomcat也必须知道数据库在哪里,这就是lib的用途。External Libraries只是客户端所添加的依赖。
当然如果想字节码输出到classes中还是需要配置的方法如下,点击红色区域
在这里插入图片描述
path中设置输出路径在这里插入图片描述
dependencies中也需要添加相关的依赖
在这里插入图片描述
完成好以上步骤后别忘了把连接器的jar包copy到lib下。
接下来就是代码部分了

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet(name = "DataTest")
public class DataTest extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        response.setContentType("text/html;set=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<table border=1>");
        out.println("<tr><td>Content:</td></tr>");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql:///mydata?useSSL=true","root","root");
            stmt = conn.createStatement();
            rs = stmt.executeQuery("select * from  article");
            while (rs.next()) {
                out.println("<tr>");
                out.println("<td>" + rs.getString("title") + "</td>");
                out.println("</tr>");
            }
            out.println("</table>");
        } catch (ClassNotFoundException e) {
            out.println("class not found");
            e.getStackTrace();
        } catch (SQLException e) {
           out.println("SQL EXCEPTION");
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs = null;
                    rs.close();
                }
                if (stmt != null) {
                    stmt = null;
                    stmt.close();
                }
            } catch (Exception e) {
            }
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

写完代码别忘了在web.xml中配置

    <servlet>
        <servlet-name>DataTest</servlet-name>
        <servlet-class>DataTest</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DataTest</servlet-name>
        <url-pattern>/DataTest</url-pattern>
    </servlet-mapping>

完成这些步骤后我们就能直接用网页访问啦~

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页