Java struts2 xml

hi mates,
Plese give me some clues for some of my questions.
I stored xml file data as xmlType in oracle database.
I am also using struts 2 for the project.
I wanna retrieve that whole xml file in the form of string and send them to the client html table. How can I catch that whole string xml file from client side with or without using the strut 2 features, objects are on the memory.
Second question is , how could I send the xml file data in string format back to server? I do appreciate for ur help. cheers.

use a simple servlet to send xml data.
example 1
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SendXml extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    //get the 'file' parameter
    String fileName = (String) request.getParameter("file");
    if (fileName == null || fileName.equals(""))
      throw new ServletException(
          "Invalid or non-existent file parameter in SendXml servlet.");
    // add the .doc suffix if it doesn't already exist
    if (fileName.indexOf(".xml") == -1)
      fileName = fileName + ".xml";
    String xmlDir = getServletContext().getInitParameter("xml-dir");
    if (xmlDir == null || xmlDir.equals(""))
      throw new ServletException(
          "Invalid or non-existent xmlDir context-param.");
    ServletOutputStream stream = null;
    BufferedInputStream buf = null;
    try {
      stream = response.getOutputStream();
      File xml = new File(xmlDir + "/" + fileName);
      response.setContentType("text/xml");
      response.addHeader("Content-Disposition", "attachment; filename="
          + fileName);
      response.setContentLength((int) xml.length());
      FileInputStream input = new FileInputStream(xml);
      buf = new BufferedInputStream(input);
      int readBytes = 0;
      while ((readBytes = buf.read()) != -1)
        stream.write(readBytes);
    } catch (IOException ioe) {
      throw new ServletException(ioe.getMessage());
    } finally {
      if (stream != null)
        stream.close();
      if (buf != null)
        buf.close();
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
example 2
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ResourceServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    //get web.xml for display by a servlet
    String file = "/WEB-INF/web.xml";
    URL url = null;
    URLConnection urlConn = null;
    PrintWriter out = null;
    BufferedInputStream buf = null;
    try {
      out = response.getWriter();
      url = getServletContext().getResource(file);
      //set response header
      response.setContentType("text/xml");
      urlConn = url.openConnection();
      //establish connection with URL presenting web.xml
      urlConn.connect();
      buf = new BufferedInputStream(urlConn.getInputStream());
      int readBytes = 0;
      while ((readBytes = buf.read()) != -1)
        out.write(readBytes);
    } catch (MalformedURLException mue) {
      throw new ServletException(mue.getMessage());
    } catch (IOException ioe) {
      throw new ServletException(ioe.getMessage());
    } finally {
      if (out != null)
        out.close();
      if (buf != null)
        buf.close();
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
}Hope That Helps

Similar Messages

  • Differnce between java script xml dom and Java Xml dom

    Hi,
    In my application For client side in Java Script for craetion of DOM MIcrosoft Activex object is used. USing that one they are buiidng DOM. And they are saving as XML. In server side i have to write one servlet which will parse that xml and i have to store in dynamic arrays.Which API is better for parsing XML in java.In util pacakge which class is better for storing dynamical values that means MAP,Hash Map,Hash table ??

    in java, the java..xml.parsers package is generally used for parsing xml into a DOM. there are also sax and stax parsers available.
    which class in java.util is better for storing stuff depends on what you need to do with the stuff. find a nice tutorial on java collections and then decide which one makes sense for what you need.

  • Help with Java to XML

    All I need to know is how to bold the tag <CompanyID> </CompanyID> OR the text within it (1001, in given sample).
    Here's a sample line of the data.txt file I'm working with:
    1001,"Fitzsimmons, Des Marteau, Beale and Nunn",109,"COD","Standard",,109,8/14/1998 8:50:02
    Thanks in advance!
    public class PracticeExerciseOne {
        public static void main(String [] args){
            DocumentBuilderFactory domFac = null;
            DocumentBuilder domBuild = null;
            //Element tags
            final String COMPANY = "Companies";
            final String COMPANY_ID = "CompanyID";
            //rest too long to post
            //Regex to be used for each field in the CSV file
            ArrayList<Pattern> patterns = new ArrayList<Pattern>();
            patterns.add(Pattern.compile("[0-9]+,"));
            patterns.add(Pattern.compile("\".+?\","));
            patterns.add(Pattern.compile("[0-9]+,"));
            patterns.add(Pattern.compile("\".+?\","));
            patterns.add(Pattern.compile("\".+?\","));
            patterns.add(Pattern.compile("[^,]*,"));
            patterns.add(Pattern.compile("[0-9]+,"));
            patterns.add(Pattern.compile("[^,]+ [^,]+"));
            //Store element tags in an array - too long to post
            try{
                //Build a new documet
                domFac = DocumentBuilderFactory.newInstance();
                domBuild = domFac.newDocumentBuilder();
                Document doc = domBuild.newDocument();
                //Create a new root element
                Element rootElement = doc.createElement(COMPANY);
                doc.appendChild(rootElement);
                //Read in the file
                BufferedReader in = new BufferedReader(new FileReader(new File("texts/data.txt")));
                BufferedWriter out = new BufferedWriter(new FileWriter(new File("texts/dataOut.xml")));
                int tempI;
                String line = in.readLine();
                //We will cut this string down after every element we take out of it
                String temp = line;
                String tempElement = "";
                while(line != null){
                    for(int i = 0; i < patterns.size(); i++){
                        //Matches a pattern to a field, starting with the first pattern
                        //Matchup should be 1st pattern = 1st field
                        Matcher matcher = patterns.get(i).matcher(temp);
                        if(matcher.find()){
                            //if we haven't reached the last field
                            if(i != 7){
                                //we want to get the index of the last comma within the matched group
                                tempI = matcher.group().lastIndexOf(',');
                                //create an element using the beginning of the given string and the last comma within that data
                                tempElement = temp.substring(0,tempI);
                            else{
                                //no comma in last field, so we just want to get the whole field
                                tempI = 0;
                                tempElement = temp.substring(0);
                            //if an empty element appears, add a space for tags to be placed correctly
                            if(tempElement.equals("")){
                                tempElement = " ";
                            //temp will be set to the remaining string, once we have taken the nth field out
                            temp = temp.substring(tempI+1);
                            //create an element with tags and append to document
                            Element em = doc.createElement(tags);
    em.appendChild(doc.createTextNode(tempElement));
    rootElement.appendChild(em);
    line = in.readLine();
    temp = line;
    //Transformer will create a new XML document using the Document we have built
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(out);
    transformer.transform(source, result);
    out.close();
    in.close();
    catch(Exception e){
    System.err.println("Exception: " + e.getMessage());
    e.printStackTrace();

    maybe this can help You for now and future,
    in this site You can download a sample codes publish in this books - java fundamentals and advanced features.,
    in 2nd book, is a big chapter about java and xml. Please read this code, i will hope, this can help You.
    http://www.horstmann.com/corejava.html (for mod: this is not SPAM)

  • Marshalling Java to XML using JAXB

    Hi,
    I have just downloaded the JAXB reference implementation and have been trying out marshalling Java objects to XML.
    I have a very basic question - can I convert the data from my Java classes into XML and simply send it as a String to another object instead of only having to write it out into a File? Ideally, I want to convert Java to XML from my Business Layer and send XML to my Presentation Layer objects. To do this, I need the XML returned to me in the form of a String and not a File. Any tips will be highly appreciated.

    You should be using Object Factory. JAXB provides one ObjectFactory for each schema.
    Create that particular object and after filling values into that object please set it to the Jaxb object where ever it fits.
    Like
    <Message>
    <Type></Type>
    <Name></name>
    <Message>
    If you want to set Name then JAXB will provide you with setter which be used to set or get. Util you are setting an object which is can repeat more that once then you will have to get a list from the JAXB object and add those objects into the list which will automatically add it the main object.

  • JAXB 1: is it possible to go from enum simulation in Java to XML Schema?

    I know how to get an enum simulation in java from XML schema, but can it be done in the other direction, in the context of a web service implementation?
    The thing is from schema to java a customization file is used. But there's no specification for such a customization file usability when going from java to schema. So far, i'm getting a string for enum wrapper.

    Well, i got it to work in JAXB 1, w/o xfire, schema-to-java. Marshall and unmarshall.
    But w/ xfire, it doesn't appear to be possible. Would probably require implementing it for them myself...

  • Can somebody explain to me how java and xml are related?

    Hi guys
    im new to java and xml.Been reading a lot regarding java and don't seem to have a problem with it...
    the problem is the xml part...im doing a simple GUI project using swing(online store) and i have to convert it to xml
    I have absolutely NO IDEA why i must convert my java to xml and have no idea how to do that.I been reading on the net that xml is a exten~ markup language and it is better and useful.
    Can somebody explain to me in layman terms
    1)how is java and xml related in?
    2)why do ppl want to convert java to xml when they can just stick to java
    3)what is actually xml...
    4)Do i need a program to create xml like i need jcreater to create java application
    5)How do we actually convert?is there any links that you guys could tell me?
    thank you
    tomleo

    im new to java and xml.Been reading a lot regarding
    java and don't seem to have a problem with it...Okay.
    the problem is the xml part...im doing a simple GUI
    project using swing(online store) and i have to
    o convert it to xmlYou have to? So presumably somebody in a position of authority told you that?
    I have absolutely NO IDEA why i must convert my java
    to xml and have no idea how to do that.I been reading
    on the net that xml is a exten~ markup language and
    it is better and useful.I have no idea either (besides which, it doesn't make sense). But why ask us? Somebody told you to do that, ask them why.
    Sure, XML is useful. But it isn't a programming language so it can't be used as a substitute for Java.
    Can somebody explain to me in layman terms
    1)how is java and xml related in?They aren't related, except perhaps in that they are both used in computers.
    2)why do ppl want to convert java to xml when they
    can just stick to javaThey don't.
    3)what is actually xml...Start here for numerous definitions:
    http://www.google.ca/search?hl=en&lr=&oi=defmore&q=define:XML
    4)Do i need a program to create xml like i need
    jcreater to create java applicationNo, XML is just text. But then Java code is just text too.
    5)How do we actually convert?is there any links that
    you guys could tell me?You don't convert Java to XML. My guess is that because you don't know much about Java or XML, you have misinterpreted something that somebody told you.

  • Java J2EE XML Developer Required - Luxembourg

    Java J2EE XML XSLT Developer - Investment Banking - Luxembourg
    French speaking candidates required to work on assignment to this leading investment Bank. You will need a good experience of Java J2EE technologies, XML and XSLT, and ideally Sybase ASA & PowerBuilder or SQL Server or Oracle. Knowledge of SQL, Stored Procedures, UNIX / Solaris of benefit. This will be a long-term contract for the right candidate. Candidates will need customer facing experience and able to propose effective technical solutions at all levels.
    Please make contact for further information.
    Best regards
    Benjamin Corke
    cerebra recruitment ltd
    +44 (0) 1483 300515
    ben AT cerebra.co.uk
    http://www.cerebra.co.uk/it
    http://jobs.cerebra.co.uk

    And the salary will be in duke dollars?
    When you signed up on this site, and supposedly read the terms of use, what gave you the idea that posting a job offer here was acceptable?

  • Looking for the java default XML parser?

    Hey guys,
    I just wondering alot about the sometimes mentioned Java Default XML Parser. So I used xerces and it worked fine, but my program doesnt need the whole functionality of xerces and I want to save some space for the resulting project jar. The xerces parser is 1.1 MB huge and instead of xerces I could use the default SAX parser in the java API, I thought.
    Although it is mentioned in some books/documents I can not find it.
    Could you give me an exmaple with the XMLReaderFactory how to use the default parser?
    I would appreciate this alot!
    Thanks.

    Hey,
    yes that I tried before, because I read this too.. If I am doing this Im getting the error:
    Exception in thread "main" org.xml.sax.SAXException: System property org.xml.sax.driver not specified
         at org.xml.sax.helpers.XMLReaderFactory.createXMLReader(XMLReaderFactory.java:90)
         at cfm.com.gui.GUIBuilder.buildGUIPage(GUIBuilder.java:51)
    ...So, this means that the JDK comes not with an default parser implementation I suggest.
    Hmm... stupid! I think I have to ship the xerces parser with my application... but its huge!
    Does anybody know what of the compelling parser are the lighweightest?
    Im gonna look for this answer too....
    Thanks.

  • Convert java to xml -urgent

    hi,
    I'm currently doing a project which requires me to generate a svg scatterplot graph. I already got data stored in vector.(in a servlet).But heard from my supervisor that i need to convert my data to xml format.With this xml format, i can generate a svg graph.I'm totally new to xml n don't know how to convert from java to xml..Though i read up on articles, i still can't get the idea of it. My data isnt very big. for graph i need to generate a x-axis :green , y-axis:red... n then retrieve the data n plot the scatterplot graph... can somebody help me??? very urgent... thanks

    One quick way is to construct the XML your self.
    e.g.
    StringBuffer xml = new StringBuffer("<?xml version="1.0" encoding="ISO-8859-1"?>");
    xml.append("<ROOT>");
    while(has more elements) {
    xml.append("<ELEMENT>").append(data).append("</ELEMENT>");
    xml.append("</ROOT>");
    Rene

  • Getting started with Java and XML

    Hi,
    Although I am pretty familiar with Java, I am a total newbie with using it to parse XML. I have been reading quite a few tutorials so am getting a good understanding of it and am thinking of using the DOM model for my purposes.
    What I haven't been able to find, however, is how I can actually get started with this. I have tried compiling a few examples and have been getting errors such as:
    xmltest.java package javax.xml.parsers does not exist
    xmltest.java package org.w3c.dom does not existetc etc...
    It looks like these packages don't come with J2SE. Can anyone confirm this? Do I need to download and install the Java Web Services Developer Pack to solve this problem?
    Finally, I know I will need an XML parser but have read that JDK 1.4 has it's own parser (Crimson). Is this adequate for parsing XML files or will I also need a parser such as Xerces?
    Thanks so much for any help!

    Hi DrClap,
    Thanks for the reply. I have JDK 1.4.1_02 installed on my server but the following error keeps coming up when I try to run my example:
    Exception in thread "main" java.lang.NoClassDefFoundError: org/w3c/dom/NodeAre there any further packages I need to download in order to run Java with XML? I have read some people install JAXP and XERCES... are these necessary for parsing an XML document or should J2SE 1.4.1 be sufficient?
    Thanks for your help!
    Jill

  • Export data to Java to XML

    How can I work with Java and XML/XSL together?. I want create a new file XML/XSL , with an editor created in Java. But, I don't Know how to write bold text,italic text.... and write this information in the file.
    Thanks,
    Ana

    If you work with JDK 1.4 you will have what you need to manipulate XML and perform XSL transformation.

  • Java and XML or XHTML Journey Planner Project

    Hello chaps,
    I need some help with a project I am doing.
    This project will be focusing on the area of information visualisation and the phenomena surrounding how data can be optimised in a confined space. Expanding on this, confined space can be a mobile phone screen, and personal organisers where information is shown in a limited area.
    I plan to use Java and XML. (or XHTML)
    I want to have a running application where raw data is transformed into a combination of graphics and information. To achieve this, I will be looking at route planning for mobile phones and how route instructions can be represented in a visual but a sophisticated way.
    My focus will be on the London transport.
    Here is a link to the London transport journey planner
    http://www.tfl.gov.uk/journeyplanner
    Using WAP, I surfed the website on my phone and there seems to be a lot of writing and there is a lot to process before understanding what is going on. I want to transform words into pictures e.g., the word underground or bus into a logo of a red bus or underground logo or Instead of ?walk?, a picture of a walking pedestrian. Picture are good connotations as we can easily recognise rather than processing words. I would also like to represent the time taken in a graph format, again, to easily visualise.
    The application can be on a phone or on Windows simulating a mobile phone.
    Can anyone help me with this mammoth task or at least point me out in the correct direction?
    Looking forward to your reply.

    1st, ) Raw Data e.g, journey time, journey distance
    2nd, ) I would want the system to recognise the 'raw data' mentioned before and transform this into graphical image(s).
    3rd ) a complete visualisation would look like,
    modes of transport represented by pics or logos, showing the time to get to from A to B.
    Showing various routes, eg, walking, and/or bus and/or tube

  • Java and xml option necessary?

    Hi,
    first when i build the repository database, i choose java and xml option, is this necessary or i waste my time.
    When i read Building a Help Desk Connector, i'm not sure, do i need the Diagnostic Pack.
    Best regards
    Thomas
    (Narri, Narro)

    This is the defacto site for xpath stuff for java
    http://xml.apache.org/xalan-j/

  • Java and XML Doc

    I am new to Java and XML, I want to know the steps i should follow to work with XML document using XPATH. also the APIs and Technologies i shoud work. If possible guide me any examples or tutorials for that.

    This is the defacto site for xpath stuff for java
    http://xml.apache.org/xalan-j/

  • Converting from PDF directly to Java Objects/XML (and PDF format questions)

    Hi,
    I posted this originally in the Acrobat Windows forums but was told I might have more luck here, so here goes:
    I am desperately trying to find a tool (preferably open source but commercial is fine also) that will sit on top of a PDF and allow me to query it's text for content and formatting (I don't care about images). I have found some tools that get me part of the way there, but nothing that seems to provide an end-to-end solution but is quite lightweight. My main question is WHY are there so many tools that go from PDF to RTF, and many tools that go from RTF to XML, but NONE that I can find that go PDF to XML.
    To clarify, by formatting I simply mean whether a line/block of text is bold/italic, and its font size. I am not concerned with exact position on the page. The background is that I will be searching PDFs and assigning importance to whether text is a heading/bodytext etc. We already have a search tool in place so implementing a pure PDF search engine is not an option. I need a lightweight tool that simply allows me to either make calls directly to the PDF OR converts to XML which I can parse.
    Some tools I have tried:
    1) PDFBox (Java Library) - Allows the extraction of text content easily, but doesn't seem to have good support for formatting.
    2) JPedal (Java Library) - Allows extraction of text content easily, and supports formatting IF XML structured data is in the PDF (not the case for my data).
    3)  Nitro PDF (Tool) + RTF to XML (script) - This works quite nicely and shows that PDF to XML is possible, but why do I have to use 2 tools? Also, these are not libraries I can integrate into my app.
    4) iText (Java Library) - Seems great at creating PDFs but poor at extracting content.
    I don't really expect someone to give me a perfect solution (although that would be nice!).
    Instead, what I'd like to know is WHY tools support PDF to RTF/Word/whatever retaining formatting, and other tools support RTF to XML with the formatting information retained. What is it about PDF and RTF/Word that makes it feasible to convert that way, but not to XML. Also, as I found in 3) above, it is perfectly feasible to end up as XML from PDF, so why do no tools support this reliably!
    Many thanks for any advice from PDF gurus.

    XML doesn't mean anything - it's just a generic concept for structuring
    information.  You need a specific GRAMMAR of XML to mean anything.  So what
    grammar would you use?  Something standard?  Make up your own?
    However, there are a number of commercial and open source products that can
    convert PDF to various XML grammars - SVG, ABW, and various custom grammars.
    But the other thing you need to understand is that most PDF files do not
    have any structure associated with them (as you saw when using JPEDAL).  As
    such, any concepts of paragraphs/sections/tables/etc. Are WILD GUESSES by
    the software in question.

Maybe you are looking for

  • Unable to share library on Vista x64

    I am running a new installation of Vista Enterprise SP1 x64 w/ iTunes 7.6.2.9. After enabling sharing, I cannot see any other libraries on the same subnet. Other's who see my library get an error when connecting: "The shared library 'my library' is n

  • DJ Software for Mac?

    Here's what I'd really like to be able to do: Have more detailed control over a playlist, so that I could decide which songs were going to crossfade, and which songs were going to "bump" into each other -- ie, one ends and the other immediately start

  • I can sign on the the web but I can not get the email to connect?

    I can sign on the to the internet yet I can not sign is and get my mail... when i press the mail app on the dock get no responce

  • Need an email address for registration

    I just bought my Toshiba a few hours ago. I filled in all my details and laptop's s/n etc and they were validated. However, at the very end of the process I was asked to send via email (or fax) the invoice/receipt of my laptop to an email address in

  • What is "failed to scene-update in time" crash

    [ Wow. No "community" for mail app (or other built-in apps), crashes, iOS 8 (or just iOS). ] iPad 2 running IOS 8 for a week or so. Sluggish and battery draining faster than before, but all apps were working ok. Then during an attempt to delete an e-