天道酬勤,学无止境

How can I get Tomcat to output empty string instead of null?

Question

I just switched over to Tomcat 6.0.26 from a different Servlet/JSP engine. Previously, null values would print out as an empty String. However, Tomcat is printing out nulls as "null".

<% String str = null; %>
The value of str is <%= str %>.

This outputs

The value of str is null.

How can I get Tomcat to replace nulls with empty/blank strings?

Answer1

This is default and expected behaviour. Apparently the previous server has some proprietary configuration setting for that. None in Tomcat comes to mind.

Regardless, scriptlets is a vintage technique and its use is discouraged over a decade. It has been succeeded by taglibs (like JSTL) and Expression Language (EL) in combination with a Servlet as controller.

E.g. in Servlet's doGet():

String str = null;
request.setAttribute("str", str);
request.getRequestDispatcher("page.jsp").forward(request, response);

and in page.jsp:

The value of str is ${str}

EL will by default print nothing if the value equals null while scriptlet expression (<%= %>) by default prints whatever String#valueOf() returns.

See also:

  • Beginning and intermediate JSP/Servlet tutorial
Answer2

Looks like you want to fix this in your code as there doesn't appear to be an option in tomcat to turn this behaviour off. (There apparently is in weblogic if that's what you were using - see "printNulls").

From the javadocs of Tomcat's JspWriterImpl#print()

public void print(java.lang.String s)
throws java.io.IOException

Print a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

Specified by:
print in class javax.servlet.jsp.JspWriter
Parameters:
s - The String to be printed
Throws:
java.io.IOException - If an error occured while writing

标签

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

相关推荐
  • h:inputText which is bound to Integer property is submitting value 0 instead of null
    Question We are using a h:inputText in a JSF page which is bound to an Integer property (and thus can accept null). When there is no value written in the h:inputText, the form is submitting a 0 instead of null. We are using Trinidad 1.2.2 and Tomcat 6.0.20 (we also tried with Tomcat 6.0.14 as we read that this could happen with certains Tomcat versions). How is this caused and how can I solve it? Answer1 This "feature" was result of a bugfix in EL which was introduced as per Tomcat 6.0.16. As per chapter 1.18.3 of the EL specification, a value of number type which is null should be coerced to
  • Tomcat 8 (and 9) coerce behaviour, null strings are incorrectly set as empty strings
    Question I have just migrated to Tomcat 8. I used to work with system property org.apache.el.parser.COERCE_TO_ZERO=false so empty strings, numbers, booleans etc. are treated as null. In Tomcat 8, EL 3.0, it is supposed to be the default but it is in fact converting null string to empty string "" on JSF side. It is supposed to be a bug and it is supposed to be corrected but I'm not able to get it working in TomEE snapshot (Tomcat 8.0.27.0, MyFaces 2.2.8). Answer1 This is a bug in the EL 3.0 specification. Since EL 3.0, as consequence of overzealous fix of JSP spec issue 184, null will be
  • h:inputText which is bound to String property is submitting empty string instead of null
    Question I have a JSF 2.0 application on Tomcat with many <h:inputText> fields to input data in my database. Some fields are not required. <h:inputText value="#{registerBean.user.phoneNumber}" id="phoneNumber"> <f:validateLength maximum="20" /> </h:inputText> When the user leave this field empty JSF sets empty string "" instead of null. How can I fix this behavior without checking every String with if (string.equals("")) { string = null; } Answer1 You can configure JSF 2.x to interpret empty submitted values as null by the following context-param in web.xml (which has a pretty long name, that
  • Integer getting default value 0 where it required to be NULL in Java [duplicate]
    Question This question already has an answer here: h:inputText which is bound to Integer property is submitting value 0 instead of null (1 answer) Closed 5 years ago. My requirement looks simple, but I feel I'm doing something wrong in code. All I need is to insert "null" in Oracle Database when nothing is passed from InputText field of UI. PaymantSpecFormPage.xhtml <h:inputText id="startWeek" value="#{flowScope.paymentSpecVO.paymStartWk}" styleClass="inputTypeForm" maxlength="4"/> PaymentSpecVO.java public class PaymentSpecVO extends BaseVO<PaymentSpec> { private Integer paymStartWk; public
  • In jsf how integer properties get value 0 in client page without process validation phase for first time request [duplicate]
    Question This question already has answers here: How to make number input area initially empty instead of 0 or 0.00? (4 answers) Closed 5 years ago. I have a bean as shown @ManagedBean @RequestScoped public class Demo { private int value1; private String value2; ..getter and setter.. this is my xhtml page demo.xhtml <h:form> <p:panelGrid columns="2"> <p:outputLabel value="id"></p:outputLabel> <p:inputText value="#{demo.value1}"></p:inputText> <p:outputLabel value="name"></p:outputLabel> <p:inputText value="#{demo.value2}"></p:inputText> </p:panelGrid> </h:form> how the integer value get 0
  • JSON.stringify output to div in pretty print way
    Question I JSON.stringify a json object by result = JSON.stringify(message, my_json, 2) The 2 in the argument above is supposed to pretty print the result. It does this if i do something like alert(result). However, I want to output this to the user by appending it inside a div. When I do this I get just a single line showing up. (I don't think it is working because the breaks and spaces are not being interpreted as html?) { "data": { "x": "1", "y": "1", "url": "http://url.com" }, "event": "start", "show": 1, "id": 50 } Is there a way to output the result of JSON.stringify to a div in a pretty
  • .Net C# String.Join how to output “null” instead of empty string if element value is null?
    Question According to the MSDN docs for String.Join "If any element in value is null, an empty string is used instead." The code I have pulls data out of a DataTable rotationValues = string.Join<object>(", ", from r in rotationData.Rows.OfType<DataRow>() select r[5]); This would result in output similar to this: 8, 7, , 12, , , 13, Is there any way to simply have it put "null" in place of an empty string like so: 8, 7, null, 12, null, null, 13, null Answer1 You can select r[5] ?? "null" instead of just r[5]. Also, just remove the <object> part when you call the generic method. It will still be
  • Tomcat server absolute file access in war webapp
    Question I have a Spring webapp whose .war file has been uploaded to a Tomcat server. Most of the basic functions are working as intended - page views and form submission. My problem now is that my webapp needs to read and write files and I am clueless as to how I can achieve this (the file I/O returns java.lang.NullPointerException). I used the following code to get the absolute path of a given file suggested by Titi Wangsa Bin Damhore to know the path relative to the server: HttpSession session = request.getSession(); ServletContext sc = session.getServletContext(); String file = sc
  • Basic knowledge and understanding of jsp
    Introduction: The full name of JSP is JavaServer Pages, which, like servlet technology, is a technology defined by SUN for developing dynamic web resources. The biggest feature of JSP technology is that writing jsp is like writing html, but: Compared with HTML, HTML can only provide users with static data, while Jsp technology allows Java code to be nested in the page to provide users with dynamic data. Compared with servlet, servlet is difficult to typeset data, and jsp can use java code to generate dynamic data, but it is also easy to typeset data. Whether it is JSP or Servlet, although it
  • How to make number input area initially empty instead of 0 or 0.00?
    Question I have an input place that should get a number. I want it to be displayed as empty. However when I run my program, I get 0 or 0.00 as default. How can I make it empty? Answer1 This will happen if you bound the value to a primitive instead of its wrapper representation. The primitive int always defaults to 0 and the primitive double always defaults to 0.0. You want to use Integer or Double (or BigDecimal) instead. E.g.: public class Bean { private Integer number; // ... } Then there are two more things to take into account when processing the form submit. First, you need to instruct
  • Java & Local Databases
    Question TL DR; Want some Java help with connecting to a truly local database ( no access to server tech ), or if you can whip up code, that will work. All it has to do is query the DB ( MS Access, although can be changed ), and output a JSON string. See EDIT2 for more specificity. EDIT: Before anyone says JDBC; I looked through the tutorials ( started reading in depth ), but most of it seems to be geared towards server tech, which I have no access to. EDIT2: Seems most the answers so far are requiring an installation of some kind which I unfortunately cannot do ( and failed to mention, so I
  • web backend (javaWeb)
    Article Directory 1. Introduction to javaweb 2.XML 3.Tomcat server 4.Servlet1 5.1 Protocol Internet Communication Model 5.2HTTP 6.servlet2 7. JDBC 8.JSP 9. File download and upload in JSP 10. The difference between request redirection and request forwarding 11.Cookie and Session 12. Use of Google Verification Code 13.Filter 14. Use of ThreadLocal 15.JSON and Ajax requests 15.1 The use of JSON in java (mutual conversion) 15.2 Ajax request 16.i18n (Internationalization) 1. Introduction to javaweb What is javaweb? What can be done? Java web is the general term for technologies that use Java
  • How do I correctly decode unicode parameters passed to a servlet
    Question Suppose I have: <a href="http://www.yahoo.com/" target="_yahoo" title="Yahoo!™" onclick="return gateway(this);">Yahoo!</a> <script type="text/javascript"> function gateway(lnk) { window.open(SERVLET + '?external_link=' + encodeURIComponent(lnk.href) + '&external_target=' + encodeURIComponent(lnk.target) + '&external_title=' + encodeURIComponent(lnk.title)); return false; } </script> I have confirmed external_title gets encoded as Yahoo!%E2%84%A2 and passed to SERVLET. If in SERVLET I do: Writer writer = response.getWriter(); writer.write(request.getParameter("external_title")); I get
  • How to set up classpath of JavaCompiler to multiple .jar files using wildcard
    Question I am using JavaCompiler of javax.tools to compile some java code and I am trying to use wildcard in my classpath in order to include all the .jar files but I fail. Here is my code: String classpath = "C:\tomcat6\webapps\myapp/WEB-INF/lib/javax.ws.rs-api-2.0-m10.jar;" + "C:\\tomcat6\\webapps\\myapp/WEB-INF/lib/javax.persistence-2.1.0.jar"; Iterable<String> options = Arrays.asList("-d", classesBaseDir, "-classpath", classpath); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, file); boolean result = task.call(); The code above works
  • Jackson Mapper serialize empty object instead of null
    Question Say I have classes Foo public class Foo { private Bar bar; } and Bar public class Bar { private String fizz; private String bang; } EDIT: For clarification I do not own Foo and Bar and cannot alter these classes. If I want to serialize an empty object of type Foo, it's member, which is of type Bar, will be returned as null. String json = objectMapper.writeValueAsString(new Foo()); // "{"bar" : null}" Is there any way I can get the object mapper to serialize an empty Bar object without having to instantiate a new instance of Bar and then adding it to a new instance of Foo? String json
  • How to access static resources when mapping a global front controller servlet on /*
    Question I've mapped the Spring MVC dispatcher as a global front controller servlet on /*. <servlet> <servlet-name>home</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>home</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> However, this mapping stops the access to static files like CSS, JS, images etc which are all in the /res/ folder. How can I access them anyway? Answer1 I've run into this also and never found a great solution. I ended up mapping my servlet one level higher in the URL
  • Injecting a Spring bean using CDI @Inject
    Question I'm trying to inject a bean defined in a Spring context into a CDI managed component but I'm not successful. The bean is not injected, instead a new instance gets created each time the injection should be performed. My environment is Tomcat 7 with JBoss Weld. The Spring ApplicationContext is straighforward: <beans> ... <bean id="testFromSpring" class="test.Test" /> ... </bean> The CDI managed bean looks like this: @javax.inject.Named("testA") public class TestA { @javax.inject.Inject private Test myTest = null; ... public Test getTest() { return this.myTest; } } This is my faces
  • Empty parameter is not Null in function
    Question Given this basic function: Function TestFunction { Param ( [int]$Par1, [string]$Par2, [string]$Par3 ) If ($Par1 -ne $Null) { Write-Output "Par1 = $Par1" } If ($Par2 -ne $Null -or $Par2 -ne '') { Write-Output "Par2 = $Par2" } If ($Par3 -ne $Null) { Write-Output "Par3 = $Par3" } } TestFunction -Par1 1 -Par3 'par3' ...the output is: Par1 = 1 Par2 = Par3 = par3 Even though I didn't pass anything into the $Par2 variable, it still isn't Null or empty. What happened, and how can I rewrite the statement so that the second If-statement evaluates as False and the script-block does not get
  • redirecting output to the text file c#
    Question This is my code: Process pr2 = new Process(); pr2.StartInfo.FileName = "show-snps"; pr2.StartInfo.Arguments = @"-Clr -x 2 out.delta > out.snps"; pr2.Start(); pr2.WaitForExit(); show-snps writes an error. when I delete the part "> out.snps" everything is ok and it writes the result into the terminal, but I need to redirect it to the text file. How can I do this? Answer1 You can't redirect like that when you are starting the program like that. It requires a shell such as CMD.EXE to do that. Instead, you need to set ProcessStartInfo.RedirectStandardOutput to a stream that you manage
  • Json Convert empty string instead of null
    Question I'm trying to serialize my struct so that the strings that didn't get a value get their default value "" instead of null [JsonProperty(PropertyName = "myProperty", DefaultValueHandling = DefaultValueHandling.Populate)] [DefaultValue("")] public string MyProperty{ get; set; } My result in the Json string: "myProperty": null, what i want "myProperty": "", I also tried creating a converter without any effect, the can Convert and WriteJson functions aren't even firing for some reason: [JsonProperty(PropertyName = "myProperty")] [JsonConverter(typeof(NullToEmptyStringConverter))] public