部落格新增與檢視的功能實現
阿新 • • 發佈:2020-11-28
一、準備工作
1.建立表
create table blog(id int primary key auto_increment,title varchar(100),content varchar(255),url varchar(255),created bigint);
2.建立工程(使用軟體IDEA)
a.建立maven工程,骨架為webapp,命名為blog_servlet
b.pom.xml檔案中新增相關依賴,連線資料庫依賴,資料庫連線池,Thymeleaf 模板引擎
c.配置Tomcat,並新增相關jar包
d.建立相關資料夾java和resource
e.並將jdbc.properties檔案放到resource資料夾中
/*jdbc.properties內程式碼*/ db.driver=com.mysql.cj.jdbc.Driver db.url=jdbc:mysql://localhost:3306/這裡存放自己的資料庫名稱?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true db.username=這裡是資料庫使用者名稱稱 db.password=這裡是資料庫密碼 db.maxActive=10 db.initialSize=2
二、程式碼工作(utils包中的DButils類資料庫工具類和ThUtils類模板引擎物件類在文章末尾)
1.釋出部落格功能的實現
a.先建立一個部落格釋出頁面(簡易版)
建立send,html頁面,在裡面準備form表單,提供檔案上傳功能,請求方式為post,並設定編碼型別
<!-- 檔案上傳必須使用post請求,而且需要新增enctype編碼型別 --> <h3>釋出部落格</h3> <form action="send" method="post" enctype="multipart/form-data"> 標題: <input type="text" name="title"><br> 內容: <input type="text" name="context"><br> 圖片: <input type="file" name="pic"><br> <input type="submit" value="釋出文章"> </form>
b.建立SendServlet,處理路徑為/send,在doPost方法中獲取傳遞的引數,並獲取上傳的檔案
package cn.tedu.controller; import cn.tedu.dao.BlogDao; import cn.tedu.entity.Blog; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import java.io.File; import java.io.IOException; import java.util.UUID; //如果處理檔案上傳,在servlet中必須新增一下註解,作用是對應頁面中的編碼型別 @MultipartConfig @WebServlet(name = "SendServlet" , urlPatterns = "/send") public class SendServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //在post請求中必須設定字符集 request.setCharacterEncoding("UTF-8"); //獲取傳遞引數 String title = request.getParameter("title"); String content = request.getParameter("content"); //測試是否獲取成功 System.out.println(title+":"+content); /* part 檔案上傳API HttpServletRequest 提供了兩個方法用於從請求中解析上傳的檔案: Part getPart(String name): 用於獲取請求中指定name的檔案 Coolection< Part > getParts();獲取請求中全部的檔案 每一個檔案用 javax.servlet.http.Part 物件來表示,該介面提供了很多處理檔案的方法 */ //獲取上傳檔案 Part part = request.getPart("pic"); //獲取檔案上傳資訊 String info = part.getHeader("content-disposition"); //驗證:form-data;name="pic";filename="上傳檔案的名字.型別" System.out.println(info); //得到檔案的型別獲取.後的檔案 String type = info.substring(info.lastIndexOf("."),info.length()-1); System.out.println(type); //設定上傳檔案唯一名字 //UUID.randomUUID()功能,獲取唯一標識 String filename = UUID.randomUUID()+type; //驗證 System.out.println(filename); //檔案儲存 //儲存路徑必須為tomcat管轄範圍內的路徑:原因是需要從html頁面中訪問此檔案 //得到路徑 String path = request.getServletContext().getRealPath("text/"); //驗證 System.out.println(path); //把指定的資料夾創建出來 //mkdirs()建立資料夾 new File(path).mkdirs(); //儲存上傳檔案 將獲取的path+filename寫入part 的路徑 part.write(path+filename); System.out.println("檔案儲存完成"); //把部落格資訊封裝到部落格物件中 Blog blog = new Blog(0,title,content, "text/"+filename,System.currentTimeMillis()); BlogDao dao = new BlogDao(); dao.insert(blog); //重新定向到頁面 response.sendRedirect("/findall"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
c.先建立Blog在其中定義Blog相關屬性,再實現dao裡面的insert方法
package cn.tedu.entity; public class Blog { private int id; private String title; private String content; private String url; private long created; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public long getCreated() { return created; } public void setCreated(long created) { this.created = created; } public Blog(int id, String title, String content, String url, long created) { this.id = id; this.title = title; this.content = content; this.url = url; this.created = created; } @Override public String toString() { return "Blog{" + "id=" + id + ", title='" + title + '\'' + ", content='" + content + '\'' + ", url='" + url + '\'' + ", created=" + created + '}'; } }
package cn.tedu.dao; import cn.tedu.entity.Blog; import cn.tedu.utils.DBUtils; import java.sql.Connection; import java.sql.PreparedStatement; public class BlogDao { //增 public void insert(Blog blog) { //獲取連線(資料庫連線) try(Connection connection = DBUtils.getConn()){ String sql = "insert into blog values(null,?,?,?,?)"; PreparedStatement ps = connection.prepareStatement(sql); ps.setString(1,blog.getTitle()); ps.setString(2,blog.getContent()); ps.setString(3,blog.getUrl()); ps.setLong(4,blog.getCreated()); ps.executeUpdate(); System.out.println("儲存完成"); }catch (Exception e){ e.printStackTrace(); } } }
二、部落格列表頁面
a.建立FindAllServlet,處理路徑為/findall ,的doGet方法中建立BlogDao 並呼叫findAll方法 返回值為List集合裡面裝著多個Blog物件,將集合裝進Context容器中, 通過模板引擎工具類將list.html頁面和容器中的資料整合到一起返回給客戶端
package cn.tedu.controller; import cn.tedu.dao.BlogDao; import cn.tedu.entity.Blog; import cn.tedu.utils.ThUtils; import org.thymeleaf.context.Context; 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.util.List; @WebServlet(name = "FindAllServlet",urlPatterns = "/findall") public class FindAllServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BlogDao dao = new BlogDao(); List<Blog> list = dao.findAll(); Context context = new Context(); context.setVariable("list",list); ThUtils.print("list.html",context,response); } }
b.實現dao裡面的findall方法
//部分程式碼 public List<Blog> findAll() { ArrayList<Blog> list = new ArrayList<>(); //獲取連線(資料庫連線) try(Connection connection = DBUtils.getConn()){ String sql = "select * from blog"; Statement statement = connection.createStatement(); ResultSet resultset = statement.executeQuery(sql); while (resultset.next()){ int id = resultset.getInt(1); String title = resultset.getString(2); String content = resultset.getString(3); String url = resultset.getString(4); long created = resultset.getLong(5); list.add(new Blog(id,title,content,url,created)); } }catch (Exception e){ e.printStackTrace(); } return list; }
c.建立list.html頁面在頁面中通過Thymeleaf提供的語法 把容器context裡面的集合遍歷 並顯示,(此頁面在資料夾resource下存放不完整程式碼頁面)
<!DOCTYPE html> <html lang="en" xmlns:th="http:www/thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!-- 遍歷容器中集合 --> <div th:each="b:${list}"> <!--把遍歷blog物件中的內容取出顯示在標籤裡面--> <h3 th:text="${b.title}">標題</h3> <p th:text="${b.content}">內容</p> <img width="100" alt="" th:src="${b.url}"> <span th:text="${b.createdStr}"></span> <hr> </div> </body> </html>