Java?Servlet實現(xiàn)表白墻的代碼實例
一、表白墻簡介
在表白墻頁面中包含三個文本框,分別表示表白者,表白對象,表白內容,在文本框中輸入內容之后,內容能夠保存,并且在下次啟動頁面的時候也能顯示出之前所保存的內容。
二、代碼實現(xiàn)
1、約定前后端交互的接口
要實現(xiàn)表白墻,首先就需要約定前后端的交互接口,在實際開發(fā)過程中,前端人員只負責前端開發(fā),后端人員負責后端開發(fā),那么就需要約定前端發(fā)送什么樣的請求,后端處理請求之后再以什么格式將數(shù)據(jù)返回給前端。
那么對于 POST請求:
POST /message { from:"XX", to:"XX", message:"xxx" }
POST響應:
HTTP/1.1 200 OK { ok:true }
當用戶點擊提交按鈕之后,就會向HTTP服務器發(fā)送一個請求,讓服務器把這個信息存儲起來。
GET 請求
GET /message
GET響應
HTTP/1.1 200 OK Content-Type:application/json { { from:"XX", to:"XX", message:"xxx" }, { from:"XX", to:"XX", message:"xxx" }, …… }
請求從服務器上獲取到之前保存的所有的留言信息,響應是Json格式的數(shù)組。
2、后端代碼實現(xiàn)
正式寫代碼之前的準備工作:
需要創(chuàng)建一個maven項目,在這個項目中先引入Servlet依賴,Mysql依賴,以及Jackson依賴并且創(chuàng)建出正確的目錄結構。
<dependencies> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.5</version> </dependency> </dependencies>
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> </web-app>
首先創(chuàng)建出一個message類定義from,to,message幾個變量。
class Message{ public String from; public String to; public String message; }
創(chuàng)建DBUtil連接數(shù)據(jù)庫,并且能夠關閉各種資源。
public class DBUtil { private static final String url = "jdbc:mysql://127.0.0.1:3306/message?characterEncoding=utf8&useSSL=false"; private static final String user = "root"; private static final String password = "1234"; public volatile static DataSource dataSource; private static DataSource getDataSource(){ if(dataSource == null){ synchronized (DBUtil.class){ if(dataSource == null){ dataSource = new MysqlDataSource(); ((MysqlDataSource)dataSource).setUrl(url); ((MysqlDataSource)dataSource).setUser(user); ((MysqlDataSource)dataSource).setPassword(password); } } } return dataSource; } public static Connection getConnection() throws SQLException { return getDataSource().getConnection(); } public static void closeResource(Connection connection, PreparedStatement statement, ResultSet resultSet){ if(resultSet != null){ try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if(statement != null){ try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if(connection != null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
在Mysql中創(chuàng)建Message表:
創(chuàng)建MessageServlet類,繼承HttpServlet類,重寫doGet方法和doPost方法。
在doPost方法中,先設置了響應的內容類型為json格式和字符集為utf-8,然后將請求信息轉換成Message對象,再將Message對象的內容存入數(shù)據(jù)庫。然后再向body中寫入約定的POST響應的內容。
private ObjectMapper objectMapper = new ObjectMapper(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("application/json;charset=utf8"); Message message = objectMapper.readValue(req.getInputStream(),Message.class); //將處理的請求信息存入數(shù)據(jù)庫 save(message); resp.getWriter().write("{\"ok\":true"); } private void save(Message message){ Connection connection = null; PreparedStatement statement = null; try { connection = DBUtil.getConnection(); String sql = "insert into message value(?,?,?)"; statement = connection.prepareStatement(sql); statement.setString(1,message.from); statement.setString(2,message.to); statement.setString(3,message.message); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally { DBUtil.closeResource(connection,statement,null); } }
在doGet方法中也要先設置響應的內容格式是json,設置字符集為utf-8,然后從數(shù)據(jù)庫中取出之前存儲的信息存到鏈表中,將Message對象轉換成字符串寫入作為get方法響應的body中。
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("application/json;charset=utf8"); List<Message> messages = load(); String jsonString = objectMapper.writeValueAsString(messages); System.out.println("jsonString:" + jsonString); resp.getWriter().write(jsonString); } private List<Message> load(){ Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; List<Message> list = new LinkedList<>(); try { connection = DBUtil.getConnection(); String sql = "select * from message"; statement = connection.prepareStatement(sql); resultSet = statement.executeQuery(); while(resultSet.next()){ Message message = new Message(); message.from = resultSet.getString("from"); message.to = resultSet.getString("to"); message.message = resultSet.getString("massage"); list.add(message); } } catch (SQLException e) { e.printStackTrace(); }finally { DBUtil.closeResource(connection,statement,resultSet); } return list; }
3、前端代碼實現(xiàn)
需要基于ajax能構造請求并解析響應。
把當前獲取到的輸入框的內容,構造成一個HTTP POST請求,然后通過ajax發(fā)給服務器。
let body = { "from": from, "to": to, "message": message }; $.ajax({ type: "post", url: "message", contentType: "application/json;charset=utf8", data: JSON.stringify(body), success: function() { alert("提交成功!"); }, error: function () { alert("提交失敗"); } });
在每次刷新頁面時,要從服務器上獲取到消息,將其進行展示。
function getMessages() { $.ajax({ type: 'get', url:'message', contentType: 'json', success: function(body) { let container=document.querySelector('.container'); console.log(body); for(let message of body) { let row=document.createElement('div'); row.innerHTML=message.from+'對'+message.to+'說:'+message.message; row.className='row'; //3.把這個新的元素添加到DOM樹上 container.appendChild(row); } } });
前端完整代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>表白墻</title> </head> <body> <div class="container"> <h1>表白墻</h1> <p>輸入后點擊提交,會將信息顯示在表格中</p > <div class="row"> <span>誰:</span> <input type="text" class="edit"> </div> <div class="row" > <span>對誰:</span> <input type="text" class="edit"> </div> <div class="row"> <span>說什么:</span> <input type="text" class="edit"> </div> <div class="row"> <input type="button" value="提交" id="submit"> </div> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <script> //點擊按鈕提交的時候,ajax要構造數(shù)據(jù)發(fā)送給服務器 //頁面加載的時候,從服務器獲取消息列表,并且在頁面上直接顯示。 function getMessages() { $.ajax({ type: 'get', url:'message', contentType: 'json', success: function(body) { let container=document.querySelector('.container'); console.log(body); for(let message of body) { let row=document.createElement('div'); row.innerHTML=message.from+'對'+message.to+'說:'+message.message; row.className='row'; //3.把這個新的元素添加到DOM樹上 container.appendChild(row); } } }); } getMessages(); let submitButton=document.querySelector('#submit'); submitButton.onclick=function(){ //1.先獲取到編輯框的內容 let edits=document.querySelectorAll('.edit'); //依靠.value來獲得其輸入框的值 let from=edits[0].value; let to=edits[1].value; let message=edits[2].value; // console.log(from,to,message); //這里是對用戶輸入進行合法的校驗,看用戶輸入是否合法 if(from==''||to==' '||message==''){ return; } //2.根據(jù)內容,構造HTML元素(.row里面包含用戶輸入的話) //createElement:創(chuàng)建一個元素 let row=document.createElement('div'); row.className='row'; row.innerHTML=from+'對'+to+'說:'+message; //3.把這個新的元素添加到DOM樹上 let container=document.querySelector('.container'); container.appendChild(row); //4.清空原來的輸入框 for(let i=0;i<edits.length;i++){ edits[i].value=''; } // 5.把當前獲取到的輸入框的內容,構造成一個HTTP POST請求,然后通過ajax發(fā)給服務器 let body = { "from": from, "to": to, "message": message }; $.ajax({ type: "post", url: "message", contentType: "application/json;charset=utf8", data: JSON.stringify(body), success: function() { alert("提交成功!"); }, error: function () { alert("提交失敗"); } }); } </script> <style> /*去除瀏覽器默認樣式:內邊距,外邊距,內邊框和外邊框不會撐大盒子*/ *{ margin:0; padding: 0; box-sizing: border-box; } /*margin:0 auto :意思是 中央居中*/ .container{ width: 400px; margin:0 auto; } /*padding:20px auto :h1標簽:上下間距20*/ h1{ text-align:center; padding:20px ; } p{ text-align:center; color:#666; padding: 10px 0; font-size:14px; } /*display:flex:基于彈性布局 justify-content:center:水平居中 align-items:center:垂直居中 */ .row{ height:50px ; display: flex; justify-content: center; align-items:center; } span{ width:90px; font-size: 20px; } input{ width:310px; height: 40px; font-size: 18px; } /* 設置提交按鈕的樣式 */ #submit{ width: 400px; color: white; background-color:orange; border:none; border-radius:5px; font-size: 18px; } /*點擊 提交 按鈕 就會改變其背景顏色*/ #submit:active{ background-color: black; } </style> </div> </body> </html>
三、效果演示
點擊提交按鈕之后:
總結
到此這篇關于Java Servlet實現(xiàn)表白墻的文章就介紹到這了,更多相關Servlet實現(xiàn)表白墻內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot整合RabbitMQ實戰(zhàn)教程附死信交換機
這篇文章主要介紹了SpringBoot整合RabbitMQ實戰(zhàn)附加死信交換機,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06Springboot+Vue+shiro實現(xiàn)前后端分離、權限控制的示例代碼
這篇文章主要介紹了Springboot+Vue+shiro實現(xiàn)前后端分離、權限控制的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07SpringBoot中@ComponentScan的使用詳解
這篇文章主要介紹了SpringBoot中@ComponentScan的使用詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11