设为首页 收藏本站
查看: 674|回复: 0

[经验分享] JSP 自己写的在JSP页面得到文件的服务器路径,并对XML文件进行读写(以对Tomcat的conf目录中的context.xml文件为例)

[复制链接]

尚未签到

发表于 2017-2-11 06:28:20 | 显示全部楼层 |阅读模式
  得到服务器的文件的绝对路径:
  <%!//获取服务器根目录String serPath = this.getClass().getResource("/").getPath();int indTom = serPath.indexOf("Tomcat");String be = serPath.substring(0,indTom);//处理后得到context.xml文件的绝对路径String conf = be + serPath.substring(serPath.indexOf("Tomcat")).substring(0,serPath.substring(serPath.indexOf("Tomcat")).indexOf("/"))+"/conf/context.xml";%><%//将路径中符号转变成空格,这样得到的conf就是文件的绝对路径conf = conf.replaceAll("%20", " ");   %>
  完整列子:
  <%@ page language="java" import="java.util.*,org.w3c.dom.*,java.io.*" pageEncoding="GBK"%><%@ page import="javax.servlet.http.HttpServletRequest,javax.xml.transform.stream.*,org.w3c.dom.*,javax.xml.transform.*,javax.xml.parsers.*,javax.xml.transform.dom.*" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%!//属性项集合Map att = new HashMap<String, String>();String userName = "";String pass = "";String databaseType = "";String url = "";String databaseName = "";//将修改的内容添加到xml文件中// // @param document// @param filename// @returnpublic static boolean doc2XmlFile(Document document, String filename) {boolean flag = true;try {/** 将document中的内容写入文件中 */TransformerFactory tFactory = TransformerFactory.newInstance();Transformer transformer = tFactory.newTransformer();/** 编码 */// transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");DOMSource source = new DOMSource(document);StreamResult result = new StreamResult(new File(filename));transformer.transform(source, result);} catch (Exception ex) {flag = false;ex.printStackTrace();}return flag;}//读取xml文件// // @param filename// @returnpublic static Document load(String filename) {Document document = null;try {DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = factory.newDocumentBuilder();document = builder.parse(new File(filename));document.normalize();} catch (Exception ex) {ex.printStackTrace();}return document;}/*** 演示修改文件的具体某个节点的值*/public static void xmlUpdateDemo() {Document document = load("c://Message.xml");Node root = document.getDocumentElement();/** 如果root有子元素 */if (root.hasChildNodes()) {/** ftpnodes */NodeList ftpnodes = root.getChildNodes();/** 循环取得ftp所有节点 */for (int i = 0; i < ftpnodes.getLength(); i++) {NodeList ftplist = ftpnodes.item(i).getChildNodes();for (int k = 0; k < ftplist.getLength(); k++) {Node subnode = ftplist.item(k);//修改节点的值if (subnode.getNodeType() == Node.ELEMENT_NODE&& subnode.getNodeName() == "status") {subnode.getFirstChild().setNodeValue("1");}}}}doc2XmlFile(document, "c://Message.xml");}// 演示修改文件的具体某个节点的属性public static void xmlUpdateDemoAttri() {Document document = load("c://xx.xml");Node root = document.getDocumentElement();/** 如果root有子元素 */if (root.hasChildNodes()) {/** ftpnodes 根节点的子节点 */NodeList ftpnodes = root.getChildNodes();/** 循环取得第一层子节点所有节点 */for (int i = 0; i < ftpnodes.getLength(); i++) {Node subnode = ftpnodes.item(i);//添加或修改某节点的属性配置if ("Resource".equals(subnode.getNodeName())) {// 生成一个属性对象Attr attr = document.createAttribute("ss");attr.setValue("ssss");subnode.getAttributes().setNamedItem(attr);}}}// 将修改的内容添加到xml文件中doc2XmlFile(document, "c://xx.xml");}//添加新的节点// 根节点下没有节点的话直接添加// 根节点下没有重名的直接添加// 有重名的节点则更新节点属性// @param nodeName 添加、更新的节点名// @param attr 属性集合public static void xmlAddDemoAttri(String filePath,String nodeName,Map<String, String> attr) {Document document = load(filePath);Node root = document.getDocumentElement();//创建节点元素,并命名Element element =document.createElement(nodeName);//向节点中添加属性for (Object key : attr.keySet().toArray()) {element.setAttribute(key.toString(), attr.get(key));}//找到根节点NodeList nodeList = document.getElementsByTagName("Context");//先判断根节点下有没有子节点,没有的话直接添加Node rootNode = nodeList.item(0);if(!root.hasChildNodes()){nodeList.item(0).appendChild(element);}else{//如果有重复的节点,flag=true;boolean flag = false;NodeList rootChs = rootNode.getChildNodes(); //循环根节点下的所有子节点 for (int i = 0; i < rootChs.getLength(); i++) {Node node = rootChs.item(i);//如果没有重名,并且是最后一个节点的就添加if(!nodeName.equals(node.getNodeName()) && !flag && (i+1) == rootChs.getLength()){nodeList.item(0).appendChild(element);}else if(nodeName.equals(node.getNodeName())){     //有重名的就看name属性,name一样就修改属性if(node.hasAttributes()){//如果有属性项,判断name属性值,如果name的值相同,则修改其他属性if(null != node.getAttributes().getNamedItem("name") && attr.get("name").equals(node.getAttributes().getNamedItem("name").getNodeValue())){// 生成一个属性对象Attr chAttr = null;//向节点中添加属性for (Object key : attr.keySet().toArray()) {//不更新name属性if(!"name".equals(key.toString())){chAttr = document.createAttribute(key.toString());chAttr.setValue(attr.get(key));}}node.getAttributes().setNamedItem(chAttr);}else if(null != node.getAttributes().getNamedItem("name") && !attr.get("name").equals(node.getAttributes().getNamedItem("name").getNodeValue()) && !flag && (i+1) == rootChs.getLength()){//如果name的值不相同,且都没有相同的节点,添加新的节点System.out.println(attr.get("name"));System.out.println(node.getAttributes().getNamedItem("name").getNodeValue());nodeList.item(0).appendChild(element);}}}}}// 将修改的内容添加到xml文件中doc2XmlFile(document, filePath);}%><%!//获取服务器根目录String serPath = this.getClass().getResource("/").getPath();int indTom = serPath.indexOf("Tomcat");String be = serPath.substring(0,indTom);//处理后得到context.xml文件的绝对路径String conf = be + serPath.substring(serPath.indexOf("Tomcat")).substring(0,serPath.substring(serPath.indexOf("Tomcat")).indexOf("/"))+"/conf/context.xml";%><%//将路径中符号转变成空格conf = conf.replaceAll("%20", " ");    //添加属性项userName = request.getParameter("userName");url = request.getParameter("url");pass = request.getParameter("pass");databaseType = request.getParameter("databaseType");databaseName = request.getParameter("databaseName");//如果是SqlServer的修改att.put("username", userName);att.put("password", pass);att.put("name", "jdbc/sqlserver-database");att.put("url", url+":1433;databaseName="+databaseName+";SelectMethod=cursor");att.put("type", "javax.sql.DataSource");att.put("driverClassName", "net.sourceforge.jtds.jdbc.Driver");att.put("maxIdle", "5");att.put("maxWait", "5000");att.put("maxActive", "100");try{xmlAddDemoAttri(conf ,"Resource",att);}catch(Exception e){}finally{%><mce:script type="text/javascript"><!--alert("配置完成,请重启Tomcat服务!");window.close();// --></mce:script> <%}%>

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-340367-1-1.html 上篇帖子: 使用Ant构建web项目 从编译到测试 生成测试报告 打包 邮件发送 远程下载tomcat 部署运行一条龙服务之ant脚本 下篇帖子: 抛弃LCDS和FMS,在tomcat下开发Red5应用(第四篇)-客户端和服务器端的方法互相调用
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表