在JSP中可以通过以下方式获取:<%String SERVER_NAME = (String)application.getAttribute("SERVER_NAME");%>
在servlet中可以通过以下方式获取:String SERVER_NAME =(String)context.getAttribute("SERVER_NAME");
在servlet中可以通过以下方式获取:String SERVER_NAME =(String)context.getAttribute("SERVER_NAME");
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();out.println("<html>");out.println("<head>");out.println("<title>Parameter Servlet</title>");out.println("</head>");out.println("<body>");// Get an enumeration of the parameter namesEnumeration parameters = request.getParameterNames();String param = null;// Iterate over the paramater names,// getting the parameters valueswhile ( parameters.hasMoreElements() ) {param = (String)parameters.nextElement();out.println(param + " : " +request.getParameter(param) +"<BR>");}out.println("</body></html>");out.close();}
在bean中
ServletContext sc=request.getSession().getServletContext();
String serverName=(String)sc.getAttribute("SERVER_NAME");在 servlet 中如何用getAttribute("SERVER_NAME"),得到"SERVER_NAME"值在servlet中
String serverName=getServletContext().getAttribute("SERVER_NAME");
在bean中
有没有不需要传request得到 "SERVER_NAME "的方法?
比如我有一个普通bean:log类,需要加载log4j.properties
我需要获得web的根路径请问如何能够获得?
try {
props.load(this.getClass().getResourceAsStream("/log4j.properties"));
//这个路径对应web-inf/classes/log4j.properties
}
catch(IOException e) {
//........
}
我想有这样一种理想情况:
服务器启动后,直到服务器关闭,期间一直存在一个或多个变量或多个集合,我可以随心所欲的使用
这些变量是无法在xml文件中配置的,因为事先不知道,比如说web运行的根路径等于是我就想在servlet中初始化好这些变量,以后可以方便的使用
如果我的log4j.properties不在web-inf/classes下,props.load(this.getClass().getResourceAsStream( "/log4j.properties ")); 恐怕就不起作用了
依你的意思,log4j.properties放哪儿呢?
一开始也是为了load文件,文件在根路径下,servlet初始化的时候得到web根路径,放在"SERVER_NAME"中
String prefix = getServletContext().getRealPath( "/");
ServletContext context = getServletContext();
context.setAttribute("SERVER_NAME",prefix); 然后就是在bean中得到这个路径"SERVER_NAME"的值
或者不需要初始化直接在bean中得到也可以啊其实就是一个问题,呵呵,简单的说就是在普通bean中如何得到web根路径的问题
方法2可能更符合你的要求,如果你想更灵活一些,可以通过(/F:/docs/WEB-INF/classes/)在整个(/F:/docs)目录来搜索log4j.properties的位置。
晚上结贴,我好像还有一个贴没结,一并结了:)