文章目錄
介紹
- 環境
操作系統:Windows 10
技術環境:jdk13+tomcat7.0
工具:Intellij Idea - 功能
老師:添加作業,添加學生,查詢學生作業
學生:根據老師添加的作業,進行作業提交 - 項目源碼
數據庫設計
ER圖
s_homework
(id
,title
,content
,create_time
,update_time
) PRIMARY KEY (id
)school.s_student
(id
,name
,create_time
,update_time
) PRIMARY KEY (id
)s_student_homework
(id
,student_id
,homework_id
,homework_title
,homework_content
,create_time
,update_time
) PRIMARY KEY (id
)
系統設計
實現
1、創建Java EE 項目
2、編寫實體類
三個實體類,set和get方法可用快捷鍵(Alt+Insert)自動生成
3、在jdbc類中實現數據庫連接,及增、查操作
主要步驟
(1)IDEA不需要加載驅動,直接創建連接
String url = "jdbc:mysql://127.0.0.1:3306/school";
String allUrl = url+"?user=root&password=123456&useSSL=false";
Connection connection = DriverManager.getConnection(allUrl)
(2)通過connection獲取statement
Statement statement = connection.createStatement()
(3)通過statement執行sql語句(注意sql語句的寫法,不要漏掉單引號)
增:
String sqlString = "INSERT INTO s_homework (title,content,create_time) VALUES ('"
+h.getTitle()+"','"+h.getContent()+"',NOW())";
int rows=statement.executeUpdate(sqlString);
查:
String sqlString = "SELECT * FROM s_homework";
ResultSet resultSet = statement.executeQuery(sqlString);
(4) 獲取執行結果
try(ResultSet resultSet = statement.executeQuery(sqlString)){
while (resultSet.next()){
Homework h = new Homework();
h.setId(resultSet.getLong("id"));
h.setTitle(resultSet.getString("title"));
h.setContent(resultSet.getString("content"));
h.setCreateTime(resultSet.getTimestamp("create_time"));
list.add(h);
}
爲了不浪費資源,把操作移到try括號裏
以HomeworkJdbc.java爲例
- 添加作業:
public static boolean addHomework(Homework h) {
String url = "jdbc:mysql://127.0.0.1:3306/school";
String allUrl = url+"?user=root&password=123456&useSSL=false";
String sqlString = "INSERT INTO s_homework (title,content,create_time) VALUES ('"
+h.getTitle()+"','"+h.getContent()+"',NOW())";
try(Connection connection = DriverManager.getConnection(allUrl)){
try(Statement statement = connection.createStatement()){
int rows=statement.executeUpdate(sqlString);
}
} catch (SQLException e){
e.printStackTrace();
}
return true;
}
- 獲取所有作業
public static List<Homework> selectAll(){
String url = "jdbc:mysql://127.0.0.1:3306/school";
String allUrl = url+"?user=root&password=123456&useSSL=false";
String sqlString = "SELECT * FROM s_homework";
List<Homework> list = new ArrayList<>();
try(Connection connection = DriverManager.getConnection(allUrl)){
try(Statement statement = connection.createStatement()){
try(ResultSet resultSet = statement.executeQuery(sqlString)){
while (resultSet.next()){
Homework h = new Homework();
h.setId(resultSet.getLong("id"));
h.setTitle(resultSet.getString("title"));
h.setContent(resultSet.getString("content"));
h.setCreateTime(resultSet.getTimestamp("create_time"));
list.add(h);
}
}
}
} catch (SQLException e){
e.printStackTrace();
}
return list;
}
4、創建HttpServlet與瀏覽器進行交互
HttpServlet
HttpServlet首先必須讀取Http請求的內容。Servlet容器負責創建HttpServlet對象,並把Http請求直接封裝到HttpServlet對象中,大大簡化了HttpServlet解析請求數據的工作量。
HttpServlet容器響應Web客戶請求流程如下:
1)Web客戶向Servlet容器發出Http請求;
2)Servlet容器解析Web客戶的Http請求;
3)Servlet容器創建一個HttpRequest對象,在這個對象中封裝Http請求信息;
4)Servlet容器創建一個HttpResponse對象;
5)Servlet容器調用HttpServlet的service方法,把HttpRequest和HttpResponse對象作爲service方法的參數傳給HttpServlet對象;
6)HttpServlet調用HttpRequest的有關方法,獲取HTTP請求信息;
7)HttpServlet調用HttpResponse的有關方法,生成響應數據;
8)Servlet容器把HttpServlet的響應結果傳給Web客戶。
主要步驟
1)擴展HttpServlet抽象類
2)@WebServlet註解
3)覆蓋HttpServlet的覆蓋doGet()和doPost()方法
4)獲取HTTP請求信息。通過HttpServletRequest對象來檢索HTML表單所提交的數據或URL上的查詢字符串
5)傳遞request或重定向
這次項目設計了5個HttpServlet
以StudentHomeworkServlet.java爲例
@WebServlet("/studentHomework")
public class StudentHomeworkServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Long homeworkId = Long.parseLong(req.getParameter("id"));
List<StudentHomework> list;
list = StudentHomeworkJdbc.select(homeworkId);
req.setAttribute("list", list);
req.getRequestDispatcher("studentHomework.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Long homeworkId = Long.parseLong(req.getParameter("homeworkId"));
Long studentId = Long.parseLong(req.getParameter("studentId"));
List<StudentHomework> list;
list = StudentHomeworkJdbc.select(homeworkId,studentId);
req.setAttribute("list", list);
req.getRequestDispatcher("studentHomework.jsp").forward(req, resp);
}
}
5、jsp頁面及css樣式設計
JavaServer Pages(JSP)是一組技術,可幫助軟件開發人員基於HTML,XML,SOAP或其他文檔類型創建動態生成的網頁。
要部署和運行JSP,需要具有servlet容器的兼容Web服務器,例如Apache Tomcat或Jetty
教師版
教師版首頁 homework_t.jsp
添加學生 addstudent_t.jsp
發佈作業 addHomework_t.jsp
查看/查詢學生作業 studentHomework.jsp
學生版
學生版首頁 homework_s.jsp
提交作業 addStudentHomework.jsp
- css主要設計表單風格
body { padding:5px 100px; font:20px/150% Verdana, Tahoma, sans-serif; }
/* tutorial */
input, textarea {
padding: 9px;
border: solid 1px #E5E5E5;
outline: 0;
font: normal 13px/100% Verdana, Tahoma, sans-serif;
width: 200px;
background: #FFFFFF left top repeat-x;
background: -webkit-gradient(linear, left top, left 25, from(#FFFFFF), color-stop(4%, #EEEEEE), to(#FFFFFF));
background: -moz-linear-gradient(top, #FFFFFF, #EEEEEE 1px, #FFFFFF 25px);
box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
-moz-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
-webkit-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
}
textarea {
width: 400px;
max-width: 400px;
height: 150px;
line-height: 150%;
}
input:hover, textarea:hover,
input:focus, textarea:focus {
border-color: #C9C9C9;
-webkit-box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 8px;
}
.form label {
margin-left: 10px;
color: #999999;
}
.submit input {
width: auto;
padding: 9px 15px;
background: #617798;
border: 0;
font-size: 14px;
color: #FFFFFF;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
問題
java的Long.getLong(str)的NullPointerException錯誤
解決:替換成Long.parseLong(String str)
getLong(String nm) | parselong(String s) |
---|---|
Determines the long value of the system property with the specified name. | Parses the string argument as a signed decimal long |
form表單提交數據到Servlet時,中文出現亂碼問題
解決:添加語句
/*瀏覽器提交的數據在提交給服務器之前設置編碼方式爲UTF-8*/
req.setCharacterEncoding("UTF-8");
數據來源 | 默認編碼格式 |
---|---|
瀏覽器頁面 | GBK (可在瀏覽器頁面右鍵切換) |
request(get) | ISO-8859-1 |
request(post) | GBK(同瀏覽器),但是如果是服務器來的頁面一般已經設置了UTF-8(例如JSP提交的頁面) |
Servlet(response) | ISO-8859-1 |
優化:編寫數據庫連接池
package com.java.code.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
/**
*優化數據庫連接
* 實現簡單連接池
* @author:Jingqi Wu
* @date: 2020/3/15
*/
public class ConPool {
private static String url = "jdbc:mysql://127.0.0.1:3306/school";
private static String allUrl = url+"?user=root&password=123456&useSSL=false";
private static String driverName = "com.mysql.cj.jdbc.Driver";
private static int initCount = 3;
private static int maxCount = 10;
private static int currentCount = 0;
private LinkedList<Connection> connectionsPool =
new LinkedList<Connection>();
public ConPool()
{
for(; currentCount < initCount; ) {
try {
// 連接池需要加載驅動?
Class.forName(driverName);
// 通過jdbc建立數據庫連接
Connection connection = DriverManager.getConnection(allUrl);
this.connectionsPool.add(connection);
currentCount++;
} catch (SQLException | ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
}
// 從連接池中拿走一個連接
public Connection getConnection() throws SQLException{
System.out.println("currentCount:"+currentCount+";list size:"+connectionsPool.size());
synchronized (connectionsPool){
if(connectionsPool.size()>0){
return connectionsPool.removeFirst();
}
if(connectionsPool.size()< maxCount){
Connection connection = DriverManager.getConnection(allUrl);
currentCount++;
return connection;
}
}
throw new SQLException("超過最大連接");
}
// 釋放連接,把連接放到連接池
public void free(Connection connection){
this.connectionsPool.add(connection);
}
}