Xml in servlet
Hi
I have used DOM to read XML node values and DOM's Transformer class to save changed xml node values back to the xml file.
File f = new File("C:\\test.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(f);I have changed the value of a node using setData method of Text.
Then saved the XML file again:
Source source = new DOMSource(doc);
Result res = new StreamResult(f);
Transformer x = TransformerFactory.newInstance().newTransformer();
x.transform(source,res);It works fine.
But when I have a web based application, I put this code in a servlet and the xml file in WEB INF, it reads it and changes the node value but does not save the file when I use Transformer.
Does it not work for web based applications. Is there any other way out.
If the OP can read and modify but cant save, sounds more like a security problem
Similar Messages
-
Processing web.xml -Adding servlet
Can you please give me an out line how to add servlets/filters/session-configs to web.xml programatically.
I have writen a program for adding these but In web.xml the order in which elements are placed matters. So right now in the program I specify that I should add this element before another specified element like that .
How can we make this generic ? I mean how I can maintain the same order as of DTD ?
please help me.Answering your original question. Yes it is possible to have a web.xml without servlet classes, if you are not using servlet classes.
>
But I got the following error from Tomcat.
2007-01-12 18:31:25 ContextConfig[worktigers] Parse
error in application web.xml
org.xml.sax.SAXParseException: The processing
instruction target matching "[xX][mM][lL]" is not
allowed.
at
t
org.apache.xerces.parsers.AbstractSAXParser.parse(Unkn
own Source)
TA
MalaiIt looks like there may be BOM characters (invisible in regular editors), before the opening angle bracket of the XML prolog: <?xml version="1.0"
The special characters usually are inserted by some editors such as Notepad.
You can download a free Hex editor, like Cygnus hex editor and see if you have the 3 special characters (in Hex) appearing before the XML prolog.
If you see anything before the prolog delete them, save the web.xml file and re-test it.
Reading from previous answers to your problem from here:
http://forum.java.sun.com/thread.jspa?threadID=694303&messageID=4033694
http://mail-archives.apache.org/mod_mbox/xerces-j-users/200201.mbox/%3Cp04330102b8689660dcbc@%5B192.168.254.4%5D%3E -
How to retrieve information from XML using servlets
Hi
I have a scenario like this
File-->XI-->J2ee application(HTTP Receiver adapter)
I want to know how XI sends xml file as a query string file name?
What ever may be the case i just need to retrieve the information from Request object and display the same in browser(JSP).How to do that, I am totally confused, please anyone help me!
Code help is highly rewarded.
ThanxHi Rajesh!
I have tried your code. But some where i went wrong. Please correct me: I am using NWDS2.0.9
my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>WEB APP</display-name>
<description>WEB APP description</description>
<servlet>
<servlet-name>DisplayRes</servlet-name>
<servlet-class>com.quinnox.DisplayRes</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DisplayRes</servlet-name>
<url-pattern>/DisplayRes/*</url-pattern>
</servlet-mapping>
</web-app>
my application.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE application PUBLIC "-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN"
"http://java.sun.com/dtd/application_1_3.dtd">
<application>
<display-name>ReceiverEntpr</display-name>
<description>EAR description</description>
<module>
<web>
<web-uri>HttpReceiver.war</web-uri>
<context-root>/HttpReceiver</context-root>
</web>
</module>
</application>
and my servlet code:
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.EntityResolver;
import org.xml.sax.SAXException;
import com.sun.java_cup.internal.parser;
import com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl;
public class DisplayRes extends HttpServlet {
public void doGet(HttpServletRequest requset, HttpServletResponse response) throws ServletException, IOException
doWork(requset, response);
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
doWork(req, resp);
private void doWork(HttpServletRequest req, HttpServletResponse resp) throws IOException
String path = null;
PrintWriter out = null;
PrintWriter p2=resp.getWriter();
try
resp.setContentType("text/xml");
out = resp.getWriter();
out.println("hi");
path = req.getPathInfo();
if(req.getContentLength() != -1){
outputURI(req.getInputStream(), out);
} catch (IOException ioe) { return;
//private void outputURI(InputStream resultStream, Writer out) {
private void outputURI(InputStream resultStream, PrintWriter out) {
if (resultStream == null) {
// no default file
// logger.error("No File to return");
return;
try {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Class clazz = loader.loadClass("org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
// DocumentBuilderFactoryImpl factory = (DocumentBuilderFactoryImpl) clazz.newInstance();
// DocumentBuilder parser = factory.newDocumentBuilder();
parser.setEntityResolver(new ClassPathEntityResolver());
printXML(parser.parse(resultStream), out);
resultStream.close();
} catch (Exception e) {
// logger.error("Trying to parse the output " , e);
//private void printXML(Document document, Writer writer) throws Exception {
private void printXML(Document document, PrintWriter writer) throws Exception {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Source source = new DOMSource(document);
Result output = new StreamResult(System.out);
transformer.transform(source, output);
// Write as XML so that entity references can be resolved.
if (writer != null) {
transformer.transform(source, new StreamResult(writer));
Please tell me how to display in servlet.
If it is better to display in a browser. Please send me the code.
Thanks -
Please help, Urgent ! creation of xml from servlet
Hi,
I have to write a servlet that takes user input from a html form and creates a xml file from those input parameters and transform that xml file into html form using xsl program. Whenever the user adds new values to the form this newly generated xml file should overwrite the previous xml file content.
Can anybody please tell me how to create a xml file from user input in servlet so that I can pass it to a transformer object.
Thanks in advance!why write out the XML, it seems to be only a temporary file?
Doing as you suggest is extremely risky for when several requests come in at the same time you can never be sure that the file contains the data that you just wrote to it.
Better to keep the XML all in memory.
For the XML creation, look no further than DOM. Most XML parsers provide excellent DOM support, I'll be using Xerces 2 here as that's what I'm most familiar with.
Document doc = new DocumentImpl();
Element root = doc.createElement("mydoc");
* fill in the XML
Element elem = doc.createElement("focuscontrol");
elem.appendChild(doc.createTextNode("alert('loaded')"));
root.appendChild(elem);
elem = doc.createElement("data");
elem.appendChild(doc.createTextNode("Hello World!"));
root.appendChild(elem);
doc.appendChild(root); creates an XML Document object like this:
<?xml version="1.0"?>
<mydoc>
<focuscontrol>alert('loaded')</focuscontrol>
<data>Hello World!</data>
</mydoc>This XML Document object can be easily passed to an XSLT processor to turn it into HTML.
String path = getServletContext().getRealPath("/WEB-INF/xsl/");
TransformerFactory tFactory = TransformerFactory.newInstance();
Source xslSource = new StreamSource(new File(path, "myxslfile.xsl"));
Source xmlSource = new DOMSource(doc);
t.transform(xmlSource, new StreamResult(out));where out is the PrintWriter for the servlet and your XSL file is stored in yourwebapp/WEB-INF/xsl (thus out of sight of prying eyes).
I leave it up to you to find an encoding of your request parameters into the generated XML that you like. -
Toplink xml binding session.xml and servlet
I made a project with toplink-jaxb mapping
with simple pojo object it works fine.
I made another project with servlet
and the same session.xml and java classes
but when my process start it throw an exception :
jaxbexception : Provider oracle.toplink.ox.jaxb.JAXBContextFactory could not be instantiated:
It is like the process could not read the session.xml files, but this file and two xml file for the mapping are in the classpath (in WEB-INF/classes).
Have i to put these files in another place ?
Thanks.Hi,
thank you for your response but
here is the code :
javax.xml.bind.JAXBContext jaxbContext = javax.xml.bind.JAXBContext.newInstance(
"fr.cnav.cramse.pgpe.contactsnationaux"),this.getClass().getClassLoader());
but i still got the same exception :
05/03/01 08:24:33 exceptionProvider oracle.toplink.ox.jaxb.JAXBContextFactory could not be instantiated: java.lang.NoSuchMethodError: oracle.toplink.publicinterface.Session oracle.toplink.tools.sessionmanagement.SessionManager.getSession(oracle.toplink.tools.sessionconfiguration.XMLSessionConfigLoader, java.lang.String, java.lang.ClassLoader, boolean, boolean)
I have also a stange message in the log window in jdev :
Cutting log (size: 101767, max: 100000)Component returned failure code: 0x80470002 (NS_BASE_STREAM_CLOSED) [nsIFileOutputStream.write]Component returned failure code: 0x80470002 (NS_BASE_STREAM_CLOSED) [nsIFileOutputStream.write]Component returned failure code: 0x80470002 (NS_BASE_STREAM_CLOSED) [nsIFileOutputStream.write]Cutting log (size: 101866, max: 100000)Error cleaning up log: Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsISeekableStream.seek]
Thank you for your help. -
Hi all,
I am very new to Java/XML. I need to get text data delimted by eg tabs, from a textbox in a java servlet into an XML format and was wondering if anyone had or knew of any sites that had code that already does this. Also, if no code is available I would be very grateful if someone could direct me the
best starting point for doing this.
thanks a lotwww.jdance.com
www.ibm.com and go to the developer section.
java.sun.com/xml
javaworld.com
oreilly.com
good luck with servlets and xml. xml ignores whitespaces and u will have to code a bit to get the tabs -
Oracle XML classgenerator /Servlet problem
Hi,
I'm developing a servlet that accepts an HTTP request, contacts a database, processes the request and return an XML document back to the browser. The XML document returned is dependent on which selection a user makes.
The problem is that on first request, say user selects "choice one", the correct XML document is returned. However, when the browser's back button is used to go back and make the same choice as previous(ie "choice one"), Explorer 4.5 displays an empty page while netscape 4.5 return a document contains no data error.
I used oracle xmlclassgenerator to generate the classes that create the XML document to be returned. The problem certainly lies in the method of my servlet that uses these classes to generate the XML document because when I replace the whole method with println statement every thing works fine(but of course without the XML document).
The content of the method is as follows.
ACCOUNT acc = new ACCOUNT(id);
//Create a child and add child to root node
NUM_OF_RESIDENTS nr = new NUM_OF_RESIDENTS(num);
acc.addNode(nr);
//Create another child and add to root node
FIXED_COST fc = new FIXED_COST();
ELECTRICITY el = new ELECTRICITY(elec);
GAS g = new GAS(gas);
WASH_MACHINE wm = new WASH_MACHINE(wash);
WATER wat = new WATER(water);
OTHER oth = new OTHER(other);
fc.addNode(el);
fc.addNode(g);
fc.addNode(wm);
fc.addNode(wat);
fc.addNode(oth);
//finally add to root node
acc.addNode(fc);
//Create another child
TELEPHONE tl = new TELEPHONE();
SUBSCRIPTION sub = new SUBSCRIPTION(tel);
COST_PER_TICK cpt = new COST_PER_TICK(tick);
tl.addNode(sub);
tl.addNode(cpt);
acc.addNode(tl);
//Create another child
// PREVIOUS_ACCOUNT pacc = new PREVIOUS_ACCOUNT();
for(int i=0; i<previous_details.size(); i++){
//Create another child
PREVIOUS_ACCOUNT pacc = new PREVIOUS_ACCOUNT();
PreviousDetails pd = (PreviousDetails)previous_details.elementAt(i);
String name = pd.getName();
String credit = pd.getCredit();
String debit = pd.getDebit();
NAME n = new NAME(name);
LAST_CREDIT lc = new LAST_CREDIT(credit);
LAST_DEBIT ld = new LAST_DEBIT(debit);
pacc.addNode(n);
pacc.addNode(lc);
pacc.addNode(ld);
acc.addNode(pacc);
for(int i=0; i<acc_dates.size(); i++){
String str = (String)acc_dates.elementAt(i);
ACCOUNT_DATE ad = new ACCOUNT_DATE(str);
acc.addNode(ad);
acc.validateContent();
ByteArrayOutputStream out1 = new ByteArrayOutputStream(1024);
acc.print(out1);
res.setContentType("text/plain");
ServletOutputStream os = res.getOutputStream();
PrintWriter out = new PrintWriter(os);
out.println(out1.toString());
out.close();
catch(Exception e){}
Am I doing somthing wrong here?
Thanks.
nullHi,
I had a very similar problem, which turned out to be the way that I was referencing one schema from another. Originally I had something like the following in my main XSD:
<xs:import namespace="http://www.govtalk.gov.uk/people/bs7666" schemaLocation="bs7666-v2-0.xsd"/>When I tried to register the schema using the schemaURL of 'http://www.govtalk.gov.uk/people/bs7666/bs7666-v2-0.xsd' I got ORA-31000: Resource 'bs7666-v2-0.xsd' is not an XDB schema document. I then tried to registering the schema using just it's name ie schemaURL => 'bs7666-v2-0.xsd' and this worked!
With further investigation I found that if I change the schemaLocation in the import to a full URL I could then register the schema using that same URL:
Reference from my main schema
<xs:import namespace="http://www.govtalk.gov.uk/people/bs7666"
schemaLocation="http://www.govtalk.gov.uk/people/bs7666/bs7666-v2-0.xsd"/>
BEGIN
DBMS_XMLSCHEMA.registerSchema
( SCHEMAURL => 'http://www.govtalk.gov.uk/people/bs7666/bs7666-v2-0.xsd'
, SCHEMADOC => bfilename('XMLDIR','bs7666-v2-0.xsd')
, LOCAL => FALSE
END;Maybe someone could shed some light on the best practice for registering schemas? I understand that schemaURL is really just a reference for the schema and not actually used to locate the schema but is it better to use full URLs?
Regards,
Tom -
Can you tell me How to loading sessions.xml in servlet
Can you tell me How to loading sessions.xml in servlet
Getting a session in a servlet is no different than in any other environment except that you need to be careful which classloader you pass to the SessionManager and correctly configure what to do if your application is reloaded. If you use the oracle.toplink.util.SessionFactory introduced in 10.1.3.1 you don't have to worry about these details--it uses the correct settings. The SessionFactory greatly simplifies the code required to get a session or unit of work. It's well documented in the SessionFactory javadoc.
If you do use SessionFactory beware there is a bug when running in a JTA environment and there's no transaction started. Doug posted a work around in his blog[1].
--Shaun
[1] http://www.jroller.com/page/djclarke/20060412 -
How to access attribute name (xml) in Servlet ?
Hi All,
Anybody please tell me how to access attribute name in servlet ?
ThanksParser.java
public class Parser
public static String getAtt()
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder parser = factory.newDocumentBuilder();
Document doc = parser.parse("customer.xml");
Element root = doc.getDocumentElement();
return root.getAttribute("name");
public static void main(String [] argc)
Parser p = new Parser();
p.getAtt();
Servlet.java
Parser p1 = new Parser();
String att1 = p1.getAtt();
Hope this will help u.
....yogesh -
Post XML to Servlet through JavaScript and reveive info back
There's a post in this forum before, but anyone know how to do this:
=========================================
MSIE5 + will let you post an XML string to a servlet. It must be done from javascript. The same javascript can also receive an xml string back from the servlet, parse it, and update dom objects in the browser, independenty of a an http post.
You can use this technique to populate ddlb based on events in the browser, or do real-time validations from the database. It works just fine, is quite fast, but is MSIE specific. If another brower is used, you must handle it some other way.
=========================================
I will use IE only.
Any help will be highly appreciated!
CharlesThanks for your response, ddossot!
I also got something from our Microsoft team, post here to share with others who have interest in this topic. It's interesting to see IE talk with Servlet in XML, especially within a LAN.
==============================================================================
I did find a couple of things. Not sure if it is exactly what you are looking for. Let me know if it works.
function submitAsXML() {
var theXML = document.myform.txtInXML.value;
var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
var url = document.myform.txtURL.value;
try {
xmlhttp.open("POST", url, false);
} catch(e) {
xmlhttp.open("POST", url, false);
xmlhttp.Send(theXML);
var xmlResp = xmlhttp.ResponseText;
document.myform.txtOutXML.value = xmlResp;
Link to XML DOM Properties -
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk30/htm/xmproresponsexmlserverxmlhttp.asp
Regards,
Ashwin -
Hi i am executing a web application on tomcat 4.1.29 and have the following structure...the jsp pages are executed but when sendinga request to a servlet the servlets are not executed...Can somebody guide me out of this....
webapps
{MyApp}->[web-inf][jsp]
{web-inf}->[classes][lib]
{classes}->[com][src]
{src}->[source files]
when the source files are compiled package structure is followed and the class files are grneated in
com.MyApp.servlets
...etc
the servlets are registered in the web.xml file as shown below.....few lines of my web.xml file
<servlet>
<servlet-name>userServlet</servlet-name>
<servlet-class>com.MyApp.servlets.UserServlet</servlet-class>
</servlet>
even then when accessing a servlet it says the resource not found
The requested resource (/MyApp/servlet/UserServlet) is not available.
am i missing something some where...why are the servlets not executed????<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.MyApp.servlets.UserServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/User</url-pattern>
</servlet-mapping>I'd invoke it with this URL:
http://localhost:8080/MyApp/UserServlet
hmm something seems to be wrong here ;-)
URL should be
http://localhost:8080/MyApp/User (see <url-pattern>) -
Web.Xml Mapping For using Filters in Servlets
Hi Team
Can any one help me in getting the correct xml mappiing for using filters
Currently i am getting 404 error when calling any resource
using the below mapping
<web-app>
<display-name>OM</display-name>
<welcome-file-list>
<welcome-file>Hello.html</welcome-file>
</welcome-file-list>
<filter>
<filter-name>Basic Filter</filter-name>
<filter-class>BasicFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Basic Filter</filter-name>
<url-pattern>/sample1</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>sample2</servlet-name>
<servlet-class>com.ustri.xml.FilteredServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sample2</servlet-name>
<url-pattern>/sample1</url-pattern>
</servlet-mapping>
</web-app>
Thanks
santhoshAs the messages tries to suggest, the elements under <web-app> must appear in a specific order. In particular the <filter> elements, if any, must appear before any <session-config> elements. That isn't the case in what you posted so it fails validation by the DTD.
-
Eclipse, WTP, Servlets and Web.xml
I wonder if you could help me.
I am using Eclipse and Web Tools Platform.
In eclipse, when I create a Servlet, I believe the servlet details (such as name, class, url-pattern) should be included into web.xml file automatically. However, this is not happening.
Would you know how I can configure Eclipse and WTP to automatically write Servlets details into web.xml files.
ThanlsThanks for the reply
I have Eclipse 3.2 and WTP 1.5
Yes, I am creating my Servlet in a project under the Dynamic Web Projects.
I deploy my WAR file using the 'Export' menu.
Now, I have manually added the servlet details into the web.xml file:
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>com.mycom.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
I am accessing the servlet as:
http://localhost:9090/MyFirstServlet/HelloWorld
But I still get HTTP 404 error when accessign HelloWorld servlet. I am not sure what I am missing.
Thanks -
XML SERVLET Communicaiton.. ?
Hi All,
Anybody please tell me how to communicate xml and servlet each other.
I have to make a program in which servlet will call xml attribute and print the xml attribute .
Please help.
Please reply with coding ...
Thanks
Harish PathakDouble Post: http://forum.java.sun.com/thread.jspa?threadID=707034
Your question is extremely unclear, please clarify what you want to achieve. Read How To Ask Questions The Smart Way if you don't know how to do that. -
Servlet is not working in NWDS
Hi Experts,
i have created j2ee(web module project) in nwds.
in that i have html page with 2 input fields,on submit it should call servlet (java servlet file).
Note: i have done servlet mapping in web.xml file
<servlet-mapping>
<servlet-name>AddServlet</servlet-name>
<url-pattern>/AddServlet</url-pattern>
</servlet-mapping>
i have tried with both servlet name and url pattern(when calling from submit action)
Submit action code:
<form action="/Addservlet" method=POST>
and i am getting error after submitting
404 Not Found
SAP J2EE Engine/7.00
The requested resource does not exist.
Details: Go to main page of this application!
can anybody tell me how to find out the url of the servlet?
and any document which gives the step by step procedure to dev the jsp/servlet project in nwds
Regards,
Vani R GHi,
The solution is in the "Defining a URL pattern" section of this link:
[http://help.sap.com/saphelp_nw04/helpdata/en/13/e7bf3eb8b73614e10000000a114084/frameset.htm]
It seems that URL Pattern should be <url-pattern> / </url-pattern>
and
servlet name is <servlet-name> QuickReservationServlet </servlet-name>
Hope that this will help you in your project.
Thanks.
p256960
Maybe you are looking for
-
Woke up this morning to my gmail app on my Iphone 5 IOS7 telling me my account was changed. It had a different user and my information gone. Since I was still asleep for the most part I didn't write down the user name. I deleted the app and change
-
Ipod 5th gen went into recovery mode after I tried to update
I went to update my ipod touch 5th generation to ios 7.1.2 and i went upstairs and left it alone for a few hours, it said the update was verifying when i left it. when i came back it had the screen that told me to connect to itunes so i connected it
-
How to retrive data from table MSPR of field PSPNR as a character.
Dear All, I need to display MSPR-PSPNR field in some report. The above said field is showing character in output wen we execute table MSPR, but it is a numeric field inside of length 8. for internal table it is picking numeric value, but I want to di
-
18 fps breaks transition previewing, precision editor, and keywords
Greetings, I'm working on a Super 8 movie project. My films were scanned at 18 fps. When I imported them into iMovie '11 I had no choice but to convert them to another speed -- 24 fps in this case. OK. Most things work fine, but there are a few excep
-
Airport Express stopped showing up on the wireless network
Airport Express stopped showing up on the wireless network, and now I can't stream music from my iMac or iPhone through the AE as I used to. I now have a new adsl modem, but it doesn't help. The AE has a wireless connection to the modem. I've used Ai