---
title: "jsp加载常量的探讨"
author: "J2EE大鸟"
date: "2012-12-24T10:43:26Z"
tags: []
categories: ["编程语言"]
slug: "jsp"
draft: false
lastmod: "2012-12-24T10:43:26Z"
id: 1752484
url: "https://benworld.iteye.com/blog/1752484"
---

今天遇到了一个jsp加载常量的问题：

代码如下：

 

```
public class SystemConstant {
    public static final int LSSV = 188;

    public int OFD = 1;
}
```

 

jsp页面代码如下：

 

```
<%@page import="com.zj.logistics.util.SystemConstant"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>  
  <% 
  	out.println("static:" + SystemConstant.LSSV);
  	out.println("not static:" + new SystemConstant().OFD);
  %>
</body>
</html>
```

 

启动tomcat，结果也很简单：页面输出 static：188    not static：1  

 

但是将systemconstant中的LSSV改为126， 将OFD的值改为2时，保存之后，jsp页面不要动，问题出现了：

页面显示：static：188    not static：2

即， LSSV的值没有在界面上发生改变。

想了很多办法：1.重新部署项目；2.重新编译项目；3.重新启动tomcat；4.重新启动电脑。均不成功

最终只有一个办法可行，即，tomcat运行，稍对jsp页面加以改动，比如任意位置多加一个空格，保存。刷新浏览器，成功。

 

 究其原因：

1.在最终一个方法上，tomcat对该jsp页面重新reloading，重新编译，生成了新的class文件，使得访问成功。

2.前几种方法的失败，可能在该jsp的class文件中，保持着对static final int LSSV的值引用，即在class中放入的是具体的值，而非内存地址。。

测试发现，将static final int LSSV 改为 static final Integer LSSV后，不存在上述问题，即改为Integer后，jsp的class中保持着对该变量的地址引用。。

 

困扰：

如果项目很大，systemconstant中很多常量，并且jsp中也引用了这些常量，难道有一天要修改systemconstant中的常量，要对每个jsp都保存一遍么？

 

上述中有一种办法可以解决，即用搜索办法，将systemconstant中的int替换成了Integer，但是也留下了隐患。。

例如：

 

 

```
switch(method) {
		case SystemConstant.UFSV_UPLOADUI : 
			this.gotoUploadFileUI(request, response); break;
		case SystemConstant.UFSV_UPLOAD : 
			this.uploadFile(request, response); break;
```

 你后端使用的是switch条件判断，在jdk 7版本以下，case后面的参数要求是常量类型，将int改你为Integer以后，会报错，并且如何将Integer类型转换为常量类型（static final int），也没有找到合适的办法。。

 

还有一种办法，是将D:\\apache-tomcat-7.0.27\\work\\Catalina\\localhost\\项目名\\org\\apache\\jsp\\WEB\_002dINF 目录下对应jsp的java和class文件删除，这样也可以达到目的。。