标签:
和上一次的并没胡什么不同,也就是多了一个使用ant初始化mysql数据库
D:\code\kongee\ant_web_three λ tree /f 卷 软件 的文件夹 PATH 列表 卷序列号为 000D-CD8E D:. │ .classpath │ .project │ build.xml │ studentbak.sql │ ├─.settings │ .jsdtscope │ org.eclipse.jdt.core.prefs │ org.eclipse.wst.common.component │ org.eclipse.wst.common.project.facet.core.xml │ org.eclipse.wst.jsdt.ui.superType.container │ org.eclipse.wst.jsdt.ui.superType.name │ ├─src │ └─com │ └─laolang │ ├─dao │ │ IStudentDao.java │ │ StudetDao.java │ │ │ ├─modle │ │ Student.java │ │ │ ├─servlet │ │ HelloServlet.java │ │ ShowServlet.java │ │ │ └─util │ DButil.java │ student-sql.properties │ └─WebContent │ hello.jsp │ index.jsp │ show.jsp │ ├─META-INF │ MANIFEST.MF │ └─WEB-INF │ web.xml │ └─lib mysql-connector-java-5.1.28-bin.jar D:\code\kongee\ant_web_three λ
package com.laolang.modle; public class Student { public Student() { super(); } public Student(String name, int age, String sex) { super(); this.name = name; this.age = age; this.sex = sex; } public Student(int id, String name, int age, String sex) { super(); this.id = id; this.name = name; this.age = age; this.sex = sex; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + "]"; } public int getId() { return id; } public void setId(int id) { this.id = id; } 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; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } private int id; private String name; private int age; private String sex; }
package com.laolang.dao; import java.util.List; import com.laolang.modle.Student; public interface IStudentDao { public List<Student> selectAll() ; }
package com.laolang.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.laolang.modle.Student; import com.laolang.util.DButil; public class StudetDao implements IStudentDao { @Override public List<Student> selectAll() { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; List<Student> stus = new ArrayList<Student>(); try { conn = DButil.getConnection(); String sql = "select stuid,stuname,stuage,stusex from student"; ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while( rs.next() ){ Student stu = new Student(); stu.setId(rs.getInt("stuid")); stu.setName(rs.getString("stuname")); stu.setAge(rs.getInt("stuage")); stu.setSex(rs.getString("stusex")); stus.add(stu); } } catch (SQLException e) { e.printStackTrace(); }finally{ DButil.close(rs); DButil.close(ps); DButil.close(conn); } return stus; } }
jdbc.url=jdbc:mysql://localhost:3306/student jdbc.username=root jdbc.userpassword=root jdbc.driver=com.mysql.jdbc.Driver
package com.laolang.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ResourceBundle; public class DButil { /** 数据库连接地址 */ private static String URL; /** 数据库用户名 */ private static String USERNAME; /** 数据库密码 */ private static String USERPASSWORD; /** mysql 驱动 */ private static String DRIVER; /** The rb. */ private static ResourceBundle rb = ResourceBundle .getBundle("com.laolang.util.student-sql"); /** * 使用静态代码块加载驱动 */ static { URL = rb.getString("jdbc.url"); USERNAME = rb.getString("jdbc.username"); USERPASSWORD = rb.getString("jdbc.userpassword"); DRIVER = rb.getString("jdbc.driver"); try { Class.forName(DRIVER); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { Connection con = null; con = DriverManager.getConnection(URL, USERNAME, USERPASSWORD); return con; } public static void close(Connection con) { try { if (con != null) con.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void close(PreparedStatement ps) { try { if (ps != null) ps.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void close(ResultSet rs) { try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } } }
package com.laolang.servlet; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class HelloServlet */ public class HelloServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public HelloServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("hello", "world"); RequestDispatcher dis = request.getRequestDispatcher("hello.jsp"); dis.forward(request, response); } }
package com.laolang.servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.laolang.dao.IStudentDao; import com.laolang.dao.StudetDao; import com.laolang.modle.Student; /** * Servlet implementation class ShowServlet */ public class ShowServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ShowServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { IStudentDao dao = new StudetDao(); List<Student> stus = dao.selectAll(); for( Student stu : stus ){ System.out.println(stu); } request.setAttribute("stus", stus); request.getRequestDispatcher("show.jsp").forward(request, response); } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>Insert title here</title> </head> <body> This is a jsp page! <br /> <a href="hello.do">hello</a> <br /> <a href="show.do">show</a> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>Insert title here</title> </head> <body> <h1>Hello:${hello }</h1> </body> </html>
<%@page import="java.util.List"%> <%@page import="com.laolang.modle.Student"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>Insert title here</title> </head> <body> <table border="1"> <tr> <th>学号</th> <th>姓名</th> <th>年龄</th> <th>性别</th> </tr> <% //@SuppressWarnings("unchecked") List<Student> stus = (List<Student>)request.getAttribute("stus"); for( Student stu : stus){ %> <tr> <td><%=stu.getId() %></td> <td><%=stu.getName() %></td> <td><%=stu.getAge() %></td> <td><%=stu.getSex() %></td> </tr> <% } %> </table> </body> </html>
/* SQLyog Ultimate v11.11 (64 bit) MySQL - 5.5.38 : 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 `student` */ DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `stuid` int(11) NOT NULL AUTO_INCREMENT, `stuname` varchar(20) DEFAULT NULL, `stuage` int(11) DEFAULT NULL, `stusex` varchar(2) DEFAULT NULL, PRIMARY KEY (`stuid`) ) ENGINE=InnoDB AUTO_INCREMENT=1006 DEFAULT CHARSET=utf8; /*Data for the table `student` */ insert into `student`(`stuid`,`stuname`,`stuage`,`stusex`) values (1001,‘xiaodaima‘,24,‘男‘),(1002,‘小叶子‘,25,‘女‘),(1003,‘老狼‘,34,‘男‘),(1004,‘龙女‘,43,‘女‘),(1005,‘天涯‘,18,‘男‘); /*insert into `student`(`stuid`,`stuname`,`stuage`,`stusex`) values (1001,‘小代码‘,24,‘男‘),(1002,‘小叶子‘,25,‘女‘),(1003,‘老狼‘,34,‘男‘),(1004,‘龙女‘,43,‘女‘),(1005,‘天涯‘,18,‘男‘);*/ /*!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 */;
<?xml version="1.0" encoding="UTF-8"?> <project name="ant_web_hello"> <!-- java源代码目录 --> <property name="src.dir" location="src" /> <!-- 构建目录 --> <property name="build.dir" location="build" /> <!-- class文件目录 --> <property name="build.classes" location="${build.dir}/classes" /> <!-- 打包目录 --> <property name="build.war" location="${build.dir}/war" /> <!-- tomcat根目录 --> <property name="tomcat.home" location="D:\program\program\java\tomcat\tomcat" /> <!-- <property name="tomcat.lib" location="${tomcat.home}/lib" /> --> <!-- web 应用的名字,也是打包后war的名字 --> <property name="web.name" value="anthello2" /> <!-- web 根目录 --> <property name="web.root" value="webContent" /> <property name="web.WEB-INF" location="${web.root}/WEB-INF" /> <property name="web.lib" location="${web.WEB-INF}/lib" /> <property name="mysqldriver" location="${web.lib}/mysql-connector-java-5.1.28-bin.jar" /> <!-- 加载环境变量 --> <property environment="env" /> <!-- 定义编译时的classpath --> <path id="compile.path"> <fileset dir="${web.lib}" includes="*.lib"> </fileset> <fileset dir="${env.tomcat_home}/lib"> <include name="*.jar" /> </fileset> </path> <target name="init" description="初始化"> <mkdir dir="${build.dir}" /> <mkdir dir="${build.classes}" /> <mkdir dir="${build.war}" /> <echo>初始化工作结束!</echo> </target> <target name="compile" depends="init" description="编译"> <javac destdir="build/classes" srcdir="src" includeantruntime="false" fork="true"> <compilerarg line="-encoding UTF-8 " /> <classpath refid="compile.path" /> </javac> <echo message="编译完成!" /> </target> <target name="war" depends="compile" description="打包war文件"> <war destfile="${build.war}/${web.name}.war"> <fileset dir="${web.root}" includes="**/*.*" /> <lib dir="${web.lib}" /> <webinf dir="${web.WEB-INF}" /> <classes dir="${build.classes}" /> </war> <echo>打包完成!</echo> </target> <!-- 此处有问题,如果使用classpath refid="compile.path" 会提示 Class Not Found: JDBC driver com.mysql.jdbc.Driver could not be loaded <presetdef name="sql-admin"> <sql userid="root" password="root" url="jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf-8" driver="com.mysql.jdbc.Driver"> <classpath refid="compile.path"> </classpath> </sql> </presetdef> --> <presetdef name="mysql-admin"> <sql userid="root" password="root" url="jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf-8" driver="com.mysql.jdbc.Driver" classpath="${mysqldriver}" print="true" encoding="utf-8"> </sql> </presetdef> <target name="mysql-init" description="初始化数据库"> <mysql-admin> <transaction src="studentbak.sql" /> </mysql-admin> <echo>数据库初始化完成!</echo> </target> <target name="mysql-test" depends="mysql-init" description="数据库测试"> <mysql-admin> <transaction> use student; select database(); show tables; select * from student; </transaction> </mysql-admin> <echo>数据库测试完成!</echo> </target> <target name="testenv" description="测试环境变量"> <echo>JAVA_HOME:${env.JAVA_HOME}</echo> <echo>CLASSPATH:${env.CLASSPATH}</echo> <echo>tomcat_home:${env.tomcat_home}</echo> <echo>${web.lib}</echo> <echo>${mysqldriver}</echo> </target> <target name="deploy" depends="mysql-test,war" description="发布"> <copy todir="${env.tomcat_home}/webapps"> <fileset dir="${build.war}" includes="*.war" /> </copy> <echo>已发布到Tomcat!</echo> </target> <target name="clean" description="清理"> <delete dir="${build.dir}" /> <delete dir="${env.tomcat_home}/webapps/${web.name}" /> <delete file="${env.tomcat_home}/webapps/${web.name}.war" /> <echo>清理完成!</echo> </target> </project>
D:\code\kongee\ant_web_two>ant deploy Buildfile: D:\code\kongee\ant_web_two\build.xml mysql-init: [mysql-admin] Executing resource: D:\code\kongee\ant_web_two\studentbak.sql [mysql-admin] 0 rows affected [mysql-admin] 0 rows affected [mysql-admin] 0 rows affected [mysql-admin] 0 rows affected [mysql-admin] 0 rows affected [mysql-admin] 0 rows affected [mysql-admin] 1 rows affected [mysql-admin] 0 rows affected [mysql-admin] 0 rows affected [mysql-admin] 0 rows affected [mysql-admin] 5 rows affected [mysql-admin] 0 rows affected [mysql-admin] 0 rows affected [mysql-admin] 0 rows affected [mysql-admin] 0 rows affected [mysql-admin] 15 of 15 SQL statements executed successfully [echo] 数据库初始化完成! mysql-test: [mysql-admin] Executing commands [mysql-admin] 0 rows affected [mysql-admin] database() [mysql-admin] student [mysql-admin] [mysql-admin] 0 rows affected [mysql-admin] TABLE_NAME [mysql-admin] student [mysql-admin] [mysql-admin] 0 rows affected [mysql-admin] stuid,stuname,stuage,stusex [mysql-admin] 1001,xiaodaima,24,男 [mysql-admin] 1002,小叶子,25,女 [mysql-admin] 1003,老狼,34,男 [mysql-admin] 1004,龙女,43,女 [mysql-admin] 1005,天涯,18,男 [mysql-admin] [mysql-admin] 0 rows affected [mysql-admin] 4 of 4 SQL statements executed successfully [echo] 数据库测试完成! init: [mkdir] Created dir: D:\code\kongee\ant_web_two\build [mkdir] Created dir: D:\code\kongee\ant_web_two\build\classes [mkdir] Created dir: D:\code\kongee\ant_web_two\build\war [echo] 初始化工作结束! compile: [javac] Compiling 6 source files to D:\code\kongee\ant_web_two\build\classes [echo] 编译完成! war: [war] Building war: D:\code\kongee\ant_web_two\build\war\anthello.war [echo] 打包完成! deploy: [copy] Copying 1 file to D:\program\program\java\tomcat\tomcat\webapps [echo] 已发布到Tomcat! BUILD SUCCESSFUL Total time: 6 seconds D:\code\kongee\ant_web_two>
index.jsp
hello.do
show.do
修改studentbak.sql将xiaodaima修改为小代码
由于使用ant时构建目录在build,而eclipse的class存放目录也是在build,所以每次使用ant进行部署时,必须在eclipse中进行project->clean操作才可以,否则出现下面的错误
我不理解这到底是为什么,如果说是由于eclipse自动编译的class文件的问题,那么为什么HelloServlet就没有问题?
PS:这里说的clean是指:在进行ant deploy之前,必须要clean,且clean后不能在eclipse中进行任何操作,否则要再次clean,不然还是会出现上图中的错误,我修改了ant的构建目录后,依然不行,这个问题让我很不解,有哪个高手指点下?
使用ant进行mysql操作的时候,不能使用path定义的classpath,也就是说在sql中不能使用classpathref,而应该使用property指向mysql的jar包的相对路径,再在sql中使用classpath引用 这个property,否则会出现Class Not Found: JDBC driver com.mysql.jdbc.Driver could not be loaded
如果想要显示sql的执行结果,可以将print指定为true
标签:
原文地址:http://my.oschina.net/iamhere/blog/526750