可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am learning form processing with spring mvc framework. But I have a problem with giving the <form:textarea /> tag a default value.
When I created a .jsp file as follow,
<form:textarea path="Content" id="my-text-box" />${content}
jsp parser translate the above line to: (let me assume that ${content} contains "hello world".)
<textarea id="my-text-box" name="Content"></textarea>third hello world!
Also, giving the value attribute does not work.
<form:textarea value="${content}" path="Content" id="my-text-box" />
jsp gives me as html output:
<textarea id="my-text-box" name="Content" value="third hello world!"></textarea>
you know the <textarea> tag does not have the value attribute.
How can I pass a default value to <form:textarea> tag? Thank you in advance.
回答1:
The Spring form tags are for data binding (e.g. your model attributes are bind to the form via path attribute of the form). If you need to specify defaults, then set the Content attribute of the ModelYouArePassingToView to the desired default value in the controller before it gets to the view.
If your using Spring MVC and @RequestMapping, a really good place for this in your controller would be your @ModelAttribute method. For example:
@ModelAttribute("modelYouArePassingToView") public ModelYouArePassingToView createDefault() { //construct it with default values for "Content" //attribute, and it will show up in textarea after the bindind ModelYouArePassingToView myapv = new ModelYouArePassingToView(); myapv.setContent(..); //default value return myapv; }
In your form, make sure to include the modelAttribute tag attribute:
<form:form modelAttribute="modelYouArePassingToView" ...> <form:textarea path="content" ..>
回答2:
Maybe you can use placeholder.
<form:textarea id="id" class="class" path="path" placeholder="test"/>
回答3:
I faced a similar situation. The below code:
<form:textarea path="Content" id="my-text-box">${content}</form:textarea>
Worked out for me.
回答4:
You can also set the defaul text in the Model as well. Your jsp would have:
<form:textarea path="my-text-box" rows="20" cols="100" cssClass="rounded"/>
and then in the Model, you'd have:
private static final String DEFAULT_textareacontent = "Hello World"; private String my-text-box = DEFAULT_textareacontent;
Not sure if this is a best practice or not, but it seems to work for me.
回答5:
This works in Spring 4 where the form:textarea tag must be empty:
<form:textarea path="content" value="${Object.content}"/>