spring how to pass values from one page to controller? - model-view-controller

I am developing a spring mvc application . I just want to do the following ,
When user clicks on a link , I just want to pass some values from that page to the target Controller of that link.
Is AbstractCommandController will be useful for this ?
Is there any way other than using session attributes ?

You can do it in one of the following ways:
1) Submit Form.
2) Send it as parameters in your URL.
3) Create cusom flash scope for your application:
You can read more about it here:http://goo.gl/nQaQh
In spring MVC there is no Flash Bean scope so you can do it as Interceptor:
Here is the simple code how to use
public class FlashScopeInterceptor implements HandlerInterceptor {
public static final String DEFAULT_ATTRIBUTE_NAME = "flashScope";
public static final String DEFAULT_SESSION_ATTRIBUTE_NAME = FlashScopeInterceptor.class.getName();
public static final int DEFAULT_RETENTION_COUNT = 2;
private String sessionAttributeName = DEFAULT_SESSION_ATTRIBUTE_NAME;
private String attributeName = DEFAULT_ATTRIBUTE_NAME;
private int retentionCount = DEFAULT_RETENTION_COUNT;
/**
* Unbinds current flashScope from session. Rolls request's flashScope to
* the next scope. Binds request's flashScope, if not empty, to the session.
*
*/
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
if (request.getSession( false ) != null)
{
request.getSession().removeAttribute( this.sessionAttributeName );
}
Object requestAttribute = request.getAttribute( this.attributeName );
if (requestAttribute instanceof MultiScopeModelMap)
{
MultiScopeModelMap attributes = (MultiScopeModelMap) requestAttribute;
if (!attributes.isEmpty())
{
attributes.next();
if (!attributes.isEmpty())
{
request.getSession( true ).setAttribute( this.sessionAttributeName, attributes );
}
}
}
}
/**
* merge modelAndView.model['flashScope'] to current flashScope
*/
#Override
public void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
if (modelAndView != null)
{
Map<String, Object> modelFlashScopeMap = null;
for (Iterator<Entry<String, Object>> iterator = ((Map<String, Object>) modelAndView.getModel()).entrySet()
.iterator(); iterator.hasNext();)
{
Entry<String, Object> entry = iterator.next();
if (this.attributeName.equals( entry.getKey() ) && entry.getValue() instanceof Map)
{
if (modelFlashScopeMap == null)
{
modelFlashScopeMap = (Map) entry.getValue();
}
else
{
modelFlashScopeMap.putAll( (Map) entry.getValue() );
}
iterator.remove();
}
else if (entry.getKey().startsWith( this.attributeName + "." ))
{
String key = entry.getKey().substring( this.attributeName.length() + 1 );
if (modelFlashScopeMap == null)
{
modelFlashScopeMap = new HashMap<String, Object>();
}
modelFlashScopeMap.put( key, entry.getValue() );
iterator.remove();
}
}
if (modelFlashScopeMap != null)
{
MultiScopeModelMap flashScopeMap;
if (request.getAttribute( this.attributeName ) instanceof MultiScopeModelMap)
{
flashScopeMap = (MultiScopeModelMap) request.getAttribute( this.attributeName );
}
else
{
flashScopeMap = new MultiScopeModelMap( this.retentionCount );
}
flashScopeMap.putAll( modelFlashScopeMap );
request.setAttribute( this.attributeName, flashScopeMap );
}
}
}
/**
* binds session flashScope to current session, if not empty. Otherwise cleans up empty
* flashScope
*/
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession( false );
if (session != null)
{
Object sessionAttribute = session.getAttribute( this.sessionAttributeName );
if (sessionAttribute instanceof MultiScopeModelMap)
{
MultiScopeModelMap flashScope = (MultiScopeModelMap) sessionAttribute;
if (flashScope.isEmpty())
{
session.removeAttribute( this.sessionAttributeName );
}
else
{
request.setAttribute( this.attributeName, flashScope );
}
}
}
return true;
}
}
and then MultiScopeModelMap
public class MultiScopeModelMap extends CompositeMap implements Serializable, MapMutator
{
public MultiScopeModelMap(int num)
{
super();
setMutator( this );
for(int i = 0; i < num; ++i)
{
addComposited( new HashMap() );
}
}
/** Shadows composite map. */
private final LinkedList<Map> maps = new LinkedList<Map>();
#Override
public synchronized void addComposited( Map map ) throws IllegalArgumentException
{
super.addComposited( map );
this.maps.addLast( map );
}
#Override
public synchronized Map removeComposited( Map map )
{
Map removed = super.removeComposited( map );
this.maps.remove( map );
return removed;
}
/**
* Starts a new scope.
* All items added in the session before the previous session are removed.
* All items added in the previous scope are still retrievable and removable.
*/
public void next()
{
removeComposited( this.maps.getFirst() );
addComposited( new HashMap() );
}
public Object put( CompositeMap map, Map[] composited, Object key, Object value )
{
if(composited.length < 1)
{
throw new UnsupportedOperationException("No composites to add elements to");
}
Object result = map.get( key );
if(result != null)
{
map.remove( key );
}
composited[composited.length-1].put( key, value );
return result;
}
public void putAll( CompositeMap map, Map[] composited, Map mapToAdd )
{
for(Entry entry: (Set<Entry>)mapToAdd.entrySet())
{
put(map, composited, entry.getKey(), entry.getValue());
}
}
public void resolveCollision( CompositeMap composite, Map existing, Map added, Collection intersect )
{
existing.keySet().removeAll( intersect );
}
#Override
public String toString()
{
return new HashMap(this).toString();
}
}
Now configure it in xml:
<bean id="flashScopeInterceptor" class="com.vanilla.scopes.FlashScopeInterceptor" />
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list><ref bean="flashScopeInterceptor"/></list>
</property>
</bean>
Usage:
#RequestMapping(value="/login.do", method=RequestMethod.POST)
public ModelAndView login(#Valid User user){
ModelAndView mv = new ModelAndView("redirect:result.html");
if (authService.authenticate(user.getUserName(), user.getPassword()))
mv.addObject("flashScope.message", "Success");
//else
mv.addObject("flashScope.message", "Login Failed");
return mv;
}
#RequestMapping(value ="/result.html", method=RequestMethod.GET)
public ModelAndView result(){
ModelAndView mv = new ModelAndView("login/loginAction");
return mv;
}
In JSP the usage is very simple:
${flashScope.message}

Related

Replace OAuth2AccessTokenJackson2Deserializer with my own custom deserializer

This class is deserializing an oauth2 token and I would like to tweak it. I created my own class extending StdDeserializer<OAuth2AccessToken> which at the moment is the same as the original class.
Here is the class:
public class MyCustomDeserializer extends StdDeserializer<OAuth2AccessToken> {
public MyCustomDeserializer() {
super(OAuth2AccessToken.class);
}
#Override
public OAuth2AccessToken deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
JsonProcessingException {
String tokenValue = null;
String tokenType = null;
String refreshToken = null;
Long expiresIn = null;
Set<String> scope = null;
Map<String, Object> additionalInformation = new LinkedHashMap<String, Object>();
// TODO What should occur if a parameter exists twice
while (jp.nextToken() != JsonToken.END_OBJECT) {
String name = jp.getCurrentName();
jp.nextToken();
if (OAuth2AccessToken.ACCESS_TOKEN.equals(name)) {
tokenValue = jp.getText();
}
else if (OAuth2AccessToken.TOKEN_TYPE.equals(name)) {
tokenType = jp.getText();
}
else if (OAuth2AccessToken.REFRESH_TOKEN.equals(name)) {
refreshToken = jp.getText();
}
else if (OAuth2AccessToken.EXPIRES_IN.equals(name)) {
try {
expiresIn = jp.getLongValue();
} catch (JsonParseException e) {
expiresIn = Long.valueOf(jp.getText());
}
}
else if (OAuth2AccessToken.SCOPE.equals(name)) {
scope = parseScope(jp);
} else {
additionalInformation.put(name, jp.readValueAs(Object.class));
}
}
// TODO What should occur if a required parameter (tokenValue or tokenType) is missing?
DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(tokenValue);
accessToken.setTokenType(tokenType);
if (expiresIn != null) {
accessToken.setExpiration(new Date(System.currentTimeMillis() + (expiresIn * 1000)));
}
if (refreshToken != null) {
accessToken.setRefreshToken(new DefaultOAuth2RefreshToken(refreshToken));
}
accessToken.setScope(scope);
accessToken.setAdditionalInformation(additionalInformation);
return accessToken;
}
private Set<String> parseScope(JsonParser jp) throws JsonParseException, IOException {
Set<String> scope;
if (jp.getCurrentToken() == JsonToken.START_ARRAY) {
scope = new TreeSet<String>();
while (jp.nextToken() != JsonToken.END_ARRAY) {
scope.add(jp.getValueAsString());
}
} else {
String text = jp.getText();
scope = OAuth2Utils.parseParameterList(text);
}
return scope;
}
}
Here I am registering the bean:
#Bean
public ObjectMapper configObjectMapper() {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
final SimpleModule module = new SimpleModule("configModule", com.fasterxml.jackson.core.Version.unknownVersion());
module.addDeserializer(OAuth2AccessToken.class, new MyCustomDeserializer());
objectMapper.registerModule(module);
return objectMapper;
}
Testing the above code the flow doesn't reach my class but the original. I am using spring boot 2.1.4

How to send a HTTP response in Zuul PRE_TYPE Filter

I want to prevent not logged user form accessing the proxy. I can throw an exception but the response is 404 instead of `401 or '403'. It it possible?
Filter code:
#Component
public class CustomZuulFilter extends ZuulFilter {
//FIXME - if 401,403 get the new token??, fallbackMethod = "fall",
#HystrixCommand(
commandProperties = {
#HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000"),
#HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")
}
)
#Override
public Object run() {
logger.debug("Adding zulu header");
String userName = getLoggedUser();
RequestContext ctx = RequestContext.getCurrentContext();
if (userName == null) {
// throw new RuntimeException("User not authenticated");
logger.info("User not authenticated");
ctx.setResponseStatusCode(401);
ctx.sendZuulResponse();
return null;
}
return null;
}
private String getLoggedUser() {
[...]
}
#Override
public boolean shouldFilter() {
return true;
}
#Override
public String filterType() {
return PRE_TYPE;
}
#Override
public int filterOrder() {
return PRE_DECORATION_FILTER_ORDER - 1;
}
}
It might be a bit late, but i think you can remove ctx.sendZuulResponse();
and add ctx.setSendZuulResponse(false);

Adding a new field to body of the request from Netflix Zuul Pre-filter

I'm trying to add a new field to request's body, in a Zuul Pre-filter.
I'm using one of the Neflix's Zuul sample projects from here, and my filter's implementation is very similar to UppercaseRequestEntityFilter from this sample.
I was able to apply a transformation such as uppercase, or even to completely modify the request, the only inconvenient is that I'm not able to modify the content of body's request that has a length more than the original length of the body's request.
This is my filter's implementation:
#Component
public class MyRequestEntityFilter extends ZuulFilter {
public String filterType() {
return "pre";
}
public int filterOrder() {
return 10;
}
public boolean shouldFilter() {
RequestContext context = getCurrentContext();
return true;
}
public Object run() {
try {
RequestContext context = getCurrentContext();
InputStream in = (InputStream) context.get("requestEntity");
if (in == null) {
in = context.getRequest().getInputStream();
}
String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
body = body.replaceFirst("qqq", "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq");
// body = body.toUpperCase();
context.set("requestEntity", new ServletInputStreamWrapper(body.getBytes("UTF-8")));
}
catch (IOException e) {
rethrowRuntimeException(e);
}
return null;
}
}
This is the request that I'm doing:
This is the response that I'm receiving:
I was able to obtain what I wanted, using the implementation of PrefixRequestEntityFilter, from sample-zuul-examples:
#Component
public class MyRequestEntityFilter extends ZuulFilter {
public String filterType() {
return "pre";
}
public int filterOrder() {
return 10;
}
public boolean shouldFilter() {
RequestContext context = getCurrentContext();
return true;
}
public Object run() {
try {
RequestContext context = getCurrentContext();
InputStream in = (InputStream) context.get("requestEntity");
if (in == null) {
in = context.getRequest().getInputStream();
}
String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
body = body.replaceFirst("qqq", "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq");
byte[] bytes = body.getBytes("UTF-8");
context.setRequest(new HttpServletRequestWrapper(getCurrentContext().getRequest()) {
#Override
public ServletInputStream getInputStream() throws IOException {
return new ServletInputStreamWrapper(bytes);
}
#Override
public int getContentLength() {
return bytes.length;
}
#Override
public long getContentLengthLong() {
return bytes.length;
}
});
}
catch (IOException e) {
rethrowRuntimeException(e);
}
return null;
}
}

Initial data on JPA repositories

I'm looking for a convenient way to provide initial data for my application. Currently I've implemented a Spring Data JPA based project which is my foundation of all database related operation.
Example:
I've got a entity Role which can be assigned to the entity User. On a clean application start I would like to provide directly some default roles (e.g. admin, manager, etc).
Best
I built a random data factory :
public class RandomDataFactory {
private static final String UNGENERATED_VALUE_MARKER = "UNGENERATED_VALUE_MARKER";
private static void randomlyPopulateFields(Object object) {
new RandomValueFieldPopulator().populate(object);
}
/**
* Instantiates a single object with random data
*/
public static <T> T getSingle(Class<T> clazz) throws IllegalAccessException, InstantiationException {
T object = clazz.newInstance();
randomlyPopulateFields(object);
return object;
}
/**
* Returns an unmodifiable list of specified type objects with random data
*
* #param clazz the myPojo.class to be instantiated with random data
* #param maxLength the length of list to be returned
*/
public static <T> List<T> getList(Class<T> clazz, int maxLength) throws IllegalAccessException, InstantiationException {
List<T> list = new ArrayList<T>(maxLength);
for (int i = 0; i < maxLength; i++) {
T object = clazz.newInstance();
randomlyPopulateFields(object);
list.add(i, object);
}
return Collections.unmodifiableList(list);
}
/**
* Returns a unmodifiable list of specified type T objects with random data
* <p>List length will be 3</p>
*
* #param clazz the myPojo.class to be instantiated with random data
*/
public static <T> List<T> getList(Class<T> clazz) throws InstantiationException, IllegalAccessException {
return getList(clazz, 3);
}
public static <T> T getPrimitive(Class<T> clazz) {
return (T) RandomValueFieldPopulator.generateRandomValue(clazz);
}
public static <T> List<T> getPrimitiveList(Class<T> clazz) {
return getPrimitiveList(clazz, 3);
}
public static <T> List<T> getPrimitiveList(Class<T> clazz, int length) {
List<T> randoms = new ArrayList<T>(length);
for (int i = 0; i < length; i++) {
randoms.add(getPrimitive(clazz));
}
return randoms;
}
private static class RandomValueFieldPopulator {
public static Object generateRandomValue(Class<?> fieldType) {
Random random = new Random();
if (fieldType.equals(String.class)) {
return UUID.randomUUID().toString();
} else if (Date.class.isAssignableFrom(fieldType)) {
return new Date(System.currentTimeMillis() - random.nextInt());
} else if (LocalDate.class.isAssignableFrom(fieldType)) {
Date date = new Date(System.currentTimeMillis() - random.nextInt());
return new LocalDate(date);
} else if (fieldType.equals(Character.class) || fieldType.equals(Character.TYPE)) {
return (char) (random.nextInt(26) + 'a');
} else if (fieldType.equals(Integer.TYPE) || fieldType.equals(Integer.class)) {
return random.nextInt();
} else if (fieldType.equals(Short.TYPE) || fieldType.equals(Short.class)) {
return (short) random.nextInt();
} else if (fieldType.equals(Long.TYPE) || fieldType.equals(Long.class)) {
return random.nextLong();
} else if (fieldType.equals(Float.TYPE) || fieldType.equals(Float.class)) {
return random.nextFloat();
} else if (fieldType.equals(Double.TYPE)) {
return random.nextInt(); //if double is used, jsonPath uses bigdecimal to convert back
} else if (fieldType.equals(Double.class)) {
return random.nextDouble(); //if double is used, jsonPath uses bigdecimal to convert back
} else if (fieldType.equals(Boolean.TYPE) || fieldType.equals(Boolean.class)) {
return random.nextBoolean();
} else if (fieldType.equals(BigDecimal.class)) {
return new BigDecimal(random.nextFloat());
} else if (Enum.class.isAssignableFrom(fieldType)) {
Object[] enumValues = fieldType.getEnumConstants();
return enumValues[random.nextInt(enumValues.length)];
} else if (Number.class.isAssignableFrom(fieldType)) {
return random.nextInt(Byte.MAX_VALUE) + 1;
} else {
return UNGENERATED_VALUE_MARKER;
}
public void populate(Object object) {
ReflectionUtils.doWithFields(object.getClass(), new RandomValueFieldSetterCallback(object));
}
private static class RandomValueFieldSetterCallback implements ReflectionUtils.FieldCallback {
private final Object targetObject;
public RandomValueFieldSetterCallback(Object targetObject) {
this.targetObject = targetObject;
}
#Override
public void doWith(Field field) throws IllegalAccessException {
Class<?> fieldType = field.getType();
if (!Modifier.isFinal(field.getModifiers())) {
Object value = generateRandomValue(fieldType);
if (!value.equals(UNGENERATED_VALUE_MARKER)) {
ReflectionUtils.makeAccessible(field);
field.set(targetObject, value);
}
}
}
}
}
}
Look into an in-memory H2 database.
http://www.h2database.com/html/main.html
Maven Dependency
<!-- H2 Database -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.178</version>
</dependency>
Spring Java Config Entry
#Bean
public DataSource dataSource() {
System.out.println("**** USING H2 DATABASE ****");
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.H2).addScript("/schema.sql").build();
}
You can create/load the H2 database w/ a SQL script in the above code using .addscript().
If you are using it for Unit test, and need a different state for different test, then
There is a http://dbunit.sourceforge.net/
Specifically for Spring there is http://springtestdbunit.github.io/spring-test-dbunit/
If you need to initialize it only once and using EmbeddedDatabaseBuilder for testing, then as Brandon said, you can use EmbeddedDatabaseBuilder.
#Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.H2).addScript("/schema.sql").build();
}
If you want it to be initialised on application start, you can add #PostConstruct function to your Configuration bean, and it will be initialised after configuration bean was created.
#PostConstruct
public void initializeDB() {
}

HttpSession attribute getting removed abnormally after adding

*After I add a session attribute using
WebUtils.setSessionAttribute(request, VBWebConstants.SESSION_ORDER_BEAN,sellerDetails);
#RequestMapping(value="/minasidor/step1",method=RequestMethod.GET)
public ModelAndView step1(HttpServletRequest request,HttpSession session){
if(logger.isTraceEnabled())logger.trace("VbSellerController ::: step1 ::: start");
if(logger.isDebugEnabled())logger.debug("[Order Step1] [Start]");
ModelAndView mav=new ModelAndView("vz-new/mina-sidor/v-orderstep1");
LoginBean user = (LoginBean) WebUtils.getSessionAttribute(request, VBWebConstants.SESSION_USER);
mav.addObject("submenu",3);
if(!checkOrderLifeCycle()){
mav.addObject("orderNotAllowed", false);
return mav;
}
try{
String orderValue = "";
orderValue = InMemoryCache.getCaProperty(PropertyEnum.MIN_ORDER_VALUE.getDatabasekey());
int minimumOrderValue = CawebUtil.isInt(orderValue);
CpSellerDetails sellerDetails=vbOrderService.getStep1Data(user.getGrp_seller_id(),user.getCatalogue_id());
if(sellerDetails != null){
mav.addObject("productlist",sellerDetails.getSellerList());
mav.addObject("totalValue",sellerDetails.getTotalOrderValue());
mav.addObject("allowedfororder",sellerDetails.getTotalOrderValue() > minimumOrderValue);
// mav addobject add discount details Discount Object ArrayList
WebUtils.setSessionAttribute(request, VBWebConstants.SESSION_ORDER_STEP_COMPLETED,"step1");
WebUtils.setSessionAttribute(request, VBWebConstants.SESSION_ORDER_BEAN,sellerDetails);
}else{
mav.addObject("allowedfororder",false);
WebUtils.setSessionAttribute(request, VBWebConstants.SESSION_ORDER_STEP_COMPLETED,null);
}
}catch(DataNotFoundException e){
logger.trace("Exception in retrieving data for step1",e);
if(logger.isDebugEnabled())logger.debug("[Order Step1 Exception]",e);
}
if(logger.isTraceEnabled())logger.trace("VbSellerController ::: step1 ::: end");
if(logger.isDebugEnabled())logger.debug("[Order Step1] [end]");
return mav;
}
Within this step1 method the VBWebConstants.SESSION_ORDER_BEAN session attribute is getting removed instantly after the step1() method finishes executing where as the other session attributes remains the same.When i debug the below Http Listener class
public class MyHttpSessionListener implements HttpSessionListener,HttpSessionAttributeListener {
public static final Logger logger = Logger.getLogger(MyHttpSessionListener.class);
public void sessionCreated(HttpSessionEvent se) {
//String ipAddr = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest().getRemoteAddr();
HttpSession session = se.getSession();
if(logger.isDebugEnabled()){
StringBuilder sbuilder = new StringBuilder();
sbuilder.append("\n").append("----------- Session Created -------------- ");
Enumeration<String> sessionAttrs = session.getAttributeNames();
while (sessionAttrs.hasMoreElements()) {
String name = sessionAttrs.nextElement();
sbuilder.append("\n").append(" session created ").append(name);
}
sbuilder.append("\n").append(" session created time "+ CawebUtil.getTimeStampInString(new Timestamp(session.getCreationTime())));
sbuilder.append("\n").append("---------------------------------------------------- ").append("\n");
logger.debug(sbuilder.toString());
}
}
public void sessionDestroyed(HttpSessionEvent se) {
HttpSession session = se.getSession();
if(logger.isDebugEnabled()){
try{
String ipAddr = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest().getRemoteAddr();
logger.debug(" session destroyed " +ipAddr);
}catch (Exception e) {
}
}
}
public void attributeAdded(HttpSessionBindingEvent se) {
String ipAddr = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest().getRemoteAddr();
HttpSession session = se.getSession();
if(logger.isDebugEnabled()){
StringBuilder sbuilder = new StringBuilder();
sbuilder.append("\n").append("----------- Attribute added -------------- from ").append(ipAddr);
sbuilder.append("\n").append(" session max inactive time "+ session.getMaxInactiveInterval());
sbuilder.append("\n").append(" session id "+ session.getId());
sbuilder.append("\n").append(" session attribute added "+ se.getName()).append(" = ").append(se.getValue());
sbuilder.append("\n").append(" session created time "+ CawebUtil.getTimeStampInString(new Timestamp(session.getCreationTime())));
}
}
public void attributeRemoved(HttpSessionBindingEvent se) {
if(logger.isDebugEnabled() ){
StringBuilder sbuilder = new StringBuilder();
sbuilder.append("\n").append("----------- Attribute removed -------------- from ");//.append(ipAddr);
sbuilder.append("\n").append(" session attribute removed "+ se.getName()).append(" = ").append(se.getValue());
}
}
public void attributeReplaced(HttpSessionBindingEvent se) {
if(logger.isDebugEnabled()){
StringBuilder sbuilder = new StringBuilder();
sbuilder.append("\n").append("----------- Attribute replaced -------------- from ");//.append(ipAddr);
sbuilder.append("\n").append(" session attribute "+ se.getName()).append(" = ").append(se.getValue());
}
}
}
I found that the session attribute is getting removed.Checked through the entire code I couldn't find what's the reason...???
Here is the CPSellerDetails class which i try to add to the session there are other 2 session attributes among which one is a string object and other is a bean.could it the size of the class that is the cause for session attribute being removed abnormally
public class CpSellerDetails implements Serializable{
/**
*
*/
private static final long serialVersionUID = -4627284179051380310L;
private List<SellerProduct> sellerList ;
private float totalOrderValue ;
private VbCpInfoBean cpinfoBean;
private Integer orderno;
private float invoiceAmount;
private Date orderedDate;
private ArrayList<DiscountVO> discounts;
private Address billingInfo;
public VbCpInfoBean getCpInfoBean() {
return cpinfoBean;
}
public void setCpInfoBean(VbCpInfoBean infoBean) {
this.cpinfoBean = infoBean;
}
public List<SellerProduct> getSellerList() {
return sellerList;
}
public void setSellerList(List<SellerProduct> sellerList) {
this.sellerList = sellerList;
}
public float getTotalOrderValue() {
return totalOrderValue;
}
public void setTotalOrderValue(float totalOrderValue) {
this.totalOrderValue = totalOrderValue;
}
public float getInvoiceAmount() {
return invoiceAmount;
}
public void setInvoiceAmount(float invoiceAmount) {
this.invoiceAmount = invoiceAmount;
}
public Integer getOrderno() {
return orderno;
}
public void setOrderno(Integer orderno) {
this.orderno = orderno;
}
public Date getOrderedDate() {
return orderedDate;
}
public void setOrderedDate(Date orderedDate) {
this.orderedDate = orderedDate;
}
public ArrayList<DiscountVO> getDiscounts() {
return discounts;
}
public void setDiscounts(ArrayList<DiscountVO> discounts) {
this.discounts = discounts;
}
public Address getBillingInfo() {
return billingInfo;
}
public void setBillingInfo(Address billingInfo) {
this.billingInfo = billingInfo;
}
}*

Resources