获取用户信息并分页显示
UserInfo.java
package cn.ict.mp.bean;
public class UserInfo {
private Long id;
private String userId;
private String userName;
private Integer type;
private String email;
private String client = "AndroidpnClient";
private String clientIp = "10.21.1.55";
private String createddate;
private Integer appType;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public String getClientIp() {
return clientIp;
}
public void setClientIp(String clientIp) {
this.clientIp = clientIp;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getAppType() {
return appType;
}
public void setAppType(Integer appType) {
this.appType = appType;
}
public String getCreateddate() {
return createddate;
}
public void setCreateddate(String createddate) {
this.createddate = createddate;
}
}
UserInfo.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.ict.mp.bean"> <class name="UserInfo" table="apn_user" lazy="false"> <id name="id" column="id" type="long"> <generator class="identity" /> </id> <property name="userId" type="string"> <column name="username" sql-type="varchar" /> </property> <property name="userName" type="string"> <column name="name" sql-type="varchar" /> </property> <property name="type" type="integer"> <column name="type" sql-type="int" /> </property> <property name="email" type="string"> <column name="email" sql-type="varchar" /> </property> <property name="createddate" type="string"> <column name="created_date" sql-type="datetime" /> </property> <property name="appType" type="integer"> <column name="apptype" sql-type="int" /> </property> </class> </hibernate-mapping>
UserInfoDaoImp.java
package cn.ict.mp.dao.imp;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateTemplate;
import cn.ict.mp.bean.UserInfo;
import cn.ict.mp.dao.UserInfoDao;
public class UserInfoDaoImp implements UserInfoDao {
private HibernateTemplate hibernateTemplate;
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
/**
* get the list of current page's user information
* @param String hql
* @param Integer pageNo
* @param Integer pageSize
* @return List<UserInfo>
*/
@SuppressWarnings("unchecked")
@Override
public List<UserInfo> findUserInfo(String hql,Integer pageNo, Integer pageSize) {
// TODO Auto-generated method stub
List<UserInfo> userList = new ArrayList<UserInfo>();
Session s = hibernateTemplate.getSessionFactory().openSession();
Query query = s.createQuery(hql);
//设置当前页显示的第一条记录
query.setFirstResult((pageNo - 1) * pageSize);
//设置每页最多显示记录条数
query.setMaxResults(pageSize);
userList = query.list();
s.close();
return userList;
}
/**
* get the size of user list
* @param String hql
* @return Integer
*/
@SuppressWarnings("unchecked")
@Override
public Integer findUserListSize(String hql) {
// TODO Auto-generated method stub
List<UserInfo> userList = new ArrayList<UserInfo>();
Session s = hibernateTemplate.getSessionFactory().openSession();
Query query = s.createQuery(hql);
userList = query.list();
Integer totalSize = userList.size();
s.close();
return totalSize;
}
}
applicationContext-beans.xml
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.generate_statistics">true</prop> <prop key="hibernate.connection.release_mode">auto</prop> <prop key="hibernate.autoReconnect">true</prop> <prop key="hibernate.cglib.use_reflection_optimizer">true</prop> </props> </property> <!-- 配置映射文件 --> <property name="mappingResources"> <list> <value>cn/ict/mp/bean/Login.hbm.xml</value> <value>cn/ict/mp/bean/UserInfo.hbm.xml</value> </list> </property> </bean> <!-- 2把Session工厂注入给hibernateTemplate --> <!-- 解释一下hibernateTemplate:hibernateTemplate提供了很多方便的方法,在执行时自动建立 HibernateCallback 对象,例如:load()、get()、save、delete()等方法。 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 3创建hibernate的事务管理器 Spring AOP 注入sessionFactory --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 4配置通知 将该通知关联到hibernate事务管理器 --> <tx:advice id="advice" transaction-manager="txManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" read-only="false" /> <tx:method name="find*" propagation="REQUIRED" isolation="DEFAULT" read-only="true" /> <tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" read-only="false" /> <tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" read-only="false" /> <tx:method name="*" read-only="true" /> </tx:attributes> </tx:advice> <!-- 5配置切入点Spring AOP,将切入点和通知关联起来 --> <aop:config> <aop:pointcut id="perform" expression="execution(* cn.ict.mp.dao..*.*(..))" /> <aop:advisor advice-ref="advice" pointcut-ref="perform" /> </aop:config> <!-- 6配置dao层 --> <bean id="loginDao" class="cn.ict.mp.dao.imp.LoginDaoImp"> <property name="hibernateTemplate" ref="hibernateTemplate" /> </bean> <bean id="userInfoDao" class="cn.ict.mp.dao.imp.UserInfoDaoImp"> <property name="hibernateTemplate" ref="hibernateTemplate" /> </bean>
DataManage.java
package cn.ict.mp.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.ict.mp.bean.Login;
import cn.ict.mp.bean.UserInfo;
import cn.ict.mp.dao.LoginDao;
import cn.ict.mp.dao.UserInfoDao;
public class DataManage {
private static ApplicationContext instance = null;
/**
* new a XmlApplicationContext object and make it be singleton
*
* @return instance
*/
private static ApplicationContext getXML() {
if (instance == null) {
instance = new ClassPathXmlApplicationContext(
"applicationContext-beans.xml");
}
return instance;
}
/**
* get the list of the current page's user information
* @param pageNo
* @param pageSize
* @return List<UserInfo>
*/
public static List<UserInfo> getUserList(Integer pageNo, Integer pageSize) {
List<UserInfo> list = new ArrayList<UserInfo>();
ApplicationContext actx = getXML();
UserInfoDao ud = (UserInfoDao) actx.getBean("userInfoDao");
String query = "from UserInfo u order by u.id desc";
list = ud.findUserInfo(query, pageNo, pageSize);
return list;
}
/**
* get the total size of user list
* @return Integer
*/
public static Integer getUserListSize() {
ApplicationContext actx = getXML();
UserInfoDao ud = (UserInfoDao) actx.getBean("userInfoDao");
String query = "from UserInfo u order by u.id desc";
Integer total = ud.findUserListSize(query);
return total;
}
/**
* get the list of the login information
*
* @return List<UserInfo>
*/
public static List<Login> getLoginList() {
List<Login> list = new ArrayList<Login>();
ApplicationContext actx = getXML();
LoginDao ld = (LoginDao) actx.getBean("loginDao");
String query = "from Login l order by l.id desc";
list = ld.findLoginList(query);
return list;
}
/**
* judge the username and password is valid or not
*
* @return String
*/
public static String isValid(String userName, String password) {
//flag=2表示用户名不存在
String flag = "2";
List<Login> loginList = getLoginList();
//flag = 1表示用户名或密码为空
if(userName == null||password == null||userName.equals("")||password.equals(""))
{
flag = "1";
}
else
{
for(int i = 0;i < loginList.size();i++)
{
Login l = loginList.get(i);
//若用户输入的用户名存在,再判断输入的密码是否与该用户名匹配
if(userName.equals(l.getUserName()))
{
if(password.equals(l.getPassword())){
//flag = 0表示用户名和密码匹配
flag = "0";
}
else{
//flag = 3表示用户名正确,但和密码不匹配
flag = "3";
}
break;
}
}
}
return flag;
}
}
ActionUserList.java
package cn.ict.mp.webservice;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import cn.ict.mp.bean.UserInfo;
import cn.ict.mp.service.DataManage;
import com.opensymphony.xwork2.ActionSupport;
public class ActionUserList extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = -6652169340293756648L;
private Map<String, Object> dataMap = new HashMap<String, Object>();
public Map<String, Object> getDataMap() {
return dataMap;
}
private Integer pageNo;
private Integer totalSize;
private Integer totalPage;
private Integer pageSize = 5;
public Integer getTotalPage() {
return totalPage;
}
public Integer getPageNo() {
return pageNo;
}
public void setPageNo(Integer pageNo) {
this.pageNo = pageNo;
}
public String execute() throws Exception {
/**
* 定义action返回格式
*/
ServletActionContext.getResponse().setContentType("application/json;charset=UTF-8");
ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
//分页显示用户信息列表
List<UserInfo> dataList = DataManage.getUserList(pageNo, pageSize);
totalSize = DataManage.getUserListSize();
//总页数向上取整
totalPage = (int)Math.ceil((double)totalSize/pageSize);
this.dataMap.put("userList", dataList);
return SUCCESS;
}
}
user.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="resources/css/user.css" /> <title>用户信息列表</title> </head> <body> <div class="pages"> <div class="header"> <div id="title"></div> <div class="mes-1"></div> <!-- 点击“推送消息”图标时跳转至推送消息页面 --> <div><a href = "http://localhost:8082/Message/sendMessageindex" class="mes-2"></a></div> <div class="mes-3"></div> <div class="mes-4"></div> <div class="img-h"></div> </div> <div id="userlist-t"> <div id="state"></div> <div id="userID"></div> <div id="name"></div> <div id="posi"></div> <div id="email"></div> <div id="client"></div> <div id="ip"></div> <div id="time"></div> </div> <div id="userlist-b"></div> <table border="1" width="50%" cellpadding="0" cellspacing="0" style="margin:10% 0 0 20%"> <tr style="background-color: yellow"> <td>appType</td> <td>userId</td> <td>userName</td> <td>type</td> <td>email</td> <td>client</td> <td>clientIp</td> <td>createddate</td> </tr> <!-- 遍历userlist获取当前页用户信息列表 (其中dataMap是ActionUserList返回的HashMap对象)--> <s:iterator value="dataMap" id="column"> <s:set var="total" name="total" value="#column.value.size"/> <s:iterator value="#column.value" id="col" status="st"> <tr> <s:if test="#st.first"></s:if> <td><s:property value="appType"/></td> <td><s:property value="userId"/></td> <td><s:property value="userName"/></td> <td><s:property value="type"/></td> <td><s:property value="email"/></td> <td><s:property value="client"/></td> <td><s:property value="clientIp"/></td> <td><s:property value="createddate"/></td> </tr> </s:iterator> </s:iterator> </table> <!-- 页码跳转实现 --> <script type="text/javascript"> //用户信息总页数 var size=parseInt(<s:property value="totalPage"/>); //第一页 function goFirst(){ goPage(1); } //上一页 function goPrevious(){ goPage(parseInt(document.all.item("pagenumber").value)-1); } //下一页 function goNext(){ goPage(parseInt(document.all.item("pagenumber").value)+1); } //最后一页 function goLast(){ goPage(size); } //进入页号为pageNumber的页面 function goPage(pagenumber){ if(pagenumber<1) {alert("到了首页");return;} if(pagenumber>size) {alert("到了最后一页");return;} window.location.href="http://localhost:8082/Message/userList?pageNo="+pagenumber; } </script> <!-- 这里设置一个隐藏标签,其值为“当前页数 ”--> <input type="hidden" name="pagenumber" value="<s:property value="pageNo"/>"/> <!-- 页码跳转链接 --> <div class="page"> <a href="javascript:goFirst()">第一页</a> <a href="javascript:goPrevious()">上一页</a> 第<s:property value="pageNo"/>页 <a href="javascript:goNext()">下一页</a> <a href="javascript:goLast()">最后一页</a> </div> <div id="foot"> 联系我们: 010-62600237@@liangchen@ict.ac.cn </div> </div> </body> </html>
struts.xml
<action name="userList" class="cn.ict.mp.webservice.ActionUserList" method="execute"> <result name="success">/user.jsp</result> </action>