Adivce on implementing boolean equals(Object)
Given that SomeClass extends Object and is is not part of an overly complicated hierarchy where each subclass adds some data useful to identify its instances.
Which version is better and why?
public boolean equals(Object o){
return (o != null
&& this.id != null
&& this.getClass().equals(o.getClass())
&& this.id.equals(((SomeClass) o).id))
|| super.equals();
public boolean equals(Object o){
return (o != null
&& this.id != null
&& o instanceof SomeClass
&& this.id.equals(((SomeClass) o).id))
|| super.equals();
}
So your question is about instanceof vs. comparing the results of getClass, right?
It depends on the semantics of your hierarchy.
The contract of equals says it has to be symmetric. a.equals(b) must return the same result as b.equals(a).
class Super {
class Sub extends Super {
Super super = new Super();
Sub sub = new Sub();
boolean b1 = super.equals(sub);
boolean b2 = sub.equals(super); If you use instanceof, then super's equals must be final, or else Sub's equals must only check for instance of Super, not instanceof Sub. If Super checks for instanceof Super, and Sub checks for instanceof Sub, then b1 (super.equals(sub)) can be true (since sub is an instance of Super) but b2 (sub.equals(super)) can never be true.
If you look at the collections hierarchy, you'll see that the equals methods check for instanceof the interface. For instance (HA!), two Lists are equal iff they both implement List, and they have the same elements in the same order. So ArrayList, LinkedList, and any custom List that you might implement must check instanceof List, not instanceof ArrayList, etc.
The general rule is, if you're going to use instanceof, then to preserve symmetry, all classes in the subtree must check for instanceof the same class (or interface), and it has to be at the highest (closest to Object) level in the subtree of classes that could be equal to each other.
Does that make sense?
¶
Similar Messages
-
Two equal objects, but different classes?
When programming on binding Referenceable object with JDK version 1.5.0_06, I have encountered a very strange phenomenon: two objects are equal, but they belong to different classes!!!
The source codes of the program bind_ref.java are listed as below:
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
import java.lang.*;
import java.io.*;
import java.util.*;
import javax.naming.*;
import javax.naming.spi.ObjectFactory;
import java.util.Hashtable;
public class bind_ref {
public static void main( String[] args ) {
// Set up environment for creating the initial context
Hashtable env = new Hashtable();
env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory" );
env.put( Context.PROVIDER_URL, "file:/daniel/" );
Context ctx = null;
File f = null;
Fruit fruit1 = null, fruit2 = null;
byte [] b = new byte[10];
try {
ctx = new InitialContext( env );
Hashtable the_env = ctx.getEnvironment();
Object [] keys = the_env.keySet().toArray();
int key_sz = keys.length;
fruit1 = new Fruit( "Orange" );
SubReference ref1 = fruit1.getReference();
ctx.rebind( "reference", fruit1 );
fruit2 = ( Fruit )ctx.lookup( "reference" );
System.out.println( "ref1's class = (" + ref1.getClass().toString() + ")" );
System.out.println( "fruit2.myRef's class = (" + fruit2.myRef.getClass().toString() + ")" );
System.out.println( "( ref1 instanceof SubReference ) = " + ( ref1 instanceof SubReference ) );
System.out.println( "( fruit2.myRef instanceof SubReference ) = " + ( fruit2.myRef instanceof SubReference ) );
System.out.println( "ref1.hashCode = " + ref1.hashCode() + ", fruit2.myRef.hashCode = " + fruit2.myRef.hashCode() );
System.out.println( "ref1.equals( fruit2.myRef ) = " + ref1.equals( fruit2.myRef ) );
} catch( Exception ne ) {
System.err.println( "Exception: " + ne.toString() );
System.exit( -1 );
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
All the outputs are shown as below:
=======================================================
Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
--------- (i)subref.hashCode() = (-1759114666)
SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
--------- (i)subref.hashCode() = (-1759114666)
FruitFactory: obj's class = (class javax.naming.Reference)
FruitFactory: obj's hashCode = -1759114666
FruitFactory: obj = (Reference Class Name: Fruit
Type: fruit
Content: Orange
FruitFactory: ( obj instanceof SubReference ) = false
FruitFactory: subref_class_name = (Fruit)
Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
ref1's class = (class SubReference)
fruit2.myRef's class = (class javax.naming.Reference)
( ref1 instanceof SubReference ) = true
( fruit2.myRef instanceof SubReference ) = false
ref1.hashCode = -1759114666, fruit2.myRef.hashCode = -1759114666
ref1.equals( fruit2.myRef ) = true
========================================================
I hightlight the critical codes and outputs related to the strangeness with bold texts.
Who can tell me what happens? Is it really possible that two objects belonging to different classes are equal? If so, why that?It can also depend on how you implement the equals method.
class Cat {
String name;
Cat(String n) {
name = n;
class Dog {
String name;
Dog(String n) {
name = n;
public boolean equals(Object o) {
return name.equals(o.name);
public static void main(String[] args) {
Dog d = new Dog("Fred");
Cat c = new Cat("Fred");
System.out.println(d.equals(c));
} -
Implementation of equals, hashCode, and
I am writing an RMI application where the implementation of the remote interface cannot extend UnicastRemoteObject because it already extends another class. So, I need to explicitly export the server object using UnicastRemoteObject.exportObject(server, 0);� no problem.
Problem is I�ve read that in order to make the class behave as if it had extend UnicastRemoteObject, you must provide implementations for equals, hashCode, and toString. I�ve searched the world over for implementations of these methods equivalent to those found in UnicastRemoteObject� no luck so far.
Could you help me out?
I�ve found some code that I�ve listed below� Is it equivalent to the equals and hashCode method found in UnicastRemoteObject? What about toString()?
public class RemoteDataServer extends LocalDataServer implements RemoteInterface{
private Remote serverStub;
public RemoteDataServer() throws IOException {
super();
//export remote object
serverStub = UnicastRemoteObject.exportObject(this);
public boolean equals(Object obj) {
return (obj == this || serverStub.equals(obj));
public int hashCode() {
return serverStub.hashCode();
//toString()???Hi,
At book Effective Java by Joshua Bloch you can see some info
overriding these members.
See at http://java.sun.com/docs/books/effective/index.html
Here is the toString()spec method from Object :
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
but toString from class String simply returns the string contents of
an object.
Hope this help -
Overriding equals(Object o) method
hi,
I have a problem in equals method ..returns true always...
can anyone suggest whats wrong ?
thanks for the help
public boolean equals(Object NumberC)
if (NumberC == null) return false;
if ( NumberC instanceof Counter)
Counter myCr = ( Counter) NumberC;
if(this.number == (myCr)
return true;
}//end if
} //end if
return false;
}// end equals
sorry..yes it always returns true
here's my code again
public boolean equals(Object NumberCounter)
if (NumberCounter == null) return false;
if ( NumberCounter instanceof Counter )
Counter myCr = ( Counter ) NumberCounter;
if(this.number == (myCr.number))
return true;
}//end if
} //end if
return false;
}// end equals -
List implementation where remove(Object) is fast?
Does anyone know of an implementation of the java.util.List interface where the the method boolean remove(Object o) is much faster than traversing through the list until it finds the right one? Perhaps something that takes advantage of the hash code of the object being removed?
ThanksSo you want a List that acts like a Map?
Couldn't you just use a Map?
Explain your problem domain better and we shall help
you see the light.
Well no - I would simply like a List that acts like a List, and whose remove(Object) method is faster than just scanning through each element.
I only mentioned use of the hash code as one way this could be implemented. To expand on that: Currently the LinkedList class internally maintains a list of Entry objects. Each of these objects has a reference to the previous and next Entry and the 'current' list element object. The problem is that the remove(Object) method has to go through each Entry one by one, searching for a list element that equals the object to be removed. To fix this problem the list implementation could also maintain a HashMap whose 'keys' are the list elements and whose 'values' are a (secondary) list of Entry objects associated with that key. Now the remove(Object) method could use the object to be removed to look up the 'list of associated Entry objects'. The first Entry in this (secondary) list is the one that needs to be removed.
But perhaps it's best if I describe the overlying problem: I want to write a program that randomly generates integers at the rate of about 10 per second. For each integer the program should calculate how many times in the past hour that number has been generated. What's the fastest way to calculate this? -
In classes that I write Is there any reason to not always override:
public String toString();
public boolean equals();
public Object clone(Object obj);Further, why not always provide a default Comparator ?
public Comparator getDefaultComparator();This seems logical?kakusaretasuna wrote:
thank you.
I am just beginning to learn Java, and so I am making a checklist of things to do when I write a class.
When it makes sense, I will always implement:
toString()
clone()
equals()
getDefaultComparator()getDefaultComparator? No, I wouldn't do that. Where did you get that idea from?
And if you override equals, you should always override hashCode as well, and vice versa.
As a rule, I do not override those methods unless I have a specific reason to.
And, I learned that by default a Java class is not Serializable . Therefore, for each of my
classes, I need to adjust them to safely be Serializable , and then declare them Serializable Only if there's a reason to serialize them. Again, it doesn't make sense for all classes, or even most.
This makes sense to me, however, I don't want to appear foolish to exeperienced developers. For example, I learned that:Worry less about appearing foolish and more about learning. Everybody had to start somewhere, and this stuff is generally not intuitive. Nobody cares if you don't automatically know it all.
>
private final void foo(); // "final" is annoying and foolish?As with most things, there are at least two schools of thought on that. In general, I don't make methods final unless I specifically don't want them overridden. Some people feel you should declare them final by default, and only remove the final in cases where there are specific reasons to override them. Neither is right or wrong. It's mostly a matter of convention, and somewhat a matter of context.
private void foo() { this.privateMethod(); } // "this" is annoying and foolish?I personally hate using "this" when it's not necessary, and it's never necessary in the case of method calls. It doesn't even add any clarity. It's just clutter.
>
I am sure there are many other construts that experienced developers avoid.Yes, but don't worry about learning them all right now. -
Hide or display Implementation Tab in object the PACKAGE
Hi!
How I can hide or display a "Implementation Tab" in object the PACKAGE for other users?
OWB 11.1.0.7.0
Thanks!
Edited by: user12277289 on 7/12/2009 6:20You can wrap your code if you dont want anyone to see it.
-
I've made custom User and UserStore classes.
Now I'm trying to register or login with a user, but I get the error
'Incorrect number of arguments supplied for call to method Boolean Equals(System.String, System.String, System.StringComparison)'
The error is on line 411:
Line 409: }
Line 410: var user = new User() { UserName = model.Email, Email = model.Email };
--> Line 411: IdentityResult result = await UserManager.CreateAsync(user);
Line 412: if (result.Succeeded)
Line 413: {
The problem is that I can't really debug UserManager's methods, because it is in a closed DLL.
I get this same error on
UserManager.FindAsync(user), UserManager.CreateAsync(user,password), UserManager.Create(User user)
Now the error doesn't occur when I log in with an External Login, like Google, which also uses methods from UserManager. Entering the email works
as well, but when the user has to be created from an External Login with the inserted email, it gives the CreateAsync error
too.
How can I fix this? Do I need to create my own UserManager? Or do I need another solution entirely?
Packages (relevant):
package id="Microsoft.AspNet.Mvc" version="5.1.2"
id="Microsoft.Owin" version="2.1.0"
id="Microsoft.AspNet.Identity.Core" version="2.0.1"
UserStore.cs
public class UserStore :
IUserStore<User, int>,
IUserPasswordStore<User, int>,
IUserSecurityStampStore<User, int>,
IUserEmailStore<User, int>,
IUserLoginStore<User, int>
private readonly NFCMSDbContext _db;
public UserStore(NFCMSDbContext db)
_db = db;
public UserStore()
_db = new NFCMSDbContext();
#region IUserStore
public Task CreateAsync(User user)
if (user == null)
throw new ArgumentNullException("user");
_db.Users.Add(user);
_db.Configuration.ValidateOnSaveEnabled = false;
return _db.SaveChangesAsync();
public Task DeleteAsync(User user)
if (user == null)
throw new ArgumentNullException("user");
_db.Users.Remove(user);
_db.Configuration.ValidateOnSaveEnabled = false;
return _db.SaveChangesAsync();
public Task<User> FindByIdAsync(int userId = 0)
int userid;
if (userId == 0)
throw new ArgumentNullException("userId");
return _db.Users.Where(u => u.UserId == userId).FirstOrDefaultAsync();
User.cs
public class User : IUser<int>
public User()
UserLogins = new List<UserLogin>();
public int UserId { get; set; }
public string UserName { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string Email {get; set; }
public bool IsEmailConfirmed { get; set; }
int IUser<int>.Id
get { return UserId; }
public ICollection<UserLogin> UserLogins { get; private set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User, int> manager)
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
Startup.Auth.cs
public partial class Startup
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(NFCMSDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User, int>(
validateInterval: TimeSpan.FromMinutes(20),
regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
getUserIdCallback: (id) => (Int32.Parse(id.GetUserId())))
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); (...)
Any help or ideas are greatly appreciated!
Kind regards,
NilsHi,
According to your description, I am afraid your problem is out of support in C# forum. For ASP.NET question, please go to
ASP.NET Forum to post your thread.
Best Wishes!
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. Thanks<br/> MSDN Community Support<br/> <br/> Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and
makes it easier for other visitors to find the resolution later. -
Implement a View Object with multiple entity objects
Hi
In 'How to' section on the 'otn.oracle.com' (Jdeveloper) web site is tutorial how to implement a View Object with multiple updateable dependent entity objects.
It allows user to insert an employee and a department at the same time.
But I would like to change this example to insert a new department only if it does not already exist. How to change this sample?
Is there any other way to this?
Thanks
Regards
GorazdOnce again the structure, sorry.
ViewObject
|-ParentEntityObject
..|-PId
..|-PAttribute
..|-CId (FK)
|-ParentChildAssociation
|-ChildEntityObject
..|-CId
..|-CAttribute
Christian -
Avoiding Bugs with equals(Object)
Hey, guys!
I've got a quick question. I've been diving through a new code base, lately, and I put a static analysis tool against it, and ran into a couple places where the code was using String.equals to compare one object that was a String, and another object that wasn't.
For example, the code looked like this:
expectedString.equals(actualObject);When it should have looked like this:
expectedString.equals(actualObject.aMethodThatProducesAString());It was human error, but the root of the problem was human error, but the compiler didn't complain, because java.lang.Object.equals accepts and object, and therefore, any class that is a subclass of java.lang.Object must also accept any type of Object. I brought it to the attention of a colleague to understand what the code was supposed to be doing. He felt that this really ought to raise a compiler error somehow, to prevent these mistakes. He suggested creating a static method of some sort that only accepts Strings, to do the comparison, and then have any other calls within our codebase that use equals(Object) fail at compile time. The only reasonable way I could think to do this without too much effort would be to use something like AspectJ to declare the method call illegal. But AspectJ doesn't play nicely with many of the other tools we are using.
Personally, this is the first time I've seen this become an issue, so I'm not sure it's really a big deal to just use a static analysis tool every once in a while to find stuff like that, but I wondered if anybody else had faced this problem in the past, and found some reasonable way to overcome it?
Thanks!
- AdamHe felt that this really ought to raise a compiler error somehow, to prevent these mistakes. Per the API definition, it was legal usage (I think someone else mentioned this, but it's important to repeat).
He suggested creating a static method of some sort that only accepts Strings, to do the comparison, Or even better, use the pre-written one from [Jakarta Commons|http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html#equals(java.lang.String,%20java.lang.String)]. This has the added benefit of being null-safe.
Personally, this is the first time I've seen this become an issue, so I'm not sure it's really a big deal to just use a static analysis tool every once in a while to find stuff like that, but I wondered if anybody else had faced this problem in the past, and found some reasonable way to overcome it?Good programming habits, and reliance on libraries of useful methods.
I'd suggest taking a day or two, grepping for every use of equals(), and replacing it. Then yell at people if they don't continue the practice. -
Integer.equals(Object) acting flakey in JDK/JRE 1.5
I am having a problem with java.lang.Integer.equals(Object).
Here's the code:
class Address
Integer id;
// Other fields...
class AddressDTO
Integer id;
// Other fields...
// Remove all Address Domain objects that are not represented in the UserDTO's address map.
l1: for(Address address : user.getAddresses().toArray(new Address[0]))
for(AddressDTO addressDTO : userDTO.getAdderssDTOs().values())
if(address.getId().equals(addressDTO.getId()))
continue l1;
user.removeAdderss(address);
My problem is, when address.id is 13 and addressDTO.id is 13, address.getId().equals(addressDTO.getId()) returns false when it should return true.
I watched this happen, even stepped through it with my Eclispe debugger, several times. I stepped into the Integer.equals(Object arg0) method, and verified that this.value=13 and arg0.value=13.
Then, I asked a coworker to come see it, and as I stepped through the code, for probably the 10th time, address.getId().equals(addressDTO.getId()) returned true as it should instead of false as it had the previous 9 times.
Can anyone tell me why or how this could happened?
Has anyone else witnessed this kind of behavior?This thread might explain it:
http://forum.java.sun.com/thread.jspa?threadID=5221311
Are you using new Integer(value) somewhere? You should be using compareTo rather than equals because equals will be checking that they are the same object reference rather than comparing their values. The caching mechanism of values from -128 to 127 could be causing this behavior.
Hmm, upon further review looks like equals is overridden. That is bizarre.
Edited by: Outtascope on Sep 29, 2007 10:42 AM -
Implementing Boolean operators during find object for qualification
Hi Team
We would like to maintain requirements profiles for PD object (position,job etc.) in terms of qualifications (Q) using complicated boolean operators , for example :
((Q=English>4 OR (Q=French=5 and Q=Spanish>2)) OR (Q=German=6 and english<3) and Q=education # 2
The complicated boolean operators could be also : range,excluded from the range,equal,not equal,not exits.
We would like to execute the search for qualification ,profile matchup based on this complicated boolean requirments profile.
Is there any custom development or configuration to make this happen ?
Best Regards
DrorIs this still true if the Collection generics elements are an interface type? For example, in the
code I sent earlier, I have:
/** The authorities granted to this account. */
private Set<Authority> authorities;
But Authority is an interface that is implemented by the DefaultAuthority class (maybe others
eventually). I was under the impression that in this situation, the metadata does have to provide
the actual type that will be in the collection.
But even if it works in Kodo, one of the requirements of my project is that the JDO implementation
be swapable with JPOX. When I started working on it, both Kodo and JPOX were at a much earlier stage
of implementing JDO 2, and if I recall correctly, JPOX required the implementation class (though I
don't know if it had to be fully qualified). I'm not sure that requirement has been removed from
JPOX yet, though I haven't checked in a while.
Thanks for your help with the default value settings though. Is there any place where I could have
found that behavior documented (Kodo docs, JDO2 spec, etc.)?
Mark
Abe White wrote:
p.s. You don't need to set the element-type in metadata if you're using
Java 5 generics; we can get the element type from the field declaration.
Also, when you do have to declare an element-type in metadata, you
don't need to fully qualify the class name if the element class is in
the same package as the field's owner (the current <package>), or in
java.util, java.math, java.lang. -
Implementing the CompareTo(Object T) method of interface Comparable T
Hi,
I cannot figure out how to write implementation to compare two objects for the CompareTo method.
I have an Employee class and a Manager class that inherits Employee and in the main method i want to sort the objects so that i can use the method binarySearch(Object[] a, Object key), originally i sorted each object in order of their salaries but i now need to be able to distinguish between a Manager object and an Employee object.demo:
class Base implements Comparable<Base> {
private String baseField;
@Override public int compareTo(Base that) {
return this.baseField.compareTo(that.baseField);
class Derived extends Base {
private String derivedField;
@Override public int compareTo(Base that) {
int result = super.compareTo(that);
if (result == 0 && that instanceof Derived) {
Derived thatThang = (Derived) that;
result = this.derivedField.compareTo(thatThang.derivedField);
return result;
}Base objects are ordered by baseField. (I assume all fields will be non-null, for simplicity.) Between Derived objects with equal baseField, I order them further by derivedField.
edit. I should mention that there are headaches that usually follow when you compare objects of different types. Suppose you have three objects:
obj1, a Derived object with baseField = "b", derivedField = "x"
obj2, a Base object with baseField = "b"
obj3, a Derived object with baseField = "b", derivedField = "y"
according to the compareTo methods, obj1 and obj2 are equal, and as well, obj2 and obj3 are equal, but obj1 and obj3 are not equal, so we do not have transitivity. ;-( -
Drill function implemented on Measure object column in the webi report
Post Author: madan kumar
CA Forum: WebIntelligence Reporting
Hi,
I have a small issue in my project.(Maintenance Project)I created a measure object in the fact table of the existing universe and saved and exported to the repository. (Say Measure object is D where D = A-(B+C))I inserted the same object as a column between two measure objects columns of a existing WebI report.
The report has two hierarchies involved - each hierarchy has dimension objects involved.I have checked with the hierarchies to make sure that measure object is not involved.The scope of analysis is None for the query.Version is BO XI R2.
The issue is the Drill function is implemented on that particular new column.The drill function should be applicable only to the two dimension objects involved in the report.But this measure object column is also getting drilled once the Drill option is selected.I had to remove the drill optiion from the Measure object column.
Can anyone help me on this issue...
Thanks in advance...
Madan KumarSushil
Thanks for your reply. I did the date diff on the columns. It does not break into 3 different groups. I am using a function called previous on the date column. So the report is like this
DATE Pervious (DATE) Date - Pervious(DATE)
01-01-2008 01:06 Null
01-01-2008 01:12 01-01-2008 01:06 :06
01-01-2008 01:18 01-01-2008 01:12 :06
01-01-2008 01:24 01-01-2008 01:18 :06
01-01-2008 01:30 01-01-2008 01:24 :06
01-01-2008 01:36 01-01-2008 01:30 :06
Basically we are breaking on the Date - Previous ( Date) column which does not work. I am not sure if there is a way to break this. I even tried it in Crystal REports XI and it does not work their either. Any help with this issue with be greatly appriciated.
Edited by: Srinivasa Prabu on Aug 4, 2008 2:55 PM
Edited by: Srinivasa Prabu on Aug 4, 2008 2:56 PM -
How to implement a Session Object.
Hi,
If anybody show me any example of how to implement
session object so that I can store any parameters such as user id and use it later on. And also if there is any good web site for reference about using session object.
thanksYou can use the the session.setAttribute and session.getAttribute methods.
For example let's say you would want to store a username in the session after a user has logged on:
String usrname = request.getParameter("username");
session.setAttribute("myStoredUsername", usrname);
you can then retrieve it using the get method. Remember that the entities stored inside a session object are generic objects and need to be cast to be used:
String usrname2 = (String)session.getAttribute("username");
Hope this helps
Chelman
Maybe you are looking for
-
How to achieve parallel execution of two or more Entity Framework queries?
Hi Everyone, I'm creating some WCF service that use EF to query the database for the data that I need. The problem I have at the moment is that I have 2 or more EF LINQ queries which are declared and then executed to bring back my data... but this is
-
Time Machine problem after restoring to a new HD (after my original HD failed)
I am running Lion 10.7.5 on a MacBook Pro Late '11 My HD was getting SMART errors, so I did a complete back up using Time Machine using a WD My Passport 1TB external, and then sent my MBP to Apple for HD replacement (under my Applecare plan). I colle
-
The Procedure entry point Could not be located in the dynamic Link Library
I have recently received an error message that starts out with "The Procedure entry point XXX Could not be located in the dynamic Link Library" and then I get an Error 7 (Windows error 127). iTunes will not start. I have uninstalled all Apple program
-
Re : item category in BOm
Hi While creating BOM how to set Item category of the higher-level item like TAN TAQ. Thanks mani
-
Error updating the dataset!!
Hi, Currently our endusers are working with SAP Lumira, automatic update to 1.15.1, Build 879 was made; but what we can see is that the stories that were already generated with a version 1.14 and they try to refresh this stories, SAP Lumira sen