Java SSH框架系列:用户登录模块的设计与实现思路

1.简介
用户登录模块,指的是根据用户输入的用户名和密码,对用户的身份进行验证等。如果用户没有登录,用户就无法访问其他的一些jsp页面,甚至是action都不能访问。
二、简单设计及实现
本程序是基于Java的SSH框架进行的。
1.数据库设计

我们应该设计一个用户表,其Userinfo表,对应的SQL语句为(Oracle数据库):

 

  1. create table userinfo  
  2. (  
  3.   id                        varchar2(36) primary key,  
  4.   username                 varchar2(50) not null,  
  5.   password                 varchar2(50) not null,  
  6.   auth_limit               varchar2(10) not null,  
  7.   register_time           varchar2(40),  
  8.   create_time             varchar2(40),  
  9.   remarks                  varchar2(1024)                 
  10. );  
create table userinfo

(

  id                        varchar2(36) primary key,

  username                 varchar2(50) not null,

  password                 varchar2(50) not null,

  auth_limit               varchar2(10) not null,

  register_time           varchar2(40),

  create_time             varchar2(40),

  remarks                  varchar2(1024)               

);


分别是id,也就是UUID,用户名、密码、权限、注册时间、记录插入数据库的时间、备注等几个字段。

 

2.使用MyEclipse的Hibernate逆向工具,生成对应的Java Bean和相应的hibernate的xml配置文件Userinfo.hbm.xml

 

  1. package edu.njupt.zhb.bean;  
  2.   
  3. /** 
  4.  * Userinfo entity. @author MyEclipse Persistence Tools 
  5.  */  
  6.   
  7. public class Userinfo implements java.io.Serializable {  
  8.   
  9.     // Fields   
  10.   
  11.     private String id;  
  12.     private String username;  
  13.     private String password;  
  14.     private String authLimit;  
  15.     private String registerTime;  
  16.     private String createTime;  
  17.     private String remarks;  
  18.   
  19.     // Constructors   
  20.   
  21.     /** default constructor */  
  22.     public Userinfo() {  
  23.     }  
  24.   
  25.     /** minimal constructor */  
  26.     public Userinfo(String id, String username, String password,  
  27.             String authLimit) {  
  28.         this.id = id;  
  29.         this.username = username;  
  30.         this.password = password;  
  31.         this.authLimit = authLimit;  
  32.     }  
  33.   
  34.     /** full constructor */  
  35.     public Userinfo(String id, String username, String password,  
  36.             String authLimit, String registerTime, String createTime,  
  37.             String remarks) {  
  38.         this.id = id;  
  39.         this.username = username;  
  40.         this.password = password;  
  41.         this.authLimit = authLimit;  
  42.         this.registerTime = registerTime;  
  43.         this.createTime = createTime;  
  44.         this.remarks = remarks;  
  45.     }  
  46.   
  47.     // Property accessors   
  48.   
  49.     public String getId() {  
  50.         return this.id;  
  51.     }  
  52.   
  53.     public void setId(String id) {  
  54.         this.id = id;  
  55.     }  
  56.   
  57.     public String getUsername() {  
  58.         return this.username;  
  59.     }  
  60.   
  61.     public void setUsername(String username) {  
  62.         this.username = username;  
  63.     }  
  64.   
  65.     public String getPassword() {  
  66.         return this.password;  
  67.     }  
  68.   
  69.     public void setPassword(String password) {  
  70.         this.password = password;  
  71.     }  
  72.   
  73.     public String getAuthLimit() {  
  74.         return this.authLimit;  
  75.     }  
  76.   
  77.     public void setAuthLimit(String authLimit) {  
  78.         this.authLimit = authLimit;  
  79.     }  
  80.   
  81.     public String getRegisterTime() {  
  82.         return this.registerTime;  
  83.     }  
  84.   
  85.     public void setRegisterTime(String registerTime) {  
  86.         this.registerTime = registerTime;  
  87.     }  
  88.   
  89.     public String getCreateTime() {  
  90.         return this.createTime;  
  91.     }  
  92.   
  93.     public void setCreateTime(String createTime) {  
  94.         this.createTime = createTime;  
  95.     }  
  96.   
  97.     public String getRemarks() {  
  98.         return this.remarks;  
  99.     }  
  100.   
  101.     public void setRemarks(String remarks) {  
  102.         this.remarks = remarks;  
  103.     }  
  104.   
  105. }  
package edu.njupt.zhb.bean;



/**

 * Userinfo entity. @author MyEclipse Persistence Tools

 */



public class Userinfo implements java.io.Serializable {



	// Fields



	private String id;

	private String username;

	private String password;

	private String authLimit;

	private String registerTime;

	private String createTime;

	private String remarks;



	// Constructors



	/** default constructor */

	public Userinfo() {

	}



	/** minimal constructor */

	public Userinfo(String id, String username, String password,

			String authLimit) {

		this.id = id;

		this.username = username;

		this.password = password;

		this.authLimit = authLimit;

	}



	/** full constructor */

	public Userinfo(String id, String username, String password,

			String authLimit, String registerTime, String createTime,

			String remarks) {

		this.id = id;

		this.username = username;

		this.password = password;

		this.authLimit = authLimit;

		this.registerTime = registerTime;

		this.createTime = createTime;

		this.remarks = remarks;

	}



	// Property accessors



	public String getId() {

		return this.id;

	}



	public void setId(String id) {

		this.id = id;

	}



	public String getUsername() {

		return this.username;

	}



	public void setUsername(String username) {

		this.username = username;

	}



	public String getPassword() {

		return this.password;

	}



	public void setPassword(String password) {

		this.password = password;

	}



	public String getAuthLimit() {

		return this.authLimit;

	}



	public void setAuthLimit(String authLimit) {

		this.authLimit = authLimit;

	}



	public String getRegisterTime() {

		return this.registerTime;

	}



	public void setRegisterTime(String registerTime) {

		this.registerTime = registerTime;

	}



	public String getCreateTime() {

		return this.createTime;

	}



	public void setCreateTime(String createTime) {

		this.createTime = createTime;

	}



	public String getRemarks() {

		return this.remarks;

	}



	public void setRemarks(String remarks) {

		this.remarks = remarks;

	}



}


3.新建一个UserInfoService接口

 

 

  1. /* 
  2.  * $filename: VideoInfoService.java,v $ 
  3.  * $Date: 2014-1-2  $ 
  4.  * Copyright (C) ZhengHaibo, Inc. All rights reserved. 
  5.  * This software is Made by Zhenghaibo. 
  6.  */  
  7. package edu.njupt.zhb.service;  
  8.   
  9. import edu.njupt.zhb.bean.Userinfo;  
  10.   
  11. /* 
  12.  *@author: ZhengHaibo   
  13.  *web:     http://blog.csdn.net/nuptboyzhb 
  14.  *GitHub   https://github.com/nuptboyzhb 
  15.  *mail:    [email protected] 
  16.  *2014-1-2  Nanjing,njupt,China 
  17.  */  
  18. public interface UserInfoService {  
  19.   
  20.     String getUserInfoList(int page, int rows);  
  21.   
  22.     String addUser(Userinfo userinfo);  
  23.   
  24.     String deleteUser(String userId);  
  25.   
  26.     String editUser(Userinfo userinfo);  
  27.   
  28.     Userinfo getUserInfoByName(String username);  
  29.   
  30.   
  31. }  
/*

 * $filename: VideoInfoService.java,v $

 * $Date: 2014-1-2  $

 * Copyright (C) ZhengHaibo, Inc. All rights reserved.

 * This software is Made by Zhenghaibo.

 */

package edu.njupt.zhb.service;



import edu.njupt.zhb.bean.Userinfo;



/*

 *@author: ZhengHaibo  

 *web:     http://blog.csdn.net/nuptboyzhb

 *GitHub   https://github.com/nuptboyzhb

 *mail:    [email protected]

 *2014-1-2  Nanjing,njupt,China

 */

public interface UserInfoService {



	String getUserInfoList(int page, int rows);



	String addUser(Userinfo userinfo);



	String deleteUser(String userId);



	String editUser(Userinfo userinfo);



	Userinfo getUserInfoByName(String username);





}


4.新建一个UserInfoServiceImpl类

 

 

  1. /* 
  2.  * $filename: VideoInfoServiceImpl.java,v $ 
  3.  * $Date: 2014-1-2  $ 
  4.  * Copyright (C) ZhengHaibo, Inc. All rights reserved. 
  5.  * This software is Made by Zhenghaibo. 
  6.  */  
  7. package edu.njupt.zhb.service.impl;  
  8.   
  9. import java.util.ArrayList;  
  10. import java.util.List;  
  11.   
  12. import net.sf.json.JSONObject;  
  13.   
  14. import edu.njupt.zhb.bean.Userinfo;  
  15. import edu.njupt.zhb.dao.BaseDao;  
  16. import edu.njupt.zhb.service.UserInfoService;  
  17. import edu.njupt.zhb.utils.DataGrid;  
  18. import edu.njupt.zhb.utils.Tips;  
  19. import edu.njupt.zhb.view.ViewUser;  
  20.   
  21. /* 
  22.  *@author: ZhengHaibo   
  23.  *web:     http://blog.csdn.net/nuptboyzhb 
  24.  *GitHub   https://github.com/nuptboyzhb 
  25.  *mail:    [email protected] 
  26.  *2014-1-2  Nanjing,njupt,China 
  27.  */  
  28. public class UserInfoServiceImpl implements UserInfoService{  
  29.     private BaseDao<Userinfo> userinfoBaseDao;  
  30.     public BaseDao<Userinfo> getUserBaseDao() {  
  31.         return userinfoBaseDao;  
  32.     }  
  33.     public void setUserBaseDao(BaseDao<Userinfo> userinfoBaseDao) {  
  34.         this.userinfoBaseDao = userinfoBaseDao;  
  35.     }  
  36.     @Override  
  37.     public String getUserInfoList(int page, int rows) {  
  38.         // TODO Auto-generated method stub   
  39.         System.out.println("page="+page+",rows="+rows);  
  40.         String hql = "from Userinfo";  
  41.         try {  
  42.             List<Userinfo> list = userinfoBaseDao.find(hql,page,rows);  
  43.             List<ViewUser> resultList = new ArrayList<ViewUser>();  
  44.             for(Userinfo userinfo:list){  
  45.                 ViewUser viewUser = new ViewUser();  
  46.                 viewUser.setBz(userinfo.getRemarks());  
  47.                 viewUser.setId(userinfo.getId());  
  48.                 viewUser.setPwd(userinfo.getPassword());  
  49.                 viewUser.setYhm(userinfo.getUsername());  
  50.                 viewUser.setYhqx(userinfo.getAuthLimit());  
  51.                 viewUser.setZcsj(userinfo.getRegisterTime());  
  52.                 resultList.add(viewUser);  
  53.             }  
  54.             DataGrid<ViewUser> dataGrid = new DataGrid<ViewUser>();  
  55.             dataGrid.setRows(resultList);  
  56.             dataGrid.setTotal(userinfoBaseDao.total(hql));  
  57.             String result = JSONObject.fromObject(dataGrid).toString();  
  58.             return result;  
  59.         } catch (Exception e) {  
  60.             e.printStackTrace();  
  61.             return null;  
  62.         }  
  63.     }  
  64.       
  65.     public String addUser(Userinfo userinfo) {  
  66.         // TODO Auto-generated method stub   
  67.         Tips tips = new Tips();  
  68.         String hql = "from Userinfo where username = '"+userinfo.getUsername()+"'";  
  69.         try {  
  70.             List<Userinfo> list =  userinfoBaseDao.find(hql);  
  71.             if(list!=null&&list.size()>0){  
  72.                 tips.setMsg("添加失败!用户名已经存在!");  
  73.                 return JSONObject.fromObject(tips).toString();  
  74.             }  
  75.         } catch (Exception e) {  
  76.             // TODO Auto-generated catch block   
  77.             e.printStackTrace();  
  78.         }  
  79.         try {  
  80.             userinfoBaseDao.save(userinfo);  
  81.         } catch (Exception e) {  
  82.             // TODO Auto-generated catch block   
  83.             e.printStackTrace();  
  84.             tips.setMsg("添加失败");  
  85.             return JSONObject.fromObject(tips).toString();  
  86.         }  
  87.         tips.setMsg("添加成功");  
  88.         return JSONObject.fromObject(tips).toString();  
  89.     }  
  90.     public String deleteUser(String userid) {  
  91.         // TODO Auto-generated method stub   
  92.         Tips tips = new Tips();  
  93.         try {  
  94.             userinfoBaseDao.executeHql("delete from Userinfo where id = '"+userid+"'");  
  95.         } catch (Exception e) {  
  96.             // TODO Auto-generated catch block   
  97.             e.printStackTrace();  
  98.             tips.setMsg("删除失败");  
  99.             return JSONObject.fromObject(tips).toString();  
  100.         }  
  101.         tips.setMsg("删除成功");  
  102.         return JSONObject.fromObject(tips).toString();  
  103.     }  
  104.     public String editUser(Userinfo userinfo) {  
  105.         // TODO Auto-generated method stub   
  106.         Tips tips = new Tips();  
  107.         String hql = "from Userinfo where username = '"+userinfo.getUsername()+"'";  
  108.         try {  
  109.             List<Userinfo> list =  userinfoBaseDao.find(hql);  
  110.             if(list!=null&&list.size()>0){  
  111.                 tips.setMsg("更新失败!用户名已经存在!");  
  112.                 return JSONObject.fromObject(tips).toString();  
  113.             }  
  114.         } catch (Exception e) {  
  115.             // TODO Auto-generated catch block   
  116.             e.printStackTrace();  
  117.         }  
  118.         try {  
  119.             userinfoBaseDao.update(userinfo);  
  120.         } catch (Exception e) {  
  121.             // TODO Auto-generated catch block   
  122.             e.printStackTrace();  
  123.             tips.setMsg("编辑失败");  
  124.             return JSONObject.fromObject(tips).toString();  
  125.         }  
  126.         tips.setMsg("编辑成功");  
  127.         return JSONObject.fromObject(tips).toString();  
  128.     }  
  129.     @Override  
  130.     public Userinfo getUserInfoByName(String username) {  
  131.         // TODO Auto-generated method stub   
  132.         Userinfo  userinfo = null;  
  133.         String hql = "from Userinfo where username = '"+username+"'";  
  134.         try {  
  135.             List<Userinfo> list =  userinfoBaseDao.find(hql);  
  136.             if(list == null || list.size()==0){  
  137.                 return null;  
  138.             }  
  139.             userinfo = list.get(0);  
  140.             return userinfo;  
  141.         } catch (Exception e) {  
  142.             // TODO Auto-generated catch block   
  143.             e.printStackTrace();  
  144.         }  
  145.         return null;  
  146.     }  
  147.   
  148. }  
/*

 * $filename: VideoInfoServiceImpl.java,v $

 * $Date: 2014-1-2  $

 * Copyright (C) ZhengHaibo, Inc. All rights reserved.

 * This software is Made by Zhenghaibo.

 */

package edu.njupt.zhb.service.impl;



import java.util.ArrayList;

import java.util.List;



import net.sf.json.JSONObject;



import edu.njupt.zhb.bean.Userinfo;

import edu.njupt.zhb.dao.BaseDao;

import edu.njupt.zhb.service.UserInfoService;

import edu.njupt.zhb.utils.DataGrid;

import edu.njupt.zhb.utils.Tips;

import edu.njupt.zhb.view.ViewUser;



/*

 *@author: ZhengHaibo  

 *web:     http://blog.csdn.net/nuptboyzhb

 *GitHub   https://github.com/nuptboyzhb

 *mail:    [email protected]

 *2014-1-2  Nanjing,njupt,China

 */

public class UserInfoServiceImpl implements UserInfoService{

	private BaseDao<Userinfo> userinfoBaseDao;

	public BaseDao<Userinfo> getUserBaseDao() {

		return userinfoBaseDao;

	}

	public void setUserBaseDao(BaseDao<Userinfo> userinfoBaseDao) {

		this.userinfoBaseDao = userinfoBaseDao;

	}

	@Override

	public String getUserInfoList(int page, int rows) {

		// TODO Auto-generated method stub

		System.out.println("page="+page+",rows="+rows);

		String hql = "from Userinfo";

		try {

			List<Userinfo> list = userinfoBaseDao.find(hql,page,rows);

			List<ViewUser> resultList = new ArrayList<ViewUser>();

			for(Userinfo userinfo:list){

				ViewUser viewUser = new ViewUser();

				viewUser.setBz(userinfo.getRemarks());

				viewUser.setId(userinfo.getId());

				viewUser.setPwd(userinfo.getPassword());

				viewUser.setYhm(userinfo.getUsername());

				viewUser.setYhqx(userinfo.getAuthLimit());

				viewUser.setZcsj(userinfo.getRegisterTime());

				resultList.add(viewUser);

			}

			DataGrid<ViewUser> dataGrid = new DataGrid<ViewUser>();

			dataGrid.setRows(resultList);

			dataGrid.setTotal(userinfoBaseDao.total(hql));

			String result = JSONObject.fromObject(dataGrid).toString();

			return result;

		} catch (Exception e) {

			e.printStackTrace();

			return null;

		}

	}

	

	public String addUser(Userinfo userinfo) {

		// TODO Auto-generated method stub

		Tips tips = new Tips();

		String hql = "from Userinfo where username = '"+userinfo.getUsername()+"'";

		try {

			List<Userinfo> list =  userinfoBaseDao.find(hql);

			if(list!=null&&list.size()>0){

				tips.setMsg("添加失败!用户名已经存在!");

				return JSONObject.fromObject(tips).toString();

			}

		} catch (Exception e) {

			// TODO Auto-generated catch block

			e.printStackTrace();

		}

		try {

			userinfoBaseDao.save(userinfo);

		} catch (Exception e) {

			// TODO Auto-generated catch block

			e.printStackTrace();

			tips.setMsg("添加失败");

			return JSONObject.fromObject(tips).toString();

		}

		tips.setMsg("添加成功");

		return JSONObject.fromObject(tips).toString();

	}

	public String deleteUser(String userid) {

		// TODO Auto-generated method stub

		Tips tips = new Tips();

		try {

			userinfoBaseDao.executeHql("delete from Userinfo where id = '"+userid+"'");

		} catch (Exception e) {

			// TODO Auto-generated catch block

			e.printStackTrace();

			tips.setMsg("删除失败");

			return JSONObject.fromObject(tips).toString();

		}

		tips.setMsg("删除成功");

		return JSONObject.fromObject(tips).toString();

	}

	public String editUser(Userinfo userinfo) {

		// TODO Auto-generated method stub

		Tips tips = new Tips();

		String hql = "from Userinfo where username = '"+userinfo.getUsername()+"'";

		try {

			List<Userinfo> list =  userinfoBaseDao.find(hql);

			if(list!=null&&list.size()>0){

				tips.setMsg("更新失败!用户名已经存在!");

				return JSONObject.fromObject(tips).toString();

			}

		} catch (Exception e) {

			// TODO Auto-generated catch block

			e.printStackTrace();

		}

		try {

			userinfoBaseDao.update(userinfo);

		} catch (Exception e) {

			// TODO Auto-generated catch block

			e.printStackTrace();

			tips.setMsg("编辑失败");

			return JSONObject.fromObject(tips).toString();

		}

		tips.setMsg("编辑成功");

		return JSONObject.fromObject(tips).toString();

	}

	@Override

	public Userinfo getUserInfoByName(String username) {

		// TODO Auto-generated method stub

		Userinfo  userinfo = null;

		String hql = "from Userinfo where username = '"+username+"'";

		try {

			List<Userinfo> list =  userinfoBaseDao.find(hql);

			if(list == null || list.size()==0){

				return null;

			}

			userinfo = list.get(0);

			return userinfo;

		} catch (Exception e) {

			// TODO Auto-generated catch block

			e.printStackTrace();

		}

		return null;

	}



}


5.新建UserInfoAction类,(当然,我们的BaseAction肯定是从struts2中的ActionSupport派生出来的)

 

 

  1. /* 
  2.  * $filename: VideoInfoAction.java,v $ 
  3.  * $Date: 2014-1-2  $ 
  4.  * Copyright (C) ZhengHaibo, Inc. All rights reserved. 
  5.  * This software is Made by Zhenghaibo. 
  6.  */  
  7. package edu.njupt.zhb.action;  
  8.   
  9. import java.util.UUID;  
  10.   
  11. import net.sf.json.JSONArray;  
  12. import net.sf.json.JSONObject;  
  13. import edu.njupt.zhb.bean.Userinfo;  
  14. import edu.njupt.zhb.service.UserInfoService;  
  15. import edu.njupt.zhb.utils.Tips;  
  16. import edu.njupt.zhb.utils.TipsMsg;  
  17. import edu.njupt.zhb.utils.Utils;  
  18.   
  19. /* 
  20.  *@author: ZhengHaibo   
  21.  *web:     http://blog.csdn.net/nuptboyzhb 
  22.  *GitHub   https://github.com/nuptboyzhb 
  23.  *mail:    [email protected] 
  24.  *2014-1-2  Nanjing,njupt,China 
  25.  */  
  26. public class UserInfoAction extends BaseAction {  
  27.   
  28.     /** 
  29.      *  
  30.      */  
  31.     private static final long serialVersionUID = 3321845277376234101L;  
  32.     private Userinfo userinfo;  
  33.     private String userId;  
  34.     private String username;  
  35.     private String password;  
  36.     public String getPassword() {  
  37.         return password;  
  38.     }  
  39.   
  40.     public void setPassword(String password) {  
  41.         this.password = password;  
  42.     }  
  43.   
  44.     public String getUsername() {  
  45.         return username;  
  46.     }  
  47.   
  48.     public void setUsername(String username) {  
  49.         this.username = username;  
  50.     }  
  51.   
  52.     public String getUserId() {  
  53.         return userId;  
  54.     }  
  55.   
  56.     public void setUserId(String userId) {  
  57.         this.userId = userId;  
  58.     }  
  59.   
  60.     public Userinfo getUserinfo() {  
  61.         return userinfo;  
  62.     }  
  63.   
  64.     public void setUserinfo(Userinfo userinfo) {  
  65.         this.userinfo = userinfo;  
  66.     }  
  67.   
  68.     private UserInfoService userInfoService;  
  69.   
  70.     public UserInfoService getUserInfoService() {  
  71.         return userInfoService;  
  72.     }  
  73.   
  74.     public void setUserInfoService(UserInfoService userInfoService) {  
  75.         this.userInfoService = userInfoService;  
  76.     }  
  77.   
  78.     public void getUserInfoList() {  
  79.         String jsonResult = userInfoService.getUserInfoList(page, rows);  
  80.         System.out.println(jsonResult);  
  81.         super.writeStr(jsonResult);  
  82.     }  
  83.   
  84.     /** 
  85.      * 添加用户 
  86.      *  
  87.      * @return 
  88.      */  
  89.     public void addUser() {  
  90.         if (userinfo == null) {  
  91.             Tips tips = new Tips();  
  92.             tips.setMsg("添加失败!对象为空");  
  93.             getPrintWriter().write(JSONArray.fromObject(tips).toString());  
  94.             return;  
  95.         }  
  96.         userinfo.setId(UUID.randomUUID() + "");  
  97.         userinfo.setCreateTime(Utils.getNowTime());  
  98.         String jsonResult = userInfoService.addUser(userinfo);  
  99.         getPrintWriter().write(jsonResult);  
  100.     }  
  101.   
  102.     /** 
  103.      * 删除用户 
  104.      *  
  105.      * @return 
  106.      */  
  107.     public void deleteUser() {  
  108.         if (userId == null) {  
  109.             Tips tips = new Tips();  
  110.             tips.setMsg("删除失败!学号无效");  
  111.             getPrintWriter().write(JSONArray.fromObject(tips).toString());  
  112.             return;  
  113.         }  
  114.         String jsonResult = userInfoService.deleteUser(userId);  
  115.         getPrintWriter().write(jsonResult);  
  116.     }  
  117.   
  118.     /** 
  119.      * 编辑用户 
  120.      *  
  121.      * @return 
  122.      */  
  123.     public void editUser() {  
  124.         if (userinfo == null) {  
  125.             Tips tips = new Tips();  
  126.             tips.setMsg("编辑失败!对象为空");  
  127.             getPrintWriter().write(JSONArray.fromObject(tips).toString());  
  128.             return;  
  129.         }  
  130.         userinfo.setId(userId);  
  131.         String jsonResult = userInfoService.editUser(userinfo);  
  132.         getPrintWriter().write(jsonResult);  
  133.     }  
  134.   
  135.     public void login() {  
  136.         TipsMsg tipsMsg = new TipsMsg();  
  137.         if(username==null){  
  138.             tipsMsg.setId("1");  
  139.             tipsMsg.setMsg("用户名为空!");  
  140.             String result = JSONObject.fromObject(tipsMsg).toString();  
  141.             super.writeStr(result);  
  142.             return;  
  143.         }  
  144.         Userinfo userinfo = userInfoService.getUserInfoByName(username);  
  145.         if(userinfo==null){  
  146.             tipsMsg.setId("1");  
  147.             tipsMsg.setMsg("用户名不存在");  
  148.             String result = JSONObject.fromObject(tipsMsg).toString();  
  149.             super.writeStr(result);  
  150.             return;  
  151.         }  
  152.         if(!userinfo.getPassword().equals(password)){  
  153.             tipsMsg.setId("1");  
  154.             tipsMsg.setMsg("用户名或密码错误");  
  155.             String result = JSONObject.fromObject(tipsMsg).toString();  
  156.             super.writeStr(result);  
  157.             return;  
  158.         }  
  159.         super.setCurrentUser(userinfo);  
  160.         tipsMsg.setId("2");  
  161.         tipsMsg.setMsg("登录成功");  
  162.         String result = JSONObject.fromObject(tipsMsg).toString();  
  163.         super.writeStr(result);  
  164.         return;  
  165.     }  
  166. }  
/*

 * $filename: VideoInfoAction.java,v $

 * $Date: 2014-1-2  $

 * Copyright (C) ZhengHaibo, Inc. All rights reserved.

 * This software is Made by Zhenghaibo.

 */

package edu.njupt.zhb.action;



import java.util.UUID;



import net.sf.json.JSONArray;

import net.sf.json.JSONObject;

import edu.njupt.zhb.bean.Userinfo;

import edu.njupt.zhb.service.UserInfoService;

import edu.njupt.zhb.utils.Tips;

import edu.njupt.zhb.utils.TipsMsg;

import edu.njupt.zhb.utils.Utils;



/*

 *@author: ZhengHaibo  

 *web:     http://blog.csdn.net/nuptboyzhb

 *GitHub   https://github.com/nuptboyzhb

 *mail:    [email protected]

 *2014-1-2  Nanjing,njupt,China

 */

public class UserInfoAction extends BaseAction {



	/**

	 * 

	 */

	private static final long serialVersionUID = 3321845277376234101L;

	private Userinfo userinfo;

	private String userId;

	private String username;

	private String password;

	public String getPassword() {

		return password;

	}



	public void setPassword(String password) {

		this.password = password;

	}



	public String getUsername() {

		return username;

	}



	public void setUsername(String username) {

		this.username = username;

	}



	public String getUserId() {

		return userId;

	}



	public void setUserId(String userId) {

		this.userId = userId;

	}



	public Userinfo getUserinfo() {

		return userinfo;

	}



	public void setUserinfo(Userinfo userinfo) {

		this.userinfo = userinfo;

	}



	private UserInfoService userInfoService;



	public UserInfoService getUserInfoService() {

		return userInfoService;

	}



	public void setUserInfoService(UserInfoService userInfoService) {

		this.userInfoService = userInfoService;

	}



	public void getUserInfoList() {

		String jsonResult = userInfoService.getUserInfoList(page, rows);

		System.out.println(jsonResult);

		super.writeStr(jsonResult);

	}



	/**

	 * 添加用户

	 * 

	 * @return

	 */

	public void addUser() {

		if (userinfo == null) {

			Tips tips = new Tips();

			tips.setMsg("添加失败!对象为空");

			getPrintWriter().write(JSONArray.fromObject(tips).toString());

			return;

		}

		userinfo.setId(UUID.randomUUID() + "");

		userinfo.setCreateTime(Utils.getNowTime());

		String jsonResult = userInfoService.addUser(userinfo);

		getPrintWriter().write(jsonResult);

	}



	/**

	 * 删除用户

	 * 

	 * @return

	 */

	public void deleteUser() {

		if (userId == null) {

			Tips tips = new Tips();

			tips.setMsg("删除失败!学号无效");

			getPrintWriter().write(JSONArray.fromObject(tips).toString());

			return;

		}

		String jsonResult = userInfoService.deleteUser(userId);

		getPrintWriter().write(jsonResult);

	}



	/**

	 * 编辑用户

	 * 

	 * @return

	 */

	public void editUser() {

		if (userinfo == null) {

			Tips tips = new Tips();

			tips.setMsg("编辑失败!对象为空");

			getPrintWriter().write(JSONArray.fromObject(tips).toString());

			return;

		}

		userinfo.setId(userId);

		String jsonResult = userInfoService.editUser(userinfo);

		getPrintWriter().write(jsonResult);

	}



	public void login() {

		TipsMsg tipsMsg = new TipsMsg();

		if(username==null){

			tipsMsg.setId("1");

			tipsMsg.setMsg("用户名为空!");

			String result = JSONObject.fromObject(tipsMsg).toString();

			super.writeStr(result);

			return;

		}

		Userinfo userinfo = userInfoService.getUserInfoByName(username);

		if(userinfo==null){

			tipsMsg.setId("1");

			tipsMsg.setMsg("用户名不存在");

			String result = JSONObject.fromObject(tipsMsg).toString();

			super.writeStr(result);

			return;

		}

		if(!userinfo.getPassword().equals(password)){

			tipsMsg.setId("1");

			tipsMsg.setMsg("用户名或密码错误");

			String result = JSONObject.fromObject(tipsMsg).toString();

			super.writeStr(result);

			return;

		}

		super.setCurrentUser(userinfo);

		tipsMsg.setId("2");

		tipsMsg.setMsg("登录成功");

		String result = JSONObject.fromObject(tipsMsg).toString();

		super.writeStr(result);

		return;

	}

}


6.配置Spring的applicationContext.xml文件,依次注入Dao、Service和Action。

 

 

  1. <bean id="baseDao" class="edu.njupt.zhb.dao.BaseDao">  
  2.         <property name="sessionFactory" ref="sessionFactory"></property>  
  3.     </bean>  
<bean id="baseDao" class="edu.njupt.zhb.dao.BaseDao">

    	<property name="sessionFactory" ref="sessionFactory"></property>

    </bean>

 

  1. <bean id="userInfoService" class="edu.njupt.zhb.service.impl.UserInfoServiceImpl">  
  2.         <property name="userBaseDao" ref="baseDao"></property>  
  3.     </bean>  
<bean id="userInfoService" class="edu.njupt.zhb.service.impl.UserInfoServiceImpl">

    	<property name="userBaseDao" ref="baseDao"></property>

    </bean>

 

  1. <bean id="userInfoAction" class="edu.njupt.zhb.action.UserInfoAction" scope="prototype">  
  2.         <property name="userInfoService" ref="userInfoService"></property>  
  3.     </bean>  
<bean id="userInfoAction" class="edu.njupt.zhb.action.UserInfoAction" scope="prototype">

		<property name="userInfoService" ref="userInfoService"></property>

	</bean>


7.配置Spring的Hibernate的Java Bean的映射文件

 

 

  1. <bean id="sessionFactory"  
  2.         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
  3.         <property name="dataSource" ref="dataSource" />  
  4.         <property name="hibernateProperties">  
  5.             <props>  
  6.                 <prop key="hibernate.show_sql">true</prop>  
  7.                 <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>  
  8.                 <prop key="current_session_context_class">thread</prop>  
  9.             </props>  
  10.         </property>  
  11.         <property name="mappingResources">  
  12.             <list>  
  13.                 ...  
  14.                 <value>edu/njupt/zhb/bean/Userinfo.hbm.xml</value>  
  15.             </list>  
  16.         </property>  
  17.     </bean>  
<bean id="sessionFactory"

		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

		<property name="dataSource" ref="dataSource" />

		<property name="hibernateProperties">

			<props>

			    <prop key="hibernate.show_sql">true</prop>

				<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>

				<prop key="current_session_context_class">thread</prop>

			</props>

		</property>

		<property name="mappingResources">

			<list>

			    ...

				<value>edu/njupt/zhb/bean/Userinfo.hbm.xml</value>

			</list>

		</property>

	</bean>


8.配置Struts2文件,增加相应的Action,login等

 

 

  1. <action name="getUserInfoList" class="userInfoAction" method="getUserInfoList"></action>  
  2.         <action name="addUser" class="userInfoAction" method="addUser"></action>  
  3.         <action name="deleteUser" class="userInfoAction" method="deleteUser"></action>  
  4.         <action name="editUser" class="userInfoAction" method="editUser"></action>  
  5.         <action name="login" class="userInfoAction" method="login"></action>  
<action name="getUserInfoList" class="userInfoAction" method="getUserInfoList"></action>

		<action name="addUser" class="userInfoAction" method="addUser"></action>

		<action name="deleteUser" class="userInfoAction" method="deleteUser"></action>

		<action name="editUser" class="userInfoAction" method="editUser"></action>

		<action name="login" class="userInfoAction" method="login"></action>


9.登录页面login.jsp中的ajax请求:

 

 

[javascript] view plain copy print ? 在CODE上查看代码片
  1. $("#btnLogin").click(function(){  
  2.         var message = "";  
  3.         var userName=$('input[name="userName"]').val();  
  4.         var userPass=$('input[name="userPass"]').val();  
  5.         if(userName == ""){  
  6.             alert("请输入用户名!");  
  7.             return;  
  8.         }else if(userPass == ""){  
  9.             alert("请输入密码!");  
  10.             return;  
  11.         }  
  12.         $.ajax({  
  13.                type:"post",  
  14.                url:'login.action?username='+userName+'&password='+userPass,  
  15.                dateType:"json",  
  16.                success:function(data){  
  17.                 var json=eval("("+data+")");  
  18.                    if(json.id=='1'){  
  19.                    alert(json.msg);  
  20.                    return;  
  21.                    }else{  
  22.                    $("#frm").submit();  
  23.                    }  
  24.             }  
  25.            });  
  26.        });  
 $("#btnLogin").click(function(){

			var message = "";

			var userName=$('input[name="userName"]').val();

			var userPass=$('input[name="userPass"]').val();

			if(userName == ""){

				alert("请输入用户名!");

				return;

			}else if(userPass == ""){

				alert("请输入密码!");

				return;

			}

			$.ajax({

                type:"post",

                url:'login.action?username='+userName+'&password='+userPass,

                dateType:"json",

                success:function(data){

				    var json=eval("("+data+")");

                    if(json.id=='1'){

                	   alert(json.msg);

                	   return;

                    }else{

                	   $("#frm").submit();

                    }

			    }

            });

        });


10.为了防止用户在不登陆的情况下,访问其他页面,我们在每一个jsp页面中添加如下代码:

 

 

  1. <%if(null == request.getSession().getAttribute("user")){  
  2.            response.getWriter().write("<script>window.location.href = 'login.jsp'</script>");  
  3.        }  
  4.      %>  
<%if(null == request.getSession().getAttribute("user")){

		   response.getWriter().write("<script>window.location.href = 'login.jsp'</script>");

	   }

     %>


思考
完成上述复杂的功能之后,我们是不是就完成任务了呢?显然不是,我们经过测试我们就会发现,在我们没有登录的情况下,我们确实没有办法访问其他的JSP页面,但是我们可以直接在浏览器中访问struts中配置的action!这依然有很大的漏洞,那我们怎么对action进行拦截呢?也即是对非login.action进行拦截判断,如果用户已经登录,就正常登录,如果用户没有登录,就返回login,让其登录。因此我们需要使用struts2的拦截器。

 

11.拦截器的Java代码

 

  1. /* 
  2.  * $filename: CheckLoginInterceptor.java,v $ 
  3.  * $Date: 2014-1-15  $ 
  4.  * Copyright (C) ZhengHaibo, Inc. All rights reserved. 
  5.  * This software is Made by Zhenghaibo. 
  6.  */  
  7. package edu.njupt.zhb.utils;  
  8.   
  9. import java.util.Map;  
  10.   
  11. import com.opensymphony.xwork2.ActionInvocation;  
  12. import com.opensymphony.xwork2.interceptor.AbstractInterceptor;  
  13.   
  14. import edu.njupt.zhb.action.UserInfoAction;  
  15. import edu.njupt.zhb.bean.Userinfo;  
  16.   
  17. /* 
  18.  *@author: ZhengHaibo   
  19.  *web:     http://blog.csdn.net/nuptboyzhb 
  20.  *GitHub   https://github.com/nuptboyzhb 
  21.  *mail:    [email protected] 
  22.  *2014-1-15  Nanjing,njupt,China 
  23.  */  
  24. public class CheckLoginInterceptor extends AbstractInterceptor{  
  25.   
  26.     /** 
  27.      *  
  28.      */  
  29.     private static final long serialVersionUID = 2092930262572782343L;  
  30.   
  31.     @Override  
  32.     public String intercept(ActionInvocation actionInvocation) throws Exception {  
  33.         // TODO Auto-generated method stub   
  34.         //System.out.println("begin check login interceptor!");   
  35.         // 对LoginAction不做该项拦截   
  36.         Object action = actionInvocation.getAction();  
  37.         if (action instanceof UserInfoAction) {  
  38.             //System.out.println("exit check login, because this is login action.");   
  39.             //UserInfoAction userinfoAction = (UserInfoAction)action;   
  40.             return actionInvocation.invoke();  
  41.         }  
  42.         // 确认Session中是否存在User   
  43.         Map<String,Object> session = actionInvocation.getInvocationContext().getSession();  
  44.         Userinfo user = (Userinfo) session.get("user");  
  45.         if (user != null) {  
  46.             // 存在的情况下进行后续操作。   
  47.             //System.out.println("already login!");   
  48.             return actionInvocation.invoke();  
  49.         } else {  
  50.             // 否则终止后续操作,返回LOGIN   
  51.             System.out.println("no login, forward login page!");  
  52.             return "login";  
  53.         }  
  54.     }  
  55.   
  56. }  
/*

 * $filename: CheckLoginInterceptor.java,v $

 * $Date: 2014-1-15  $

 * Copyright (C) ZhengHaibo, Inc. All rights reserved.

 * This software is Made by Zhenghaibo.

 */

package edu.njupt.zhb.utils;



import java.util.Map;



import com.opensymphony.xwork2.ActionInvocation;

import com.opensymphony.xwork2.interceptor.AbstractInterceptor;



import edu.njupt.zhb.action.UserInfoAction;

import edu.njupt.zhb.bean.Userinfo;



/*

 *@author: ZhengHaibo  

 *web:     http://blog.csdn.net/nuptboyzhb

 *GitHub   https://github.com/nuptboyzhb

 *mail:    [email protected]

 *2014-1-15  Nanjing,njupt,China

 */

public class CheckLoginInterceptor extends AbstractInterceptor{



	/**

	 * 

	 */

	private static final long serialVersionUID = 2092930262572782343L;



	@Override

	public String intercept(ActionInvocation actionInvocation) throws Exception {

		// TODO Auto-generated method stub

		//System.out.println("begin check login interceptor!");

        // 对LoginAction不做该项拦截

        Object action = actionInvocation.getAction();

        if (action instanceof UserInfoAction) {

            //System.out.println("exit check login, because this is login action.");

            //UserInfoAction userinfoAction = (UserInfoAction)action;

            return actionInvocation.invoke();

        }

        // 确认Session中是否存在User

        Map<String,Object> session = actionInvocation.getInvocationContext().getSession();

        Userinfo user = (Userinfo) session.get("user");

        if (user != null) {

            // 存在的情况下进行后续操作。

            //System.out.println("already login!");

            return actionInvocation.invoke();

        } else {

            // 否则终止后续操作,返回LOGIN

            System.out.println("no login, forward login page!");

            return "login";

        }

	}



}


12.拦截器在Struts2中的配置

 

 

  1. <interceptor name="loginIntercepter"  
  2.                 class="edu.njupt.zhb.utils.CheckLoginInterceptor">  
  3.             </interceptor>  
  4.             <!-- 拦截器栈 -->  
  5.             <interceptor-stack name="loginStack">  
  6.                 <interceptor-ref name="defaultStack" />  
  7.                 <interceptor-ref name="loginIntercepter" />  
  8.             </interceptor-stack>  
<interceptor name="loginIntercepter"

				class="edu.njupt.zhb.utils.CheckLoginInterceptor">

			</interceptor>

			<!-- 拦截器栈 -->

			<interceptor-stack name="loginStack">

				<interceptor-ref name="defaultStack" />

				<interceptor-ref name="loginIntercepter" />

			</interceptor-stack>


为每一个action配置拦截器,比如:

 

 

  1. <action name="getStudentList" class="dataGridDemoAction"  
  2.             method="getStudentList">  
  3.             <result type="httpheader"></result>  
  4.             <interceptor-ref name="loginStack" />  
  5.             <result name="login">/login.jsp</result>  
  6.         </action>  
  7.         <action name="addStudent" class="dataGridDemoAction" method="addStudent">  
  8.             <result type="httpheader"></result>  
  9.             <interceptor-ref name="loginStack" />  
  10.             <result name="login">/login.jsp</result>  
  11.         </action>  
  12.         <action name="deleteStudent" class="dataGridDemoAction" method="deleteStudent">  
  13.             <result type="httpheader"></result>  
  14.             <interceptor-ref name="loginStack" />  
  15.             <result name="login">/login.jsp</result>  
  16.         </action>  
  17.         <action name="editStudent" class="dataGridDemoAction" method="editStudent">  
  18.             <result type="httpheader"></result>  
  19.             <interceptor-ref name="loginStack" />  
  20.             <result name="login">/login.jsp</result>  
  21.         </action>  
<action name="getStudentList" class="dataGridDemoAction"

			method="getStudentList">

			<result type="httpheader"></result>

			<interceptor-ref name="loginStack" />

			<result name="login">/login.jsp</result>

		</action>

		<action name="addStudent" class="dataGridDemoAction" method="addStudent">

			<result type="httpheader"></result>

			<interceptor-ref name="loginStack" />

			<result name="login">/login.jsp</result>

		</action>

		<action name="deleteStudent" class="dataGridDemoAction" method="deleteStudent">

			<result type="httpheader"></result>

			<interceptor-ref name="loginStack" />

			<result name="login">/login.jsp</result>

		</action>

		<action name="editStudent" class="dataGridDemoAction" method="editStudent">

			<result type="httpheader"></result>

			<interceptor-ref name="loginStack" />

			<result name="login">/login.jsp</result>

		</action>


当然,对于用户登录的action,我们也配置相应的拦截器:

 

 

  1. <!-- 用户信息Action -->  
  2. <action name="getUserInfoList" class="userInfoAction" method="getUserInfoList">  
  3.     <interceptor-ref name="loginStack" />  
  4.     <result name="login">/login.jsp</result>  
  5. </action>  
  6. <action name="addUser" class="userInfoAction" method="addUser">  
  7.     <interceptor-ref name="loginStack" />  
  8.     <result name="login">/login.jsp</result>  
  9. </action>  
  10. <action name="deleteUser" class="userInfoAction" method="deleteUser">  
  11.     <interceptor-ref name="loginStack" />  
  12.     <result name="login">/login.jsp</result>  
  13. </action>  
  14. <action name="editUser" class="userInfoAction" method="editUser">  
  15.     <interceptor-ref name="loginStack" />  
  16.     <result name="login">/login.jsp</result>  
  17. </action>  
  18. <action name="login" class="userInfoAction" method="login">  
  19.     <interceptor-ref name="loginStack" />  
  20. </action>  
		<!-- 用户信息Action -->

		<action name="getUserInfoList" class="userInfoAction" method="getUserInfoList">

			<interceptor-ref name="loginStack" />

			<result name="login">/login.jsp</result>

		</action>

		<action name="addUser" class="userInfoAction" method="addUser">

			<interceptor-ref name="loginStack" />

			<result name="login">/login.jsp</result>

		</action>

		<action name="deleteUser" class="userInfoAction" method="deleteUser">

			<interceptor-ref name="loginStack" />

			<result name="login">/login.jsp</result>

		</action>

		<action name="editUser" class="userInfoAction" method="editUser">

			<interceptor-ref name="loginStack" />

			<result name="login">/login.jsp</result>

		</action>

		<action name="login" class="userInfoAction" method="login">

			<interceptor-ref name="loginStack" />

		</action>


总结:

 

以上步骤完成之后,我们基本上就完成了一个简单的用户登录模块的设计和实现了。而且我们可以根据用户的权限,显示不同的内容。比如管理员和普通操作员等具有不同的操作权限。

说明:

以上代码只是一些代码片段,我这里主要介绍的是思路。以上代码还有一些小小的漏洞,比如,我们在没有登录的情况下,还是可以直接访问getUserinfoList、deleteUser、editUser等与login在同一个Action类中的action。因此,我们设计的时候,要尽量将login和logout单独一个action。还有:上面写的getUserinfoList等一些action,目的是管理员对用户表进行增删改查等操作的,和本博客关系不大。本文主要注意的是:一个是在jsp页面中对未登陆用户的拦截,还有就是通过配置Struts2的拦截器,对未登录用户直接访问action方式进行拦截的。

你可能感兴趣的:(java)