分析查询所有用户
初始时,
初始时welcome.jsp首页数据统计显示的代码,其数字都是写固定的:
<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>
数据库:
需要分别从这四个表中获取,接下来进行分析如何从数据库中获取数据:
书写查询所有用户的代码
在GetDataAction.java进行封装userService:
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语句:
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.jsp
<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>
当在此时运行该项目的时候,出现的问题:
出现该原因是因为没有进行注入:
在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>
数据库中的用户数:
页面通过数据库显示的效果: