Java web

来源:互联网 发布:黑莓q10软件 编辑:程序博客网 时间:2024/06/06 08:56

MyEclipse   jdbc

1.1新建数据库连接

 

1.2


1.3新建web project

1.4添加数据库连接jar包到项目


1.5创建连接类


1.6连接编写类

package com.jiangpei.util;

 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

 

 

public class ConnectionUtil {

    //数据库的用户名

    public static String user="root";

    //密码

    public static String pwd="123456";

    //数据库连接语句

    public static String url="jdbc:mysql://localhost:3306/dbname";

    //数据库驱动

    public static String driver="com.mysql.jdbc.Driver";

    //数据库的连接方法

    //返回连接到数据库后产生的通往数据库的通道

    public static Connection getConnection(){

       Connection con=null;

       //加载数据库的连接驱动

       try {

           Class.forName(driver);

           //驱动管理器连接数据库

           con=DriverManager.getConnection(url,user,pwd);

       } catch (Exception e) {

           // TODO Auto-generatedcatch block

           e.printStackTrace();

       }

       return con;

    }

    //关闭数据库连接通道

    public static void close(Connection con){

       try {

           con.close();

       } catch (SQLException e) {

           // TODO Auto-generatedcatch block

           e.printStackTrace();

       }

    }

    //关闭从数据库返回的结果集

    public static void close(ResultSet rs){

       try {

           rs.close();

       } catch (SQLException e) {

           // TODO Auto-generatedcatch block

           e.printStackTrace();

       }

    }

    //关闭从代码通往数据库的语句

    public static void close(Statement stmt){

       try {

           stmt.close();

       } catch (SQLException e) {

           // TODO Auto-generatedcatch block

           e.printStackTrace();

       }

    }

   

}

1.7添加连接数据库的jar包和Struts2的jar包、编写web.xml


 

<?xmlversion="1.0"encoding="UTF-8"?>

<web-appversion="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>index.jsp</welcome-file>

  </welcome-file-list>

 

 

  <!--拦截器:前后台通过相同的名字联系起来-->

  <filter>

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

  <!--jar包中的用来处理的类-->

  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

  </filter>

 

  <filter-mapping>

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

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

  </filter-mapping>

</web-app>

 

0 0
原创粉丝点击