jquery-ajax请求action读取oracle数据库clob字段xml数据格式化显示(struts2)

1.页面js

function showXML(aa,bb){
			$.ajax({
				url : encodeURI("showXML.action?aa="+aa+"&bb="+bb),
				type : 'POST',
				dataType : "html",
				success : function(data) {
				document.getElementById('mainContent').innerText = data;
					
				}
			});
	}

2.action类

public String showXML() throws IOException, SQLException, SAXException, ParserConfigurationException, DocumentException{  
          
        HttpServletRequest request=ServletActionContext.getRequest();  
        HttpServletResponse response=ServletActionContext.getResponse();  
        response.setContentType("text/xml;charset=utf-8"); //(1)一定要在(2)的前面,不然会乱码    
        response.setCharacterEncoding("UTF-8"); //(2)    
        response.setHeader("Cache-Control", "no-cache");     
        PrintWriter pw=response.getWriter();    
          
        String aa=request.getParameter("aa");  
        String bb=request.getParameter("bb");  
          
        JavBean javaBean=xmlService.showXML(aa, bb);  
          
        Clob clob=javaBean.getClobXml();  
          
//      String msgXML=clob.getSubString(1L,(int)clob.length());  
          
//      InputStream input = clob.getAsciiStream();    //乱码  
//        int len = (int)clob.length();  
//        byte[] by = new byte[len];  
//        int i ;  
//        while(-1 != (i = input.read(by, 0, by.length))) {  
//            input.read(by, 0, i);  
//        }  
//      String msgXML = new String(by);  
        
		//CLOB转String
        Reader inStreamDoc = clob.getCharacterStream();     
        char[] tempDoc = new char[(int) clob.length()];     
        inStreamDoc.read(tempDoc);     
        inStreamDoc.close();     
        
        String msgXML= new String(tempDoc);     
  
//      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
//      Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(msgXML.getBytes()));  
            
		//格式化xml字符串
        SAXReader reader = new SAXReader();  
        Document _document =  reader.read(new StringReader(msgXML));  //dom4j,not w3c
        String paramXML = "";  
        OutputFormat format = OutputFormat.createPrettyPrint();  
        format.setEncoding("utf-8");              
        ByteArrayOutputStream out = new ByteArrayOutputStream();   
        XMLWriter writer = new XMLWriter(out, format);   
        writer.write(_document);  
        
        writer.toString();  
        writer.flush();  
        writer.close();  
            
            
        paramXML = out.toString(format.getEncoding()); 
		
		//页面显示 
        StringBuilder sb=new StringBuilder();    
        sb.append(paramXML);  
          
        pw.print(sb.toString());    
        pw.flush();    
        pw.close();   
        return "success";  
    }  



你可能感兴趣的:(jquery-ajax请求action读取oracle数据库clob字段xml数据格式化显示(struts2))