开发者

JSP resourceBundle

I have no problem loading and using properties file from JSP files which are located in the root of website (using ResourceBundle class) but when I try to load the same properties file from a JSP which is located in a directory it fails and says the resource can not be found!

Code of the page which is located in a directory

<%@page import="org.apache.log4j.Logger"%>
<%@page import="com.persiangulfcup.utility.LogUtils"%>
<%@page import="java.util.ResourceBundle"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
  Logger logger = LogUtils.getLogger("page/contact");
  ResourceBundle lbls = null;
  ResourceBundle msgs = null;
  try {
    lbls = ResourceBundle.getBundle("labels");
    msgs = ResourceBundle.getBundle("messages");
  } catch (Exception ex) {
    logger.fatal(ex);
  }
%>
<div class="form">
  <div style="text-align: left; font: normal bold 14px arial; cursor: pointer" onclick="contactBox.hide();">X</div>
  <div style="padding-bottom: 10px;font-size: 14px; text-align: center"><%=msgs.getString("contactHeader")%></div>
  <form id="frmContact" onsubmit="try {sendContact();} catch (e) {console.log(e)} return false;">
    <table class="form">
      <tr>
        <td class="caption"><%=lbls.getString("name")%>: </td>
        <td class="data">
          <input id="txtName" type="text" name="txtName"/>
        </td>
      </tr>
      <tr>
        <td class="caption"><%=lbls.getString("email")%>: </td>
        <td class="data">
          <input id="txtEmail" type="text" name="txtEmail"/>
        </td>
      </tr>
      <tr>
        <td class="caption"><%=lbls.getString("subject")%>: </td>
        <td class="data">
          <input id="txtSubject" type="text" name="txtSubject"/>
        </td>
      </tr>
      <tr>
        <td class="caption"><%=lbls.getString("message")%>: </td>
        <td class="data">
          <textarea id="txtMessage" name="txtMessage"></textarea>
        </td>
      </tr>
      <tr>
    开发者_C百科    <td class="button" colspan="2"><input type="submit" value="<%=lbls.getString("send")%>"/></td>        
      </tr>
      <tr>
        <td style="text-align: center" colspan="2" id="brdContact"></td>        
      </tr>
    </table>
  </form>
</div>


This is because you didn't respect a golden rule: don't put anything in the default package. A resource bundle is loaded as a class, from the classpath. It has a fully qualified name, which must be used to load it. And it's not possible to use a class in the default package from a class not in the default package.

So, put your resource bundle in an appropriate package (example : com.persiangulfcup.foo.bar), and load them like this : ResourceBundle.getBundle("com.persiangulfcup.foo.bar.labels").

That said, using scriptlets inside JSPs is a bad practice. You should really use the JSTL, which has a fmt library allowing to use resource bundles, format messages, etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜