初始時,javascript
初始時welcome.jsp首頁數據統計顯示的代碼,其數字都是寫固定的:java
<div carousel-item=""> <ul class="layui-row layui-col-space10 layui-this"> <li class="layui-col-xs2"> <a href="javascript:;" class="x-admin-backlog-body"> <h3>用戶數</h3> <p> <cite>66</cite></p> </a> </li> <li class="layui-col-xs2"> <a href="javascript:;" class="x-admin-backlog-body"> <h3>帖子數</h3> <p> <cite>12</cite></p> </a> </li> <li class="layui-col-xs2"> <a href="javascript:;" class="x-admin-backlog-body"> <h3>回覆數</h3> <p> <cite>99</cite></p> </a> </li> <li class="layui-col-xs2"> <a href="javascript:;" class="x-admin-backlog-body"> <h3>點贊數</h3> <p> <cite>67</cite></p> </a> </li> </ul> </div>
數據庫:web
須要分別從這四個表中獲取,接下來進行分析如何從數據庫中獲取數據:spring
在GetDataAction.java進行封裝userService:sql
private UserService userService; Integer userCount = userService.getAllUser(); ActionContext.getContext().put("userCount", userCount); public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; }
在service層建立UserService.java類,並引入getAllUser():數據庫
package com.guiyan.service; import com.guiyan.dao.UserDao; public class UserService { private UserDao userDao; public Integer getAllUser() { return userDao.getAllUser(); } public UserDao getUserDao() { return userDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } }
在dao層建立UserDao.java類,在該類中寫入其sql語句:session
package com.guiyan.dao; import java.math.BigInteger; import org.hibernate.Session; import org.hibernate.query.NativeQuery; import org.springframework.orm.hibernate5.support.HibernateDaoSupport; public class UserDao extends HibernateDaoSupport { public Integer getAllUser() { Session session = getHibernateTemplate().getSessionFactory().getCurrentSession(); String sql = "select count(*) from user"; NativeQuery query = session.createSQLQuery(sql); BigInteger result = (BigInteger) query.uniqueResult();//須要BigInteger類型 return result.intValue(); } }
在頁面顯示中進行獲取到的數據的顯示:welcom.jspapp
<li class="layui-col-xs2"> <a href="javascript:;" class="x-admin-backlog-body"> <h3>用戶數</h3> <p> <cite> <s:property value="userCount"/> </cite> </p> </a> </li>
當在此時運行該項目的時候,出現的問題:jsp
出現該緣由是由於沒有進行注入:ui
在applicationContext.xml進行注入:
<!-- 配置Action --> <bean name="getDataAction" class="com.guiyan.web.GetDataAction" scope="prototype"> <property name="userService" ref="userService"></property> </bean> <!-- 配置service --> <bean name="userService" class="com.guiyan.service.UserService"> <property name="userDao" ref="userDao"></property> </bean> <!-- 配置Dao --> <bean name="userDao" class="com.guiyan.dao.UserDao"> <property name="sessionFactory" ref="sessionFactory"></property> </bean>
數據庫中的用戶數:
頁面經過數據庫顯示的效果: