基於jsp和servlet簡單的java web開發(idea)

弋刀刀發表於2020-11-14

這裡伺服器用的是mysql與Tomcat。
首先就是來建立一個web專案,然後我先在src下面建立了4個包。分別是controller,dao,entity,until.這些不同的包裡面放著不同功能的封裝類。
1.jpg
Util包裡面放著的就是與mysql資料庫的連線類。我們的web的資料都存在於mysql庫裡,所以肯定要進行客戶端與資料庫資料的互動。通過這個類我們就可以與資料庫進行連線。封裝好連線方法類,可以直接呼叫
2.jpg
貼一波原始碼:

package util;
import java.sql.*;
public class Util {
    final String URL="jdbc:mysql://localhost:3306/boke?useUnicode=true&characterEncoding=UTF-8";
    final String USERNAME="***";
    final String PASSWORD="****";
    Connection con=null;
    PreparedStatement ps=null;

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }

    public Connection getCon(){

        try {
            con= DriverManager.getConnection(URL,USERNAME,PASSWORD);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return con;
    }

    public PreparedStatement creatStatement(String sql){
        try {
            ps=getCon().prepareStatement(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return ps;

    }

    public void close(){
        if (ps!=null){
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(con!=null){
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

    public void close(ResultSet rs){
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        close();
    }

}

Entity包裡放資料庫具體表表單的實體類。例如我的mysql裡面的article表單
3.jpg
在我的article實體類中就會有對應的屬性,set與get方法。
再來一手原始碼:

package entity;

import java.util.Date;

public class Article {
    private Integer liker;
    private Integer articleID;
    private Integer userID;
    private String author;
    private String title;
    private String paper;
    private Date times;

    public Integer getLiker() {
        return liker;
    }

    public void setLiker(Integer liker) {
        this.liker = liker;
    }

    public Integer getArticleID() {
        return articleID;
    }

    public void setArticleID(Integer articleID) {
        this.articleID = articleID;
    }

    public Integer getUserID() {
        return userID;
    }

    public void setUserID(Integer userID) {
        this.userID = userID;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPaper() {
        return paper;
    }

    public void setPaper(String paper) {
        this.paper = paper;
    }

    public Date getTimes() {
        return times;
    }

    public void setTimes(Date times) {
        this.times = times;
    }

    public Article(Integer liker, Integer userID, String author, String title, String paper) {
        this.liker = liker;
        this.userID = userID;
        this.author = author;
        this.title = title;
        this.paper = paper;
    }

    public Article() {
    }
}

Dao包裡面放的就是表單的操作類,在裡面封裝例如增,刪,改,查的方法。

首先在在dao類要連線資料庫,這樣才能真正實現對資料庫的表單的操作,這個時候util類就排上用場了。先建立一手util類,然後你就可以寫增刪改查對應的封裝方法了。
下面以增為例貼一段程式碼。

 private Util util = new Util();

    public int Insert(Article article) {
        int result = 0;
        String sql = ("insert into article(articleID,userID,author,title,paper,liker,times) values (NULL,?,?,?,?,?,NOW())");
        PreparedStatement ps = util.creatStatement(sql);
        try {
            ps.setInt(1, article.getUserID());
            ps.setString(2, article.getAuthor());
            ps.setString(3, article.getTitle());
            ps.setString(4, article.getPaper());
            ps.setInt(5, article.getLiker());
            result = ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            util.close();
        }
        return result;
    }

要想看懂上面的程式碼你首先要知道運算元據庫是要用SQL語言的。上面的sql字串就是對資料庫插入的SQL操作。Try後面就是將你要增加的資料按照表單的格式儲存。

Servlet包裡面就是靈魂的servlet了。servlet就是呼叫之前三個包裡面的類來實現前後端的互動。首先要在xml檔案裡面配置servlet

<servlet>
        <servlet-name>articleServlet</servlet-name>
        <servlet-class>controller.articleServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>articleServlet</servlet-name>
        <url-pattern>/article/insert</url-pattern>

標籤就是給他重新命名一個新名字/article/insert.然後就方便jsp表單來提交。下面貼的就是jsp的程式碼

 <form action="/boke/article/insert" method="post">
        <div>
            <input type="text" required="required" maxlength="20" class="form-control" placeholder="Title(Limited to 20 words)" id="titlee" name="title">
        </div>
        <div>
            <textarea  placeholder="Article(Limited to 2000 words)" class="form-control" maxlength="2000" required="required" id="bodyy" name="paper"></textarea>
        </div>
        <p id="submit"><input type="submit" style="width: 100%" value="submit" class="btn btn-outline-dark" ></p>
    </form>

這樣就實現類客戶端寫好資料後點選提交按鈕就把資料提交到了對應的servlet中。然後servlet通過呼叫之前封裝的類來對提交的資料進行判斷,在符合規則的情況下將資料新增到mysql資料庫的表單。

最後來一手servlet的程式碼:

package controller;

import dao.DAO_article;
import entity.Article;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class articleServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int result=0;
        PrintWriter out=null;
        HttpSession mysession=request.getSession(true);
        DAO_article dao=new DAO_article();
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        out= response.getWriter();
        Integer liker=0,userID;
        String author,title,paper;
        title=request.getParameter("title");
        paper=request.getParameter("paper");
        author= (String) mysession.getAttribute("username");
        userID=(Integer) mysession.getAttribute("userID");
        if (userID==null||author.isEmpty()){
            out.print("<script language='javascript'>alert('未登入');window.location.href='../JSP/homepage.jsp';</script>");
        }
        Article article=new Article(liker,userID,author,title,paper);
        result=dao.Insert(article);
            if (result!=0){
                out.print("<script language='javascript'>alert('編譯成功');window.location.href='../JSP/profile%20page.jsp';</script>");
            }else {
                out.print("<script language='javascript'>alert('編譯失敗');window.location.href='../JSP/blogcreation.jsp';</script>");
            }
    }

}

——本文主要是講web開發應有的java結構,不會出現每一段程式碼詳解。(太多了)

相關文章