patternjavaMinor
Minimize boilerplate code in Action class
Viewed 0 times
minimizeactioncodeboilerplateclass
Problem
I perform an
I have this kind of
How can I improve on what I am trying to achieve?
if-check (commented in the code) to determine whether a user can access certain actions or not. The user will be redirected to the index page if they try to access the login.action while already logged in.I have this kind of
if-check in many of my Action classes (containsKey() or !containsKey(), depending on the action) and it is looking very redundant.How can I improve on what I am trying to achieve?
public String execute() throws Exception {
// redirect if user is already logged in
if(session.containsKey("currentId")) {
return "index";
}
Integer currentId = mm.getCurrentId(member.getMemberId());
String currentAccessType = mm.getMemberInfo("member_access_type", member.getMemberId());
System.out.println("Current ID: " + currentId);
System.out.println("Current Access Type: " + currentAccessType);
session.put("currentId", currentId);
session.put("currentAccessType", currentAccessType);
System.out.println("You have logged in!");
return SUCCESS;
}Solution
Aspect-Oriented programming would seem to be the way to go here. Since you're using Struts2, use
Interceptors to wrap around the relevant actions. Inside the interceptors, do your check and redirect. You want two, one for the affirmative, and one for the negative.Context
StackExchange Code Review Q#75191, answer score: 2
Revisions (0)
No revisions yet.