0

I want to set a session value when running the main application. I tried the following way:

@SpringBootApplication
public class WebApplication extends SpringBootServletInitializer {

@Autowired
public HttpServletRequest request;

@Autowired
private CountryService countryService;

private static Class<WebApplication> applicationClass = WebApplication.class;

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(applicationClass);
}

public void set_session_country(){
    request.getSession().setAttribute("session_countries", countryService.getAllCountry());
}

public static void main(String[] args) {
    WebApplication webApplication = new WebApplication();
    webApplication.set_session_country();
    SpringApplication.run(WebApplication.class, args);
}

}

when running application, occurred NullPointerException

Exception in thread "main" java.lang.NullPointerException at com.paid.webapp.WebApplication.set_session_country at com.paid.webapp.WebApplication.main

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Nur Hossen
  • 31
  • 8
  • can you include a bit more of the stacktrace? the npe is probably originated from countryService – Michael Michailidis Mar 06 '20 at 10:32
  • @coroutineDispatcher , Bro it't not. It's a different question – Nur Hossen Mar 06 '20 at 10:35
  • @MichaelMichailidis, Bro countryService return list of country – Nur Hossen Mar 06 '20 at 10:36
  • well it has to be wired to return it. Is it wired? can you provide a bit more of your stacktrace and how the countryService is setup ? Asking about npe looks like you are learning about dependency injection of spring so you may have done that part wrong – Michael Michailidis Mar 06 '20 at 10:41
  • @MichaelMichailidis, okey I use this `request.getSession().setAttribute("session_countries", "hello");` there not use any dependency, just a String,,, but same execption occourred. – Nur Hossen Mar 06 '20 at 10:50
  • Have a look at this. https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors . NPE shows in the stacktrace ( Which i am asking and you are not providing ) the exact line that they were produced. – Michael Michailidis Mar 06 '20 at 10:51
  • @talex, Dear are you understand my question ??? – Nur Hossen Mar 06 '20 at 10:52
  • @NurHossen you didn't asked any question, so I had to guess. – talex Mar 07 '20 at 08:10
  • Unfortunately the question has been closed... the real answer: you start the application as a regular java application (“main” thread visible in the exception) and try to access the httpservlet request without having an http request. Therefore you get an NPE. I recommend that you try to understand the fundamental model of spring boot AND how servlets work before further experiments. – Thomas Mar 07 '20 at 08:53

0 Answers0