Pages

Tuesday, November 27, 2012

Jquery ajax request send json object after binding from a form

This is a common mistakes done by jquery developers. Say you have a form (with form tags) and you extract the form data and create a json object and send it to a url via ajax. Also lets say your action is also the ajax url. Then if you send the content via jquery ajax, pre-request callback will append the form content to the jason object you extracted. So in order to avoid this you can set return to false in the form.

Wednesday, November 21, 2012

Save or Update vs Merge operations in hibernate

Following is from the hibernate documentation.

saveOrUpdate() does the following:
if the object is already persistent in this session, do nothing
if another object associated with the session has the same identifier, throw an exception
if the object has no identifier property, save() it
if the object's identifier has the value assigned to a newly instantiated object, save() it
if the object is versioned (by a <version> or <timestamp>), and the version property value is the same value assigned to a newly instantiated object, save() it
otherwise update()

merge() is very different:
if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance
if there is no persistent instance currently associated with the session, try to load it from the database, or create a new persistent instance
the persistent instance is returned
the given instance does not become associated with the session, it remains detached

You should use merge when there is an  object that was detached from the session and a persistence object of it is currently associated with the session.

Tuesday, November 20, 2012

Jackson access node elements and binding sub trees in to java objects

Say you have several types of pojos and you need to send them in json format. Finally you need to deserialize them. In this post lets see how you can access subtrees of the json object and deserialize them in to pojos.

In this example we are using jackson. Another popular json serialize/deserialize library is google's gson library. How ever the gson library does not support maps at the moment. Therefore you cannot use key/value concept to access the json object.
Now let's see how we can do this. In this example, the json string contains lecturer object and an array of subject ids. Say we need to get these two objects separately.

ObjectMapper mapper = new ObjectMapper();//need this to deserialize in to required pojo
JsonNode rootNode = mapper.readTree(json);//json is the json string.
JsonNode lecturerNode = rootNode.path("lecturer");//get the lecturer node from json root node using the related key.
JsonNode subjectIdNode = rootNode.path("selectedSubjects");//get the array from json root node using the related key.
Lecturer lecturer = mapper.readValue(lecturerNode, Lecturer.class);//use the mapper to get the object
String[] subjectIdList = mapper.readValue(subjectIdNode, String[].class);

Monday, November 19, 2012

Managing js, css resources in the maven webapp

external java scrpt files and css files are essential when developing a cool webapp. So how would you manage your files? As far as I know the best way is to put it under webapp folder. That way, all the js and css files will be included in the war file that you will generate. First create a folder named resources in your webapp folder. then put your js files in a folder called js. and css files in a folder called css. Now link your file in the jsp file like below.

<script src="<%=request.getContextPath()%>/resources/js/youfile.js" type="text/javascript">/script>

But still the dispatcher-servlet does not know how to link your file. It will try to get the file in the default manner (Through controller mapping if you use controllers). You need to put the following 2 lines to handle this problem.

 <bean class = "org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" /><mvc:resources mapping="/resources/**" location="/resources/" />

This will easily link you js files. You can link css files in the same manner as well.

Friday, November 16, 2012

hibernate ondelete cascase for generic collection

Well if your are doing a @OnDelete(action=OnDeleteAction.CASCADE) for a generic collection like a list of strings etc... then chances are that hibernate will raise an exception. It cannot initialize the sessionfactory bean. This at the moment, is a bug in hibernate. The easiest method is to clear the collection and saving first, then deleting the entity.
How ever most of the time, if you are doing a bulk deletion using hibernate, then chances are that you are on your own. You will have to handle them rather than expecting hibernate to handle everything with a single annotation.

Tuesday, November 13, 2012

showing and hiding elements based on the user role in spring security


In the previous blog post I showed you how to  provide method level security.  Now let's see how to hide or show elements based on the user role. Well it is quite simple with spring security tag library. just do the following to grant rights to view a specific user role to access some content.

declare the tag lib as follows in the jsp file

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

* Note that in order to use the above library you need to add the spring security tag lib jar file in your class path. you can easily get the dependency from maven repository.

Then go to the element you need to grant rights and surround it with the following block.
<sec:authorize access="hasRole('supervisor')">
</sec:authorize>

Also do not forget to put the following line to your spring security context file.
<beans:bean class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"/>

Providing method level security

I showed you how to provide basic security in spring mvc with intercept url patterns in here. Now with that knowledge let's see how to provide method level security.

This can be achieved by using @Preauthorize annotation. First you need to enable it. For that you need to add the following line to your dispatcher servlet.


<global-method-security
pre-post-annotations="enabled" />

Then you can use @Preauthorize annotation.
eg : @PreAuthorize("isAuthenticated() and hasRole('ROLE_ADMIN')")

In the above example the method is allowed to execute if the user is authenticated and has the ROLE_ADMIN role.

How ever you can use @Secure annotation as well. For that you need to add the following line to your dispatcher servlet.

<global-method-security secured-annotations="enabled" />

How ever the first method gives you more flexibility to handle the permissions as it is based on expressions.

hibernate lazy initialization and jason response to an ajax call

Some days back I was coding and found an interesting problem. It is as follows.

I have two classes called Lecturer and Course. My Lecturer class has a List of Course objects a variable as shown
@OneToMany(mappedBy = "lecturer")
@NotFound(action = NotFoundAction.IGNORE)
private List<Course> courseList = new ArrayList<Course>();

In my course class I have a Lecturer object as a variable as below.

@ManyToOne@JoinTable(name = "course_lecturer", joinColumns = @JoinColumn(name = "course_id"), inverseJoinColumns = @JoinColumn(name = "lecturer_id"))
private Lecturer lecturer;

Now I have a spring Controller method that returns a json object of Lecturer as below.

@RequestMapping(value = "/getlecturerbyid", method = RequestMethod.POST)

public @ResponseBodyObject getLecturer(@ModelAttribute(value = "id") Lecturer lecturer) {

Map<String, Object> response = new HashMap<String, Object>();
    response.put("message", "succeess");
    response.put("lecturer", lecturer);return response;
}

The problem is it throws a lazy initialization exception. Therefore I set fetch type in both variables in Lecturer and Course class to eager. Now the problem is it infinitely tries to fetch objects eagerly(if I unset fetch of either, it raises the same exception).On the other hand if I remove the