String manipulation question (servlet)

Hello,
I have a problem replacing parts of a String with values from a HttpServletRequest.
I have the following method:
public String replaceVariables(String s, HttpServletRequest request) {
     Enumeration e = request.getParameterNames();
     Vector v = new Vector();
     while(e.hasMoreElements()) {
          v.add(e.nextElement());
     String paramName;
     ListIterator li = v.listIterator();
     while(li.hasNext()) {
          paramName = (String) li.next();
          if (s.indexOf("#" + paramName + "#") > -1) {
               s = new String(new StringBuffer(s).replace(s.indexOf("#" + paramName + "#"), s.indexOf("#" + paramName + "#") + (("#" + paramName + "#").length()), request.getParameter(paramName).toString()));
     return s;
}What I am trying to do here is read in a line of text (String s) along with a the htpp servlet request. Put the names of the request paramaters into Vector v.
Next I try to check the String s for any part of the String that matches one of the parameter names surrounded by #'s. If there is a match then I replace the #string# with the value associated with it in the http servlet request.
The trouble is, my code on ly replaces the very first variable then stops, I cannot see why it does not do the rest.
I hope this makes sense to somebody, becuase it doesn't to me :-)
Thanks for any advise or help

Yep. I have just done a basic one for testing. The String I read in is:
username = #username#, action = #action#, email = #email#
And the html form information that is sent to the servlet is:
<input type="hidden" name="action" value="test">
<input type="hidden" name="username" value="testuser">
<input type="hidden" name="email" value="testemail">
....etc.
I don't know if it makes a difference, I don;t think it does, but I am reading in a whole file, and passing the file line by line to this method.
The method that passes each line is:
public Vector generateHTML(HttpServletRequest request) {
     Vector v = new Vector();
     try {
          File f = new File("/fakepath/" + request.getParameter("action") + ".template");
          FileReader fr = new FileReader(f);
          BufferedReader br = new BufferedReader(fr);
          String s;
          while((s = br.readLine()) != null) {
               s = replaceVariables(s, request);
               v.add(s);
     } catch (Exception e) {
          // ignore
     } finally {
          return v;
}

Similar Messages

  • String manipulation in JSTL

    Hello All
    I'm a just a beginner and I'm need to write a web page that is totally based on JSTL. I found out that the standard java tab lib in JSTL doesnt really support string manipulation or regular expression like in perl.
    As such, I would like to know what are the different options (like adding servlets/javabeans/etc) can i add to my JSTL page so that i can perform complex string manipulation to a data entered by the user in the text box?
    Some of the operations that I wish to carry out on the data are:
    1. check if data contains certain characters, strings
    2. joining and spliting strings
    3. find length of the string
    4. find the position of certain character in a string
    5. check if string match certain pattern.
    and many more.
    Would greatly appreciate if you guys can help to provide some light.
    Regards
    Beginner....

    You might find MicroNova YUZU JSP tag library (http://sourceforge.net/projects/micronova-yuzu) useful, especially if you need to support both JSP 1.2 and 2.0. Hope this helps.

  • String Manipulation in BI Publisher Report Paramater

    Hi,
    My Problem is that I am not able to do string manipulation on BI Publisher report Prameters.
    Actually I want to Show Deptno-Dname in Menu(LOV).and when I select Certain combination like '10-Accounting',and while passing the parameter:Dept I wanted to Cut the department no(10) using string manipulation functions provided by oracle in Data Model(Query) in where clause like (where deptno=to_number(substr(:Dept,1,2)).
    This query is working fine in other application like TOAD,But not giving results in BI Publisher Report.
    It's also not giving any error while saving or running the report.
    Please suggest any solution.

    even I tried the following query in data model..
    select DISTINCT EMP.EMPNO as EMPNO,
    EMP.ENAME as ENAME,
    EMP.JOB as JOB,
    DEPT.LOC as LOC
    from SCOTT.DEPT DEPT,
    SCOTT.EMP EMP
    where emp.DEPTNO=DEPT.deptno
    and DEPT.deptno=nvl(to_number(substr(:department,1,2)),DEPT.deptno)
    But the Parameter which I want to pass say Department('10-Accounting'),
    Still it is showing employees from all departments.

  • How do I Display a string from a servlet into a JSP Page???? NEED HELP!!!!

    Hi guys,
    How do I Display a string from a servlet into a JSP Page...
    Ive tried so many bloody things!.....
    Simply.
    I get text from JSP. The servlet does what ever it does to the string.
    Now. Ive create sessions and bean things,.... how the hell do I display it in a text box... I can display on the screen.. but not in the text box.!!!
    please help!!!

    hmmm, I dont really like using JSP programming, u should be using JAVA..
    the way to do it is:
    Call and cast to the bean like this:
    <%@ page import="beans.*" %>
    <% //cast to bean get request create object
    userNameBean u= (userNameBean) request.getSession().getAttribute("userNameBean");
    then... all you do is call it like this:
    <input type="text" name="firstName" value="<%= u != null? u.getFirstName(): "" %>">
    this is the real programmers way,,,
    chet.~

  • How to pass a string from a servlet to client side

    hi,
    i would like to generate a string from a servlet and pass it to the client side. the client will receive the string by using request.getParameter(). How should i implement this system? Could anybody give me some hint?
    Best Regards,
    Henry

    Greetings,
    hi,
    i would like to generate a string from a servlet and
    pass it to the client side. the client will receive
    the string by using request.getParameter(). HowAre you referring to the instance of (Http)ServletRequest the 'request' object being passed to the "client"? What is the "client" in this case? If you mean a "traditional" client communicating over (or by tunneling through...) HTTP then no can do. The (Http)ServletRequest object is generated by the web container (a.k.a. "servlet engine"), not by the client, and it is not serializable so there is no way to pass it back to the client...
    should i implement this system? Could anybody give me
    some hint?It depends again on "what is the 'client' in this case?"
    Best Regards,
    HenryRegards,
    Tony "Vee Schade" Cook

  • How to send a String value  from Servlet to  Action class in Struts .

    when iam trying to send string value from Servlet to Struts Action class through Http Session, iam getting null value, iam really in big confusion, help me.

    please elaborate clearly or put you code of both action and servlet here
    Are both of them in same web application

  • Question about string manipulation

    Hello, I am practicing with Java and trying to learn it, and have a quick question. I am trying to get the count on a string of numbers for after a decimal point. the numbers are generated as the result of a math, so I can't use index, since the location of the decimal changes based on the number imputed. I want to figure this out on my own, but have hit a wall here, i've spent the past few hours trying every string command I can think of, and haven't figured it out yet, anyone mind pointing me in the right direction for which string to use? Thanks in advance for any help you can provide!

    Is this what you want?
    public class Fallen{
      public static void main(String[] args){
        String number = "123.45678";
        String frac = number.substring(number.indexOf('.') + 1);
        System.out.println(frac + " length=" + frac.length());
        frac = number.replaceFirst("^.+\\.", "");
        System.out.println(frac + " length=" + frac.length());
    }

  • How to send byte array and String values to servlet from Swing application

    Hi all,
    I am new to swing, servlet, and socket connection.
    I have swing application to draw images and some input data. I dont know to send to server.
    byte[] buf = baos.toByteArray();
    URL servletURL = new URL("http://10.70.70.1:8080/servlet/SaveImage)
    URLConnection conn = servletURL.openConnection();
    conn.setDoOutput(true);
    BufferedWriter out = new BufferedWriter( new OutputStreamWriter( conn.getOutputStream() ) );
    out.write(buf&a=aaaa&b=bbbbb);
    out.flush();
    out.close();
    can I do like this. Strings are received in server side perfect. but i cant get byte array data. Please help me.
    Thanks in advance.

    <img src="myservlet">
    In your myservlet:
    response.setContentType("image/jpeg");
    then write your image date via ImageIO that uses response output stream.

  • Very simple XSLT string replacing question

    Hi,
    This is a really simple question for you guys, but it took me long, and i still couldn't solve it.
    I just want to remove all spaces from a node inside an XML file.
    XML:
    <?xml version="1.0" encoding="UTF-8"?>
    <root insertedtime="2008-05-01T14:03:00.000+10:00" pkid="23421">
       <books>
          <book type='fiction'>
             <author>John Smith</author>
             <title>Book title</title>
             <year>2 0  0 8</year>
          </book>
       </books>
    </root>in the 'year' node, the value should not contain any spaces, that's the reason why i need to remove spaces using XSLT. Apart from removing space, i also need to make sure that the 'year' node has a non-empty value. Here's the XSLT:
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <xsl:strip-space elements="*"/>
        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:template>
        <xsl:template match="//books/book[@type='fiction']">
            <xsl:copy>
                <xsl:apply-templates select="@*"/>
                <xsl:attribute name="id">101</xsl:attribute>
                <xsl:call-template name="emptyCheck">
                    <xsl:with-param name="val" select="year"/>
                    <xsl:with-param name="type" select="@type"/>
                    <xsl:with-param name="copy" select="'true'"/>
                </xsl:call-template>
                <xsl:value-of select="translate(year, ' ', '')"/>
            </xsl:copy>
        </xsl:template>
        <!-- emptyCheck checks if a string is an empty string -->
        <xsl:template name="emptyCheck">
            <xsl:param name="val"/>
            <xsl:param name="type"/>
            <xsl:param name="copy"/>
            <xsl:if test="boolean($copy)">
                <xsl:apply-templates select="node()"/>
            </xsl:if>
            <xsl:if test="string-length($val) = 0 ">
                <exception description="Type {$type} value cannot be empty"/>
            </xsl:if>
        </xsl:template>
    </xsl:stylesheet>The 'emptyCheck' function works fine, but the space replacing is not working, this is the result after the transform:
    <?xml version="1.0" encoding="utf-8"?>
    <root insertedtime="2008-05-01T14:03:00.000+10:00" pkid="23421">
       <books>
          <book type="fiction" id="101">
             <author>John Smith</author>
             <title>Book title</title>
             <year>2 0 0 8</year>2008</book>
       </books>
    </root>The spaced year value is still there, the no-space year is added outside the 'year' tags'
    anyone can help me, your help is extremely appreciated!
    Thanks!

    You should add a template for 'year' :<xsl:template match="year">
    <year><xsl:value-of select="translate(.,' ','')"/></year>
    </xsl:template>and remove the translate call in the 'book' template.
    It would be better to add a 'priority' attribute at each template so it would be explicit which template to use because match="@*|node()" could be interpreted by another transform engine as the unique template to be used !

  • How to send a String to a Servlet using a HTTP POST

    Well, I have designed a servlet that receives a HTTP POST, I was testing it using an HTML form to send (using POST) information, now, I have coded a Java App to send it a string, I don't know how to make the servlet recognize that info so it can make its work, I am posting both codes (Servlet & API) so anyone can guide me and tell me how and where to modify them
    Servlet:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.sql.*;
    public class xmlwriter extends HttpServlet
    public void service(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    ServletOutputStream salida = res.getOutputStream();
    res.setContentType("text/HTML");
    String cadena = req.getParameter("cadena");
    File f1 = new File ("c:/salida.xml");
    FileWriter out = new FileWriter(f1);
    f1.createNewFile();
    out.write(cadena);
    out.close();
    salida.println("OK");
    Now, the JAVA API is:
    import java.io.*;
    import java.net.*;
    public class HTTPSender {
    public static void main(String[] args) throws Exception {
    URL url1 = new URL
    ("http://localhost:8080/XMLSender/xmlwriter");//internal site
    URLConnection UrlConnObj1 = url1.openConnection();
    HttpURLConnection huc1 = (HttpURLConnection)UrlConnObj1;
    huc1.setRequestMethod("POST");
    huc1.setDoOutput(true);
    huc1.setDoInput(true);
    huc1.setUseCaches(false);
    huc1.setDefaultUseCaches(false);
    String cadena = ""
    + "<root>\n"
    + "<tlf>$TLF$</tlf>\n"
    + "<op>$OP$</op>\n"
    + "<sc>$SC$</sc>\n"
    + "<body>$BODY$</body>\n"
    + "</root>";
         PrintWriter out = new PrintWriter(huc1.getOutputStream());
    System.out.println("string="+cadena);
    out.write(cadena);
    out.close();
    I'm a JAVA newbie, so, maybe I'm getting a bad idea of what I need to do, anyway, every (detailed) help is welcome. What my servlet should do (and it doesn't when I send the message through the API) is to write a file with the info received.

    I'm not trying to send a string from a WEB Page, I'm tryring to send it using a JAVA program, I mean, using a HTTPSender, in fact, I already have made the code to do that:
    import java.io.*;
    import java.net.*;
    public class HTTPSender {
    public static void main(String[] args) throws Exception {
    try {
    String cadena = "Message to be written";
    // Send data
    URL url = new URL("http://localhost:8080/XMLSender/xmlwriter");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(cadena);
    wr.flush();
    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
    // Process line...
    wr.close();
    rd.close();
    } catch (Exception e) {
    And modified my servlet so it can receive anything:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.sql.*;
    public class xmlwriter extends HttpServlet
    public void service(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    ServletOutputStream salida = res.getOutputStream();
    res.setContentType("text/HTML");
    String cadena = req.toString();
    File f1 = new File ("c:/salida.xml");
    FileWriter out = new FileWriter(f1);
    f1.createNewFile();
    out.write(cadena);
    out.close();
    salida.println("OK");
    Now the problem is that, the servlet in fact DOES create the file, but....the file is empty, that means that no info is arriving to the servlet, why?, how should I send it then? I repeat FORGET about a Web Page Form, that is in the past and I don't need that.

  • C:import tag - Query string while calling servlet from JSP

    Hi,
    From my JSP I am calling a servlet to write back to the response stream of the JSP. From the JSP i am trying to pass some values into the query string as follows
         <%
         String strGetParameters = "/servlet/MyServlet?path=" + strPath;
          %>
         <pre><c:import url="<%=strGetParameters%>" /></pre>In the servlet I try to get the path from the query string by using
    request.getParameter("path")But in the servlet the query string doesnt have the "path" parameter that I added in the strGetParameters string (in the JSP).
    Am i missing something? Do i have to use something else or do something else?
    Any help is appreciated.

    I've taken some time to do a simple test and it just works.
    Here is the test code, it was tested in Java EE 5 + JSTL 1.2 + Tomcat 6.
    JSP<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
    <html>
        <head>
            <title>Test</title>
        </head>
        <body>
            <pre>
                <c:import url="myServlet?param1=foo&param2=bar">
                    <c:param name="param3" value="meep" />
                    <c:param name="param4" value="waah" />
                </c:import>
            </pre>
        </body>
    </html>MyServlet (mapped on "/myServlet")package mypackage;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class MyServlet extends HttpServlet {
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
            String param1 = request.getParameter("param1");
            String param2 = request.getParameter("param2");
            String param3 = request.getParameter("param3");
            String param4 = request.getParameter("param4");
            String output = param1 + ", " + param2 + ", " + param3 + ", " + param4;
            response.getOutputStream().write(output.getBytes());
    }All parameters gets printed.

  • How do I view previous strings of questions and answers on FF support?

    I read this response but it really doesn't answer the question.
    "If you are logged on then you see a My Contributions item in the Filter bar at the top that goes to:
    https://support.mozilla.org/questions?filter=my-contributions"
    I don't see the "filter bar" or "my responses" after I log in. I just see "Ask a question" "my log in name" and some other stuff to the right of that and below that.
    So after I log in, how do I look at strings of my previous questions and all responses to them, including new ones?

    I just figured it out!!! Wha-lah. Go to a question and then click on the underlined text in the question. Then a string of the Q and subsequent responses appears.

  • Classes and subclasses given as String input - question

    Hello, I am new in Java so please don't laugh at my question!!
    I have a method as the following and I am trying to store objects of the type Turtle in a vector. However the objects can also be of Turtle subclasses: ContinuousTurtle, WrappingTurtle and ReflectingTurtle. The exact class is determined by the String cls which is input by the user.
    My question is, how can I use cls in a form that I don't have to use if-else statements for all 4 cases? (Imagine if I had 30 subclasses).
    I have tried these two and similar methods so far but they return an error and Eclipse is not of much help in this case.
    Simplified methods:
    //pre:  cls matches exactly the name of a valid Turtle class/subclass
    //post: returns vector with a new turtle of type cls added to the end
    private Vector<Turtle> newturtle(Vector<Turtle> storage, String cls){
         Turtle t = new cls(...);
         storage.add(t);
         etc.
    private Vector<Turtle> newturtle(Vector<Turtle> storage, String cls){
         Turtle t = new Turtle<cls>(...);
         storage.add(t);
         etc.
    }Thanks for your help.
    p.s.: I didn't know whether to post this question here or under Generics.

    a Factory is atually very simple (100x simpler than reflection).
    example:
    class TurtleFactory
      public Turtle makeTurtle(String typeOfTurtle)
        if (typeOfTurtle.equals("lazy") { return new LazyTurtle(); }
        else if (typeOfTurtle.equals("fast") { return new FastTurtle(); }
        <etc>
    }While at first this doesn't look any better than your original problem, what we've done is made a class that is responsible for all the types of turtles. This will also benefit in case some turtles need initialization or need something passed to their constructor. You encapsulate all that knowledge in one place so you rcode doesn't become littered with it else ladders.

  • Can anyone help with string manipulation please?

    I am trying to change this string 43180-1-0001-37 into the following expression 43181-0001-37
    It is a string for Project No + Job Phase + Drawing No + Item No.
    The reduction of '43180' to '4318' is causing me the problem, I have the concatenation.
    Current report code is
    SELECT Os.[Orderno-o] As 'Order Number'
    ,Ph.PH_PHASE_NO + '.' + Re.REQUISITION_NUMBER As 'Req. Number'
    ,Pl.ID As 'Item ID'
    ,@CurrentProjectNumber + '-' + Ph.PH_PHASE_NO + '-' + Dr.DRAWING_NO + '-' + Cast(Pl.ITEM_NO As varchar(max)) As 'Drg & Item No.'
    It is this line giving me the problem?
    ,@CurrentProjectNumber + '-' + Ph.PH_PHASE_NO + '-' + Dr.DRAWING_NO + '-' + Cast(Pl.ITEM_NO As varchar(max)) As 'Drg & Item No.'

    Hi uh... Mr. Rubbish at SQL :)
    Unfortunately, there are many elements in your questions which aren't clear:
    1. What is the content in your columns PH_PHASE_NO, DRAWING_NO, ITEM_NO and what is their data type?
    2. What is the content of the variable @CurrentProjectNumber and what is its data type?
    3. It's unclear what is the logic behind the "reduction" of '43180' to '4318'. Do you want to remove trailing zeros? Shorten the value by one character? Because from what I see in your first sentence, it seems like you simply want to add 1 to '43180'
    and turn it into '43181'. That's a simple +1 operation. I also notice that you want to remove the "Job Phase" part from the string (which is "1" in your case)? Or do you need to add its value to the "Project No" (43180)? It's
    all quite confusing.
    Clarification would be highly appreciated.
    I would suggest, if you can, to please explain what you need NOT by specific examples, but by explaining your requirements IN GENERAL. In other words, don't use specific values like '43180', but start with a variable like 'X', and then let us know specifically
    what operation you want to perform on it (e.g. 'add 1' / 'remove trailing zeros' / 'shorten by one character' / 'add to it the value of some column' etc.). This will make it easier to understand the algorithm needed.
    Eitan Blumin; SQL Server Consultant - Madeira Data Solutions;

  • Using CharAt for String Manipulation

    Hi,
    I am new to Java and am taking a Java class. I am trying to put a social security number in "nnn-nn-nnnn" format where n is a digit 0-9. I don't know if it would work with the charAt method of the String class. Does anyone have any suggestions on how to implement this kind of manipulation.
    It would be greatly appreciated!
    Thanks,
    waggypup99

    You could just create a class for social security number.
    e.g.
    public class SSNum{
        private int _num;
        public SSNum(int number){
          _num = number;
          * take number in the form  nnn-nn-nnnn
        public SSNum(String number){
          StringTokenizer st = new StringTokenizer(number,"-");
          StringBuffer numStringB = new StringBuffer(st.nextToken());
          numStringB.append(st.nextToken());
          numStringB.append(st.nectToken());
         _num = Integer.parseInt(numStringB.toString());
       public String toString(){
          //left as fun exercise
    }

Maybe you are looking for

  • : / Doesn't seem to work with my appleTV

    Is there any good documents on Airplay? Based on what I have read here in the forums, I'm guessing that because I don't see the airplay icon my appleTV must be a first gen, although I didn't purchase it that long ago. I've made sure everything is up-

  • User Exit / BAdI to validate Overall Limit and Expected Value

    Hi SAP Gurus, I have a requirement that needs to check if Overall Limit exceeds the Expected Value (This is in tcode ME21N). Is there any user-exit or badi I can use? Thanks, Eo

  • Quick dock question---Using cmd-tab

    Hello, I am very used to using alt-tab to cycle through all the windows in XP. In XP it would cycle through all the open windows regardless if they were maximized, minimized, etc... In OS X if you minimize a window cmd-tab wont bring it out from the

  • ICloud enabled apps not sending data to iCloud

    I have many iCloud enabled apps, however only some of them will show up in the documents and data section under iCloud (Infinity Blade 2, Galaxy on Fire 2, Pocket God, W.E.L.D.E.R., Doodle Jump, Pocket God Journey to Uranus, and The Creeps!). However

  • 10.8.3 hdmi fix?

    Just installed the new update as i was under the impression that it would fix the poor dp - hdmi quality. After installing there is no change to the screen display. I still only get the 1080p option compared to running the rgb cable. have i missed so