Reputation: 127
I have a Struts 2 , spring security app. I have a requirement for which I need to make the fields in JSP read only. If the user logged in is not the creator of document then he/she should not be able to edit the document just view the information. Is there any way I can achieve this using struts and JSP ? Or I need to have a different form for read and edit?
Upvotes: 0
Views: 2093
Reputation: 50231
There are really several ways to do this.
Assuming a List<Document> documents;
, and the Document
object having fields like documentId
, ownerId
, description
, and a User object stored somewhere, and accessible through getCurrentUser() (eg. from a BaseAction extended by the other ones), you can check it inline with
<s:iterator value="allDocuments" var="currentDocument" status="stat">
<s:hidden name="allDocuments[%{#stat.index}"].documentId />
<s:if test="%{currentUser.id.equals(#currentDocument.ownerId)}">
<s:textfield name="allDocuments[%{#stat.index}"].description" />
</s:if>
<s:else>
<s:textfield name="allDocuments[%{#stat.index}"].description"
readonly="true" />
</s:else>
<br/>
</s:iterator>
In case you have to perform more complicated checks, you can call an Action function while iterating the documents:
<s:iterator value="allDocuments" var="currentDocument" status="stat">
<s:hidden name="allDocuments[%{#stat.index}"].documentId />
<s:if test="%{amIOwnerOfThisDocument(#currentDocument.ownerId)}">
<s:textfield name="allDocuments[%{#stat.index}"].description" />
</s:if>
<s:else>
<s:textfield name="allDocuments[%{#stat.index}"].description"
readonly="true" />
</s:else>
<br/>
</s:iterator>
and in the Action:
public boolean amIOwnerOfThisDocument(String ownerId){
return getService().checkSomethingComplex(getCurrentUser().getId(),ownerId);
}
And so on.
Important : don't forget to replicate this kind of control server side while accepting the data received from the JSP... it's easy for a malicious user to forge a request with data that should not be modifiable by him, eg. with Firebug / Firefox console, simply removing the readonly
attribute.
Upvotes: 1
Reputation: 1668
This is assuming that you're saving some kind of an identification for the current user on your session.
On your form, use a ternary operator to know if it should be readonly
or not.
Something like this:
<input type="text" ... ${sessionScope.userId.equals(userIdOfTheCreator)?"":"readonly"}>
If the current user is the same as the one who created the document, then don't add readonly
attribute, else do otherwise.
Upvotes: 1