以下为struts2的BaseAction里的处理方法。
- public HttpServletResponse getResponse()
- {
- return ServletActionContext.getResponse();
- }
- public HttpSession getSession(boolean flag)
- {
- return this.getRequest().getSession(flag);
- }
- /**
- * 获取当前登录的会员信息
- * @return
- */
- public Member getLoginMember() throws Exception
- {
- Member member=null;
- String memberId=this.getCookieValue("memberId");
- String memberName=this.getCookieValue("memberName");
- String grade=this.getCookieValue("grade");
- String subject=this.getCookieValue("subject");
- if(memberId!=null&&memberName!=null&&grade!=null&&subject!=null)
- {
- member=new Member();
- member.setMemberId(Integer.valueOf(memberId));
- member.setMemberName(memberName);
- member.setGrade(Integer.valueOf(grade));
- member.setSubject(Integer.valueOf(subject));
- }
- return member;
- }
- /**
- * 获取指定Cookie的值
- * @param cName
- * @return
- * @throws Exception
- */
- public String getCookieValue(String cName) throws Exception
- {
- String cValue=null;
- Cookie cookie=this.getCookie(cName);
- if(cookie!=null)
- {
- cValue=cookie.getValue();
- }
- return cValue;
- }
- /**
- * 获取指定Cookie
- * @param cName
- * @return
- * @throws Exception
- */
- public Cookie getCookie(String cName) throws Exception
- {
- Cookie cookie=null;
- Cookie[] cs=this.getRequest().getCookies();
- if(cs!=null)
- {
- for(Cookie c:cs)
- {
- String name=c.getName();
- if(cName.equals(name))
- {
- cookie=c;
- }
- }
- }
- return cookie;
- }
- /**
- * 将设置cookie独立出来便于对cookie的配置统一控制
- * @param sName
- * @param sValue
- */
- public void addACookie(String cName,String cValue) throws Exception
- {
- Cookie cookie=new Cookie(cName,cValue);
- cookie.setMaxAge(365*24*60*60);
- this.getResponse().addCookie(cookie);
- }
- /**
- * 将登录的用户信息存放到cookie中
- * @param member
- */
- public void setLoginMember(Member member) throws Exception
- {
- this.addACookie("memberId",member.getMemberId().toString());
- this.addACookie("memberName",member.getMemberName());
- this.addACookie("grade",member.getGrade().toString());
- this.addACookie("subject",member.getSubject().toString());
- }
- /**
- * 删除所有Cookie
- * @throws Exception
- */
- public void invalidateCookies() throws Exception
- {
- Cookie[] cs=this.getRequest().getCookies();
- if(cs!=null)
- {
- for(Cookie c:cs)
- {
- c.setMaxAge(0);
- this.getResponse().addCookie(c);
- }
- }
- }