我的 Java 入门项目
我的 Java 入门项目
我入门 Java 是在2019年10月入的,当时已经学完了 C语言,因此这个入门项目只用了一个下午
工具:IDEA + MariaDB + Navicat + Tomcat + maven
SQL 文件
CREATE DATABASE `book` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; DROP TABLE IF EXISTS `employees_cn`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `employees_cn` ( `employee_id` int(11) NOT NULL AUTO_INCREMENT, `employee_name` varchar(255) COLLATE utf8_bin DEFAULT NULL, `employee_address` varchar(255) COLLATE utf8_bin DEFAULT NULL, `employee_price` int(10) DEFAULT NULL, PRIMARY KEY (`employee_id`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=utf8 COLLATE=utf8_bin ROW_FORMAT=DYNAMIC; INSERT INTO `employees_cn` VALUES (1,'张伟','北京',20000), (6,'周通','上海',17500), (14,'王飞','赣州',28000), (17,'马超','佛山',20000), (18,'刘备','抚州',15000), (20,'李兰','北京',20000), (21,'李兰妈','株洲',46000), (22,'周杰','深圳',20000), (23,'丁宁','天津',1500), (24,'张飞','上饶',25000), (25,'周杰','深圳',20000), (48,'孙红雷','哈尔滨',30000);
创建 JavaWeb 项目
新建工程后,maven会下载一些文件,没多大,大家耐心等待即可。
新建工程成功以后是下面这样的:
首先在 pom.xml 文件中 </build>
上面添加如下代码,添加完成后,等待它自己加载完成即可。
<plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <hostName>localhost</hostName> <!-- Default: localhost --> <port>8080</port> <!-- 启动端口 Default:8080 --> <path>/</path> <!-- 访问应用路径 Default: /${project.artifactId}--> <uriEncoding>UTF-8</uriEncoding> <!-- uri编码 Default: ISO-8859-1 --> </configuration> </plugin> </plugins>
编写代码
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.baidu</groupId> <artifactId>MyBlog</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>MyBlog Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.speedment.runtime/runtime-typemapper --> <dependency> <groupId>com.speedment.runtime</groupId> <artifactId>runtime-typemapper</artifactId> <version>3.2.10</version> </dependency> <!-- https://mvnrepository.com/artifact/org.teiid.connectors/translator-loopback --> <dependency> <groupId>org.teiid.connectors</groupId> <artifactId>translator-loopback</artifactId> <version>16.0.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.xmlgraphics/batik-css --> <dependency> <groupId>org.apache.xmlgraphics</groupId> <artifactId>batik-css</artifactId> <version>1.14</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>MyBlog</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <hostName>localhost</hostName> <!-- Default: localhost --> <port>8081</port> <!-- 启动端口 Default:8080 --> <path>/</path> <!-- 访问应用路径 Default: /${project.artifactId}--> <uriEncoding>UTF-8</uriEncoding> <!-- uri编码 Default: ISO-8859-1 --> </configuration> </plugin> </plugins> </build> </project>
DatabaseForBook.java
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.HashMap; import java.util.List; import java.util.Map; /** * * @author colors * @date 2019/10/26 */ public class DatabaseForBook { private final String url = "jdbc:mysql://localhost:3306/book?characterEncoding=UTF8&servertimeZone=GMT%2B8"; private final String driver = "com.mysql.jdbc.Driver"; private final String name = "root"; private final String password = "123456"; private Connection connection = null; private final List allEmployees = new ArrayList(); public void openDatabase(){ try { // 加载驱动 Class.forName(driver); connection = DriverManager.getConnection(url,name,password); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } public void addData(String name, String address , float price){ // 打开数据库 openDatabase(); try { // 操作数据库的一个sql语句 String sql = "INSERT into employees_cn (employee_name,employee_address,employee_price) VALUES (?,?,?)"; // 获取声明 PreparedStatement statement = connection.prepareStatement(sql); statement.setObject(1,name); statement.setObject(2,address); statement.setObject(3,price); // 执行你的sql statement.execute(); } catch (SQLException e) { e.printStackTrace(); } closeDatabase(); } public void deleteData(String name){ openDatabase(); String sql = "DELETE FROM employees_cn WHERE employee_name= ?"; try { PreparedStatement statement = connection.prepareStatement(sql); statement.setObject(1, name); statement.execute(); } catch (SQLException e) { e.printStackTrace(); } closeDatabase(); } public void updateData(String addreess, int price, String name){ openDatabase(); String sql = "UPDATE employees_cn set employee_address = ? , employee_price = ? WHERE employee_name = ?"; try { PreparedStatement statement = connection.prepareStatement(sql); statement.setObject(1, addreess); statement.setObject(2, price); statement.setObject(3, name); statement.execute(); } catch (SQLException e) { e.printStackTrace(); } closeDatabase(); } public List selectData() { openDatabase(); String sql = "select * from employees_cn"; try { PreparedStatement statement = connection.prepareStatement(sql); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { int id = resultSet.getInt("employee_id"); String name = resultSet.getString("employee_name"); String address = resultSet.getString("employee_address"); int price = resultSet.getInt("employee_price"); // sout System.out.println(id + " " + name + " " + address + " " + price); // 集合 Map<String, Object> employee = new HashMap<>(); employee.put("id", id); employee.put("name", name); employee.put("address", address); employee.put("price", price); allEmployees.add(employee); } return allEmployees; } catch (SQLException e) { e.printStackTrace(); } closeDatabase(); return null; } public void closeDatabase(){ if (connection !=null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
BookServlet.java
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * * @author colors * @date 2019/10/27 */ // 接受客户请求 // 返回数据给客户 public class BookServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 去查数据库 DatabaseForBook databaseForBook = new DatabaseForBook(); List allEmployees = databaseForBook.selectData(); // 将数据放到网页里 req.setAttribute("all", allEmployees); // 将网页返给用户 req.getRequestDispatcher("employee.jsp").forward(req, resp); } }
TestBook.java
import org.junit.Test; /** * Created by guoke on 2019/10/30. */ public class TestBook { @Test public void testBook(){ DatabaseForBook databaseForBook = new DatabaseForBook(); databaseForBook.addData("郭柯柯","九江",30000); } @Test public void testSelect(){ DatabaseForBook databaseForBook = new DatabaseForBook(); databaseForBook.selectData(); } @Test public void testDelete(){ DatabaseForBook databaseForBook = new DatabaseForBook(); databaseForBook.deleteData("郭柯柯"); } @Test public void testUpdate(){ DatabaseForBook databaseForBook = new DatabaseForBook(); databaseForBook.updateData("北京", 20000, "刘备"); } }
index.jsp
<html> <body> <h2>Hello World!</h2> </body> </html>
employee.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page isELIgnored="false" %> <%-- Created by IntelliJ IDEA. User: colors Date: 2019/10/27 Time: 15:53 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>部门员工表</title> </head> <body> <%-- jsp + el + jstl --%> <table border="1" cellspacing="0" align="center" > <caption><h3>部门员工表</h3></caption> <thead> <tr> <th>工号</th> <th>姓名</th> <th>住址</th> <th>工资</th> </tr> </thead> <c:forEach items="${all}" var="employee"> <tr> <td>${employee.id}</td> <td>${employee.name}</td> <td>${employee.address}</td> <td>${employee.price}</td> </tr> </c:forEach> </table> </body> </html>
web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>a</servlet-name> <servlet-class>BookServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>a</servlet-name> <url-pattern>/all</url-pattern> </servlet-mapping> </web-app>