Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2308081
  • 博文数量: 252
  • 博客积分: 5472
  • 博客等级: 大校
  • 技术积分: 3107
  • 用 户 组: 普通用户
  • 注册时间: 2011-09-17 18:39
文章分类

全部博文(252)

文章存档

2012年(96)

2011年(156)

分类: Java

2011-12-23 11:16:04

1   在逻辑处理代码中 保存逻辑错误的全局信息
2   在JSP页面中 使用来输出全局信息
 
 
以登录验证为例
 
1  登录时 验证是否登录成功  LoginAction
在类LoginAction的execute()中 如果登录不成功 或代码抛出异常 此时保存一个全局错误信息
 
部分代码
  1. public ActionForward execute(ActionMapping mapping, ActionForm form,
  2.             HttpServletRequest request, HttpServletResponse response)
  3.             throws Exception {

  4.         ActionErrors errors = new ActionErrors();
  5.         ActionForward forward = new ActionForward();
  6.         LoginForm loginForm = (LoginForm) form;

  7.         try {
  8.             // get parameters

  9.             String username = loginForm.getUsername();

  10.             // invalidate the original session if exists

  11.             HttpSession session = request.getSession(false);
  12.             if (session != null) {
  13.                 session.invalidate();
  14.             }

  15.             // create a new session for the user

  16.             session = request.getSession(true);

  17.             // login

  18.             boolean isValid = valid(request, loginForm);
  19.             if (isValid) {
  20.                 session.setAttribute(Constants.USERNAME_KEY, username);

  21.                 log.info("User " + username + " login.");
  22.             } else {
  23.                 errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage(
  24.                         "login.message.failed"));
  25.             }

  26.         } catch (Exception e) {
  27.             errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage(
  28.                     "login.message.failed"));

  29.         }

  30.         // If a message is required, save the specified key(s)

  31.         // into the request for use by the tag.


  32.         if (!errors.isEmpty()) {
  33.             saveErrors(request, errors);
  34.             request.setAttribute("loginFormBean", loginForm);
  35.             forward = mapping.findForward(Constants.FAILURE_KEY);
  36.         } else {
  37.             forward = mapping.findForward(Constants.SUCCESS_KEY);
  38.         }

  39.         // Finish with

  40.         return (forward);
  41.     }

 

 

2  在上面的代码中 添加一个资源引用的标签 我们在ApplicationResources_temp.properties中添加如下

 

  1. # loginAction
  2. login.message.failed=用户名或者密码不存在!

并使用命令native2ascii转换更新到ApplicationResources_zh_CN.properties 同样的 也需要在ApplicationResources.properties中添加英文的标签

 

3   再JSP页面login.jsp中输出这个全局错误信息

 

  1. <html:errors property="org.apache.struts.action.GLOBAL_MESSAGE" />
阅读(1304) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~