用户登录功能以及登录拦截

一、用户登录

        思路:jsp实现表单提交,action用模型驱动的方式接收数据,在数据库查找有没有与之匹配的记录,若没有,回到登录界面(并将用户填的数据回显,并给出错误提示),若有,进入首页,显示用户名

1、jsp页面

账号:
密码:

2、action

public class LoginAction extends ActionSupport implements ModelDriven {
	private User user = new User();
	UserService service = new UserService();
	
	public String login() {
		List list = service.login(user);
		if (list.size()==0) {
			this.addActionError("您输入的信息有误!");
			ServletActionContext.getRequest().getSession().setAttribute("user", user);
			return LOGIN;
		}else {
			ServletActionContext.getRequest().getSession().setAttribute("user", list.get(0));
			return SUCCESS;
		}
	}
	
	@Override
	public User getModel() {
		return user;
	}
	
}

3、配置struts2.xml


	
		/index.jsp
		/login.jsp
	

4、service及dao层实现

public class UserService {
	UserDao dao = new UserDao();
	public List login(User user) {
		return dao.login(user);
	}
	
}

public List login(User user) {
	Session session = HibernateUtils.openSession();
	Transaction ts = session.beginTransaction();
	Query query = session.createQuery("from User where user_name=? and user_password=? and user_code=?");
	query.setParameter(0, user.getUser_name());
	query.setParameter(1, user.getUser_password());
	query.setParameter(2, user.getUser_code());
	List list = query.list();
	ts.commit();
	session.close();
	return list;
}

效果:

失败>>

用户登录功能以及登录拦截_第1张图片

成功>>

用户登录功能以及登录拦截_第2张图片

二、登录拦截

1、编写拦截器(继承MethodFilterInterceptor类)

public class LoginInterceptor extends MethodFilterInterceptor {

	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		User user = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
		if (user == null) {
//			未登录
			ActionSupport actionSupport = (ActionSupport) invocation.getAction();
			actionSupport.addActionError("您没有权限,请先登录!");
			return actionSupport.LOGIN;
		}else {
//			已经登录
			return invocation.invoke();
		}
	}
	
}

2、添加配置文件


		
	
		
	
	
		/login.jsp
	
	
		/success.jsp
		/jsp/customer/list.jsp
		/jsp/customer/edit.jsp
		
		
		
		
	
	
		/index.jsp
		
		
		
		
			login
		
	

用户登录功能以及登录拦截_第3张图片

有一个问题,当我们在这个页面点击登录后,会产生页面嵌套的效果,只要在login.jsp表单提交的form中修改一个属性即可

你可能感兴趣的:(三大框架)