JavaWeb小项目02home界面实现
创建表
CREATE TABLE `publish` ( `id` int(11) NOT NULL AUTO_INCREMENT, `date` varchar(200) NOT NULL, `nickname` varchar(50) NOT NULL, `content_txt` varchar(200) NOT NULL, `content_img` varchar(200) NOT NULL, `sign` varchar(255) NOT NULL, `username` varchar(20) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;
添加数据
INSERT INTO `publish` VALUES ('6', '2020-9', '超级用户', '苏丹暴雨和洪涝灾害致死人数升至86人', 'http://29e5534ea20a8.cdn.sohucs.com/c_zoom,h_103/c_cut,x_0,y_0,w_898,h_599/os/news/b2a8fea0bf3da20c49100e0040563f6.jpg', '111', 'admin'), ('9', '2020-9', '*飞', '帅', 'http://29e5534ea20a8.cdn.sohucs.com/c_zoom,h_103/c_cut,x_0,y_0,w_898,h_599/os/news/b2a8fea0bf3da20c49100e0040563f6.jpg', '112', 'lipengfei'), ('14', '2020-71', '超级用户', '打开了撒娇看到撒开多久啊剋三六九等卢卡斯', './publish_img/logo.jpg', '1598603620227', 'admin'), ('15', '2020-71', '超级用户', 'Djdjjdndndjdjq', './publish_img/DF8FAFFE-CE25-4A1D-87E7-693B158CB0D8.jpeg', '1598604627621', 'admin'), ('16', '2020-71', '超级用户', 'Hdjdjdbdb ', './publish_img/image.jpg', '1598604712939', 'admin'), ('17', '2020-71', '吴亦凡', '我很帅', './publish_img/4DB4EF0B-4588-4E4A-8E9A-41D057C40807.jpeg', '1598605395091', '13253689303'), ('18', '2020-71', '李易峰', '我很帅', './publish_img/1E174559-5A5B-43E6-BE4D-9024608204BE.jpeg', '1598605645315', '13253689309');
创建简单实体类POJO
定义的时候一般和数据库表对应,不包含逻辑关系
public class Publish { private int id; private String date; private String nickname; private String contentTxt; private String contentImg; private String sign; private String username; }
使用alt+insert键快捷键选择Getter and Setter方法自动生成构造方法
/*get set构造方法的快捷键是alt+insert键*/ public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getContentTxt() { return contentTxt; } public void setContentTxt(String contentTxt) { this.contentTxt = contentTxt; } public String getContentImg() { return contentImg; } public void setContentImg(String contentImg) { this.contentImg = contentImg; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; }
创建PublishDao方法
利用Dao方法实现访问数据库,查询publish表并返回功能
/*连接数据库,查询publish表中所有数据, 打包成publish对象存入List<Publish>类型集合中返回*/ public class PublishDao { public List<Publish> selectAll(){ DBUtils utils = DBUtils.getInstance(); Connection conn = null; PreparedStatement pst = null; ResultSet result = null; try { conn = utils.getConn(); String sql = "select * from publish"; pst = conn.prepareStatement(sql); //执行查询,返回结果集 result = pst.executeQuery(sql); List<Publish> list=new ArrayList<>(); while (result.next()){ /*根据数据库表的列名获取数据*/ String nickname = result.getString("nickname"); String date = result.getString("date"); String contentTxt = result.getString("content_txt"); String contentImg = result.getString("content_img"); /*对于每条数据,实例化一个publish对象用于存储,并添加到list集合中*/ Publish publish =new Publish(); publish.setContentImg(contentImg); publish.setContentTxt(contentTxt); publish.setDate(date); publish.setNickname(nickname); list.add(publish); } return list; } catch (SQLException throwables) { throwables.printStackTrace(); }finally { try { utils.closeAll(conn,pst,result); } catch (SQLException throwables) { throwables.printStackTrace(); } } return null; } }
创建PublishService方法
调用Dao方法获得数据库查询结果,并将list集合转化为JSON字符串并返回
public class PublishService { public String selectAll(){ PublishDao dao = new PublishDao(); List<Publish> list = dao.selectAll(); if (list!=null && list.size()>0){ Gson gson = new Gson(); //将list集合转化为json字符串 String jsonString = gson.toJson(list); return jsonString; } return "error"; } }
创建HomeServlet方法
使用Servlet接收前端数据,并返回查询结果(JSON字符串或者"error")
@WebServlet("/home") public class HomeServlet extends HttpServlet { PublishService publishService=null; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); publishService = new PublishService(); String jsonString = publishService.selectAll(); resp.getWriter().write(jsonString); } }
前端利用原生JavaScript实现数据添加
<script src="js/jquery-1.10.2.min.js" type="text/javascript" charset="utf-8"></script> <script> //调用ajax传参 $.ajax({ url:"http://localhost:8080/Day07XL/home", method:"GET", dataType:"json", success:function (data) { //返回值data是json类型因此不需要格式化 //返回值是json字符串,需要进行json格式化 // var result = JSON.parse(data); //找到整个需要动态添加内容的模块 var contentList = document.getElementsByClassName("content-list")[0]; for(var i=0;i<data.length;i++){ //获取一个json数据 var publish = data[i]; //按照键取json的值 var nickname = publish.nickname; var date = publish.date; var contentTxt = publish.contentTxt; var contentImg = publish.contentImg; //按照home.html中存放数据的格式创建一组html标签,并将数据库中的值置入 //创建一个div标签 var content = document.createElement("div"); //设置该标签的值 content.className="content"; //创建第一块儿内容 var user = document.createElement("div"); user.className = "content-user"; //添加子标签 var icon= document.createElement("img"); icon.setAttribute("src","image/icon.jpg"); icon.className="content-user-icon"; user.appendChild(icon); var div = document.createElement("div"); var p_name = document.createElement("p"); p_name.className="content-user-nick"; p_name.innerText=nickname; div.appendChild(p_name); var p_date = document.createElement("p"); p_date.className="content-user-date"; p_date.innerText=date; div.appendChild(p_date); user.append(div); content.appendChild(user); //创建第二块儿内容 var user_content = document.createElement("div"); user_content.className="content-user-content"; //添加子标签 var p_text = document.createElement("p") p_text.className="text"; p_text.innerText = contentTxt; user_content.appendChild(p_text); var image_content = document.createElement("img"); image_content.setAttribute("src",contentImg); image_content.className="image"; user_content.appendChild(image_content); content.appendChild(user_content); //将创建好的div,放进它的父元素中 contentList.appendChild(content); } }, error:function (data) { } }) </script>