Rectangle 27 6

I don't think there is way to do what you are asking for, because in the exception handler method unhandledExceptionHandler there is no way to find out what the name of the view that the handler method somemethod would have returned.

The only way is for you to introduce some sort of meta data scheme so that when you end up in the exception handler you can figure out what view to map it to. But I think this meta data scheme would be fairly complex. You can implement such a scheme by finding out what was the original url being accessed when the exception was thrown, this can be done with the code snippet below.

(ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()

Once you know what the original request URL you can redirect to it, maybe using flash attribute to store the fact that there was an exception and what the error is.

The main problem wit the metadata will occur when you have a handler method that select between different views something like.

@RequestMapping(value = "/somepage", method = RequestMethod.GET)
public String somemethod(HttpSession session) throws Exception {
    String abc = null;
    if(someCondition) {
        abc.length();
        return "someview";
    } else {
        // do some stuff here.
        return "someOtherView";
    }
}

Even knowing that somemethod was the source of the error leaves you not knowing which branch in the if statement caused the exception.

Thanks. I guess I'll just have to redirect to a error page for now. I'll just leave this question open for few days. if still no response I'll just accept it as an answer..

java - spring mvc @ExceptionHandler method get same view - Stack Overf...

java spring spring-mvc exceptionhandler
Rectangle 27 4

I dont think you can do this without modifying all of your handler methods. However you can try to do this in a "pretty" way:

1) You can define your own annotation which will accept target view name as a parameter (e.g. @ExceptionView)

@ExceptionView("someview")
@RequestMapping(value = "/somepage", method = RequestMethod.GET)
    public String somemethod(HttpSession session) throws Exception {
    String abc = null;
    abc.length();
    return "someview";
}

3) After that you can do something like this in exception handler:

@ExceptionHandler(Exception.class)
protected ModelAndView unhandledExceptionHandler(Exception ex, HandlerMethod hm) {
    String targetView;
    if (hm != null && hm.hasMethodAnnotation(ExceptionView.class)) {
        targetView = hm.getMethodAnnotation(ExceptionView.class).getValue();
    } else {
        targetView = "someRedirectView"; // kind of a fallback
    }
    ModelAndView mv = new ModelAndView();
    mv.setViewName(targetView);
    mv.addObject("UNHANDLED_ERROR", "UNHANDLED ERROR. PLEASE CONTACT SUPPORT. "+ex.getMessage());
    return mv;
}

java - spring mvc @ExceptionHandler method get same view - Stack Overf...

java spring spring-mvc exceptionhandler
Rectangle 27 2

Rather than sending the error on a separate page, you can you just put the error in the ModelAndView object. In your case you can just put the try/catch in your controller method and return the same view like so:

@RequestMapping(value = "/somepage", method = RequestMethod.GET)
public String somemethod(ModelAndView mv,HttpSession session) throws Exception {
   mv.setViewName("someview");
   try{ 
      String abc = null;
      abc.length();
    } catch(Exception e) {
      mv.addObject("UNHANDLED_ERROR", "UNHANDLED ERROR. PLEASE CONTACT SUPPORT.  "+ex.getMessage());
   }
   return mv;
}

java - spring mvc @ExceptionHandler method get same view - Stack Overf...

java spring spring-mvc exceptionhandler
Rectangle 27 1

I have not tried this out, but based on the documentation here, we can get the request object in the exception handler. We may not be able to get the view linked to the URL. Getting the view from the URL, and the state/model of the view will be the tricky part.

@ExceptionHandler(Exception.class)
  public ModelAndView handleError(HttpServletRequest req, Exception ex) {
    logger.error("Request: " + req.getRequestURL() + " raised " + ex);

    ModelAndView mav = new ModelAndView();
    mav.addObject("exception", ex);
    mav.addObject("url", req.getRequestURL());
    mav.setViewName("error");
    return mav;
  }

java - spring mvc @ExceptionHandler method get same view - Stack Overf...

java spring spring-mvc exceptionhandler
Rectangle 27 2

My suggestions is not to look at view framework as described in most of the above which was not written on top of spring MVC since you will end up in issues like postbacks which means you won't be able to submit the data from this view technology and get back the response from sever. example like validation , edit data submission which refreshes back with data from server WILL NOT WORK .

This is because java beans in some above of view technology don't use Spring container lifecycle. You will only be able to use them for pure view example stateless request. example with JSF you won't be able to use postbacks since jsf postbacks only work if you use jsf life cycle and if you use spring framework JSF view resolver with spring mvc you won't be able to do postback so you need to replace jsf servlet controller instead of spring mvc controller .

Again since your full project requirement is not clear and if you want no postback requirement you can use some of above choices .

one example view technology which is written on top og spring mvc is zk framework based zk mvc in which you can extend your spring mvc controllers from ZK GenericForwardComposer to handle events. You can always use Spring to handle the lifecycle of these controllers using Spring framework.

you can google to find similiar other products .

This review is based on high level design of framework life cycle.

java - Alternatives to JSP for Spring MVC view layer - Stack Overflow

java jsp spring-mvc
Rectangle 27 2

I would recommend to look into plain Spring configuration first to get a feel of how fundamental things (like injection) work. If you manage to get a hang of it in Spring, the process will be very similar in Spring MVC/Spring Boot/etc. Personally, I find it very frustrating trying to juggle multiple concepts (view resolvers, different configuration files, views, repositories, multiple annotations, multiple ways of configuration, etc.) at once, so I tend to start from the simplest concepts and build my way up. Once you are comfortable with how injection works, you can easily apply this knowledge elsewhere.

As for java config and annotations, they do allow for much quicker and cleaner development. XML is quite verbose, hard to maintain and is very prone to errors, in part because IDEs are generally more helpful when working with java based configuration. Perhaps that is why you read that XML is being deprecated. I would recommend to go for java/auto configuration rather than XML one, unless you really need to (or are interested in it).

/* Bean definition

@Component tells Spring that this is a bean. There are a few similar annotations.
It will be discovered during the component scan, as it has @Component annotation */

package main.java.org.example;
import org.springframework.stereotype.Component;

@Component 
public class Greeting {
    private String greeting = "Hello";

    public String getGreeting() {
        return this.greeting;
    }

    public void setGreeting(String greeting) {
        this.greeting = greeting;
    }
}


/* Another bean definition.
It has another bean as a dependency, which we inject with a setter. */

package main.java.org.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class GreetingCollector {
    private Greeting greeting;

    /* This is how you do setter injection */
    @Autowired
    public void setGreeting(Greeting greeting) {
        this.greeting = greeting;
    }

    public String getGreeting() {
        return greeting.getGreeting();
    }
}


/* This is a minimal config class. 
@ComponentScan instructs to look for classes that are 
annotated with @Component annotation (in other words, beans) */

package main.java.org.example;    
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan
@Configuration
public class Config {}

If you want to do it explicitly:

package main.java.org.example;  
import main.java.org.example.GreetingCollector;
import main.java.org.example.Greeting;  
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {
    @Bean
    public Greeting greeting() {
        return new Greeting();
    }

    @Bean
    public GreetingCollector greetingCollector(Greeting greeting) {
        return new GreetingCollector(greeting);
    }
}

And if you want to run it just to see how it works:

import main.java.org.example.Config;
import main.java.org.example.GreetingCollector;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AppContext {
    public static void main(String args[]) {
        System.out.println("Configuring application context...");
        ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        GreetingCollector collector = (GreetingCollector) context.getBean("greetingCollector");
        System.out.println(collector.getGreeting());
    }
}

Naturally, Spring web application would be a bit different, but the basic injection idea is the same. First, you need to declare beans (either by using @Bean, @Component or any other annotation: see here and here for differences). You annotate either a setter or constructor (or even a field) with @Autowired, specify parameters (which do not necessarily need to be concrete classes - interfaces, abstract classes are fine, too), assign them to appropriate fields. Create a config class which takes cares of bean instantiation. You do not need to have your components in the same folder as config classes, as you can always specify where to look for components. Finally, if you want a more fine grained control, you can always declare beans explicitly in configuration class (so called JavaConfig, whereas @ComponentScan based config might sometimes be called autoconfig). This should be enough to get you started and give you vocabulary to search for more advanced stuff.

And of course, with Spring Boot everything is even more abstracted away/quicker.

xml - How do I use setter injection with java configuration in Spring?...

java xml spring dependency-injection
Rectangle 27 2

I would recommend to look into plain Spring configuration first to get a feel of how fundamental things (like injection) work. If you manage to get a hang of it in Spring, the process will be very similar in Spring MVC/Spring Boot/etc. Personally, I find it very frustrating trying to juggle multiple concepts (view resolvers, different configuration files, views, repositories, multiple annotations, multiple ways of configuration, etc.) at once, so I tend to start from the simplest concepts and build my way up. Once you are comfortable with how injection works, you can easily apply this knowledge elsewhere.

As for java config and annotations, they do allow for much quicker and cleaner development. XML is quite verbose, hard to maintain and is very prone to errors, in part because IDEs are generally more helpful when working with java based configuration. Perhaps that is why you read that XML is being deprecated. I would recommend to go for java/auto configuration rather than XML one, unless you really need to (or are interested in it).

/* Bean definition

@Component tells Spring that this is a bean. There are a few similar annotations.
It will be discovered during the component scan, as it has @Component annotation */

package main.java.org.example;
import org.springframework.stereotype.Component;

@Component 
public class Greeting {
    private String greeting = "Hello";

    public String getGreeting() {
        return this.greeting;
    }

    public void setGreeting(String greeting) {
        this.greeting = greeting;
    }
}


/* Another bean definition.
It has another bean as a dependency, which we inject with a setter. */

package main.java.org.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class GreetingCollector {
    private Greeting greeting;

    /* This is how you do setter injection */
    @Autowired
    public void setGreeting(Greeting greeting) {
        this.greeting = greeting;
    }

    public String getGreeting() {
        return greeting.getGreeting();
    }
}


/* This is a minimal config class. 
@ComponentScan instructs to look for classes that are 
annotated with @Component annotation (in other words, beans) */

package main.java.org.example;    
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan
@Configuration
public class Config {}

If you want to do it explicitly:

package main.java.org.example;  
import main.java.org.example.GreetingCollector;
import main.java.org.example.Greeting;  
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {
    @Bean
    public Greeting greeting() {
        return new Greeting();
    }

    @Bean
    public GreetingCollector greetingCollector(Greeting greeting) {
        return new GreetingCollector(greeting);
    }
}

And if you want to run it just to see how it works:

import main.java.org.example.Config;
import main.java.org.example.GreetingCollector;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AppContext {
    public static void main(String args[]) {
        System.out.println("Configuring application context...");
        ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        GreetingCollector collector = (GreetingCollector) context.getBean("greetingCollector");
        System.out.println(collector.getGreeting());
    }
}

Naturally, Spring web application would be a bit different, but the basic injection idea is the same. First, you need to declare beans (either by using @Bean, @Component or any other annotation: see here and here for differences). You annotate either a setter or constructor (or even a field) with @Autowired, specify parameters (which do not necessarily need to be concrete classes - interfaces, abstract classes are fine, too), assign them to appropriate fields. Create a config class which takes cares of bean instantiation. You do not need to have your components in the same folder as config classes, as you can always specify where to look for components. Finally, if you want a more fine grained control, you can always declare beans explicitly in configuration class (so called JavaConfig, whereas @ComponentScan based config might sometimes be called autoconfig). This should be enough to get you started and give you vocabulary to search for more advanced stuff.

And of course, with Spring Boot everything is even more abstracted away/quicker.

xml - How do I use setter injection with java configuration in Spring?...

java xml spring dependency-injection
Rectangle 27 2

Maybe you could try Vaadin together with Grails. Grails gives you clear division between database, services and view layer (+ you will get Spring IoC for free). If you want to give it a try, follow this one.

  • as view, create UI with components from Vaadin
  • you could also use State pattern for implementation of different states of UI screens
  • and use Listener pattern for action

The second option without Grails is pure Java, but it is also more painful.

Thanks, how about using only Spring IOC and just separete my view and logic and data classes, no DAO or listener pattern

Actually, I think that is too heavy weapon for that kind of stuff. I prefer simple and easy to understand solutions (and if possible, no XML configurations...). So I think that Vaadin+Grails might be nice option for you. But it depends on what are you technology constraints...

java - Vaadin:A suitable Design Pattern - Stack Overflow

java spring design-patterns java-ee vaadin
Rectangle 27 3

I'd say that JSF fills most of the part of the controller. There are other libraries that are compatible with JSF though. For example, you can use Spring WebFlow together with JSF to get more powerful navigation features.

JSF is not very intrusive when it comes to the model. Ideally, there aren't any traces that you are using JSF in your domain model (the exception is that JSF provides annotations that you can optionally use, such as @ManagedBean). This means you are free to use any libraries you want. You can use Spring IOC or EJB if you want to, or you can code your entire model in plain old java objects.

That being said, I should like to emphasize that JSP is not obsolete. As digitaljoel points out, Facelets have replaced JSP as the view technology in JSF, but JSP is still alive and healthy in other frameworks. There is not an agreement that JSF including Facelets are "better" than JSP (together with another web framework); and JSF has not become an industry standard.

Writing a web application using JSF is closer to writing a desktop application, since they have abstracted away much of the request-response handling. There is not a specific method being invoked each time a client does a request, instead each request passes through a lifecycle of which you are not fully in control. Interacting directly with the HttpServletRequest is discouraged.

Ignoring the request-response nature of the web increases the complexity of a request and conflicts with another growing trend: rich web applications that heavily relies on Javascript. The responsibility of the view logic is moved from the server to the browser, which interacts with the server using Ajax against thin HTTP APIs.

The point is that JSF is not the end-all framework that you need to learn and ignore everything else. It can be the correct choice for some applications, but not for all.

Thanks waxwing! My intended application actually would be heavy in JS and AJAX. Can you recommend any Java frameworks that - unlike JSF - work well with JS/AJAX? I mean, is using pure Servlets a possibility here, or is that taboo?

Great answer waxwing, you make some excellent points. One clarification on JSF vs. JSP. Using JSP as the view technology for JSF is discouraged at best. Using JSP with another framework, like Spring MVC is alive and well IMO. As for JS/AJAX, one reason I left JSF for Spring MVC is the ease of JS/AJAX in Spring MVC vs. JSF, even with the JSF 2.0 ajax enhancements.

So.... I'm assuming then that Spring has a web tier for MVC web applications? If so, that might be my best bet. For some reason I always thought Spring was pure client-side.

@digitaljoel: Thanks. I hope you don't mind that I tried, somewhat clumsily, to work that clarification into the answer.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

java - Available JSF MVC components - Stack Overflow

java jsf web-applications java-ee
Rectangle 27 0

thought about that one, and wondered if it can be avoided ;-) But, this might be the simplest way of handling it.

Then maybe you may want to implement a HandlerInterceptorAdapter. I think this question may help you: stackoverflow.com/questions/8384903/. Once you get the name of the controller and the method name, you can add them to the model in the postHandle method.

java - Get name of Spring controller and method in view - Stack Overfl...

java spring jsp spring-mvc
Rectangle 27 0

if you want to all upperTyrePropertyCodeList back to you submit action,you can do like this:

<c:forEach var="index" items="${upperTyrePropertyCodeList}">    
  <form:hidden name="propertyCode" value="${index.propertyCode}"/>
</c:forEach>

select box only hold the selected value to controller.

java - How to get all the item of a jstl select in MVC Spring controll...

java html spring spring-mvc jstl
Rectangle 27 0

If your condition is not satisfied, it will go to the else block. so the model will never be instantiated. Declare the instantiation of the model object outside the if block

mv = new ModelAndView("searchResults");
    List<GridMappingVO> searchList= gridMappingFacade.validate(gridMappingVO);
    if( users.equals(searchList.get(0).getUser()) 
    && passwrd.equals(searchList.get(0).getPass()) ) {
    System.out.println("validation succesfull"); 
    logger.info("Response is: " + mv);
    mv.addObject("searchList", searchList);
} else {
    List<String> list = new ArrayList<String>();
    list.add("Invalid");
    map.put("error_messages", list);
    mv.addAllObjects(map);
}
return mv;

You can also do it this way, instantiate a hashmap at the start of the method like:

Map model = new HashMap();

and add the objects to the model.

model.put("searchList", searchList);

while returning create a new ModelAndView object

return new ModelAndView("jsp/searchResults", model)

are you getting the same error?

Check the jsp path passing in the ModelAndView object, it should be the same path in your webapp. Also you need to add the view resolver in the dispatcher servlet

am not getting any error not even before..it just that searchResults.jsp page is not getting displayed

java - Unable to get the view from controller in spring mvc - Stack Ov...

java spring java-ee spring-mvc
Rectangle 27 0

I think the error is generated from '/Registration.htm' you are requesting to give you a .htm file while in your configuration you have set it to .jsp file that's why is returning the error HTTP Status 404 - /SpringMVCBaselineDynamic/WEB-INF/jsp/Registration.jsp because the viewresolver is trying convert anything after the dot in your request mapping value to jsp.

You should try changing it to:

@RequestMapping(value = {"/Registration"}, method = {RequestMethod.GET})

I think that should work since your configuration is all working.

java - Spring - Unable to get the view name set in ModelAndView - Stac...

java spring jsp spring-mvc web
Rectangle 27 0

I ended up using Spring Security. It seems with Java EE 6 libraries, it is not easily possible to implement a custom authentication provider. Of course you can implement everything from scratch using servlet filters, but that's in my view too error prone. Spring Security seems to be a good solution even though it adds many libraries to my webapp, which I hoped I could get around without.

servlets - Form-based authentication, but with custom authentication m...

java-ee servlets java-ee-6 web.xml jaas
Rectangle 27 0

Please change any one of place . Don't change in two places.

protected ModelAndView onSubmit(HttpServletRequest request,
      HttpServletResponse response, Object command) throws Exception {

      ScheduleClass wiziqClass = (ScheduleClass) command;
      System.out.println(wiziqClass);
      return new ModelAndView("classdetail", "wiziqClass", wiziqClass);
}
${ScheduleClass.name}
<form:form method="POST" commandName="scheduleClass">
return new ModelAndView("index");

java - Unable to get value in view after form post in Spring mvc - Sta...

java spring spring-mvc
Rectangle 27 0

@RequestMethod("/server-error")
@ExceptionHandler
return "forward:/server-error";

java - spring mvc @ExceptionHandler method get same view - Stack Overf...

java spring spring-mvc exceptionhandler
Rectangle 27 0

onSubmit
onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,BindException errors)

java - Unable to get value in view after form post in Spring mvc - Sta...

java spring spring-mvc
Rectangle 27 0

I don't think there is way to do what you are asking for, because in the exception handler method unhandledExceptionHandler there is no way to find out what the name of the view that the handler method somemethod would have returned.

The only way is for you to introduce some sort of meta data scheme so that when you end up in the exception handler you can figure out what view to map it to. But I think this meta data scheme would be fairly complex. You can implement such a scheme by finding out what was the original url being accessed when the exception was thrown, this can be done with the code snippet below.

(ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()

Once you know what the original request URL you can redirect to it, maybe using flash attribute to store the fact that there was an exception and what the error is.

The main problem wit the metadata will occur when you have a handler method that select between different views something like.

@RequestMapping(value = "/somepage", method = RequestMethod.GET)
public String somemethod(HttpSession session) throws Exception {
    String abc = null;
    if(someCondition) {
        abc.length();
        return "someview";
    } else {
        // do some stuff here.
        return "someOtherView";
    }
}

Even knowing that somemethod was the source of the error leaves you not knowing which branch in the if statement caused the exception.

Thanks. I guess I'll just have to redirect to a error page for now. I'll just leave this question open for few days. if still no response I'll just accept it as an answer..

java - spring mvc @ExceptionHandler method get same view - Stack Overf...

java spring spring-mvc exceptionhandler
Rectangle 27 0

I ended up using Spring Security. It seems with Java EE 6 libraries, it is not easily possible to implement a custom authentication provider. Of course you can implement everything from scratch using servlet filters, but that's in my view too error prone. Spring Security seems to be a good solution even though it adds many libraries to my webapp, which I hoped I could get around without.

servlets - Form-based authentication, but with custom authentication m...

java-ee servlets java-ee-6 web.xml jaas
Rectangle 27 0

Thanks guys for helping .. I already know the problem..

the ModelAndView I used is in portlet component.. it should be servlet ..

java - Spring - Unable to get the view name set in ModelAndView - Stac...

java spring jsp spring-mvc web