日期:2014-05-17  浏览次数:20789 次

最近一段是在是被web项目的路径折磨的不行了,来咨询下。这个帖子是咨询配置文件的生成路径的。
这么一个servlet主要是GET进来检测,读不到流的话是新的,进入初始页,POST提交上来的生成配置文件内容,再定向给GET,检测到配置文件了就初始化完毕了,进入网站内容,以后就不会进入初始化页面了。


public class Redirect extends HttpServlet
{
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletExceptionIOException
{
InputStream inStream = Redirect.class.getClassLoader().getResourceAsStream("com/yulei/bank/web/userconfig.properties");
if (inStream == null)
{
request.getRequestDispatcher("/WEB-INF/jsp/init.jsp").forward(request, response);
}
else
{
Properties props = new Properties();
props.load(inStream);

ServletContext application = this.getServletContext();
application.setAttribute("bankPrefix", props.getProperty("bankPrefix"));
application.setAttribute("bankName", props.getProperty("bankName"));

request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
}
}

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String bankPrefix = request.getParameter("bankPrefix");
String bankName = request.getParameter("bankName");

String url = request.getParameter("url");
String username = request.getParameter("username");
String password = request.getParameter("password");

// 生成userconfig.properties
// bankPrefix=
// bankName=

Properties props = new Properties();
props.setProperty("bankPrefix", bankPrefix);
props.setProperty("bankName", bankName);

props.store(new FileOutputStream("userconfig.properties"),"init");

// 修改dbcpconfig.properties的数据库、用户名、密码
// url=jdbc:mysql://localhost:3306/test
// username=root
// password=root

request.getRequestDispatcher("/redirect").forward(request, response);
}

}


但是在这句时候
props.store(new FileOutputStream("userconfig.properties"),"init");
路径问题很困扰我。

直接这么写就生成到tomcat的bin下面了。

自己还在考虑的是,部署时候只有WebRoot以下的,因为我这个文件时部署后才在运行时生成的,是不是应该把目录指向到WebRoot\WEB-INF\classes里面

我不知道怎么生成相对路径的文件,每次都是获取硬盘路径后再生成的文件,所以很困惑。

求知道下!


基本的路径获取是知道的。

java项目根路径:System.getProperty("user.dir")
但是这里是项目部署后跑起来才生成的,所以这个PASS掉。

web项目的当前类的目录this.getClass().getResource("").getPath().substring(1)
但是这个在部署后跑起来是获取到路径了,但是生成时候
String temp =this.getClass().getResource("").getPath().substring(1);
props.store(new FileOutputStream(temp+"userconfig.properties"),"init");
D:\Program%20Files\apache-tomcat-6.0.37\webapps\ccb1\WEB-INF\classes\com\yulei\bank\web\userconfig.properties (系统找不到指定的路径。)

然后我就闷了,请问像这样,部署后,根据配置web页面提交的信息生成的文件应该写在什么路径下呢?
------解决方案--------------------
如果unix环境下运行,一般会取绝对路径,还可以用Java针对路径写个方法来处理它。
给你思路,想想解决方法。
------解决方案--------------------
Quote: 引用:

如果unix环境下运行,一般会取绝对路径,还可以用Java针对路径写个方法来处理它。
给你思路,想想解决方法。