Null Pointer Exception when autowiring beans - java

I'm making a simple project for school but I'm stuck.
I have a bean FavoriteService that I need to address. However when autowiring the bean in my servlet I keep getting a Null Pointer Exception and I can't figure out why.
FavoriteService
public class FavoriteService {
#Autowired
private Users users;
public boolean checkLogin(String username, String password) {
return users.login(username, password);
}
public void addUser(String rootUsername, String rootPassword, String username, String password)
{
if(rootUsername.equals("root") && rootPassword.equals("rootpasswd")) users.addUser(username, password);
}
public List<String> getFavorites(String username, String password)
{
List<String> favorites;
if(checkLogin(username, password))
{
favorites = users.getFavorites(username);
} else {
favorites = new ArrayList<String>();
}
return favorites;
}
public void addFavorite(String username, String password, String favorite)
{
if(checkLogin(username, password))
{
users.addFavorite(username, favorite);
}
}
public void removeFavorite(String username, String password, String favorite)
{
if(checkLogin(username, password))
{
users.removeFavorite(username, favorite);
}
}
}
Servlet
public class LoginServlet extends HttpServlet {
#Autowired
private FavoriteService favoriteService;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(favoriteService);
if(favoriteService.checkLogin(username, password))
{
resp.sendRedirect("root.jsp");
} else {
resp.sendRedirect("index.jsp");
}
}
}
springservlet-servlet
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="be.kdg.prog4.tdd"/>
<bean name="userDao" class="be.kdg.prog4.tdd.UserDaoWithMap" scope="singleton" />
<bean name="users" class="be.kdg.prog4.tdd.Users" scope="singleton" />
<bean name="favoriteService" class="be.kdg.prog4.tdd.FavoriteService" scope="singleton" />
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".*"/>
</bean>
</beans>
Web.xml
<web-app schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>TDD oefening</display-name>
<servlet>
<servlet-name>springservlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springservlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>be.kdg.prog4.tdd.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
If you need any more info feel free to ask.
Thanks.
EDIT:
I solved it by doing this in the servlet init
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
}

If you are calling LoginServlet you are not going through Spring. You mapped it directly in your web.xml and your set let container is initializing your class without going through Spring and the autowired does not work. You need the access the server through a mapping of springservlet.

The Servlet is not initialized by Spring and therefore the #Autowired fields are not getting initialized by Spring.
Instead of using #Autowired you can override the Servlet init() method and get the Spring web context and use its getBean method to get your bean.
This is how you can get the Spring context in your init method:
ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

Related

SEVERE: Servlet.init() call for Servlet [appServlet] caused an exception

While implementing CRUD with a spring, this error occurred and has not been able to proceed with CRUD for several hours...
"Line 7 of the xml document of the servlet context resource [/web-inf/spring/appservlet/slaplet-slap.xml] is invalid."
Even if line 7 is erased, line 6 is an error and line 5 is an error if erased once again, so I don't think this is an empty tag problem.
Just in case, I'll put the controller and dao.
I'm worried that it'll be uncomfortable to watch. sorry..
help me!!
Controller
#Controller
#RequestMapping("/article")
public class ArticleController {
private static final Logger logger = LoggerFactory.getLogger(ArticleController.class);
private final ArticleService articleService;
#Inject
public ArticleController(ArticleService articleService) {
this.articleService = articleService;
}
#RequestMapping(value = "/write", method = RequestMethod.GET)
public String writeGET() {
logger.info("write GET...");
return "/article/write";
}
#RequestMapping(value = "/write", method = RequestMethod.POST)
public String writePOST(ArticleVO articleVO, RedirectAttributes redirectAttributes) throws Exception {
logger.info("writePOST...");
logger.info(articleVO.toString());
articleService.create(articleVO);
;
redirectAttributes.addFlashAttribute("msg", "regSuccess");
return "redirect:/article/list";
}
#RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(Model model) throws Exception {
logger.info("list ...");
model.addAttribute("articles", articleService.listAll());
return "/article/list";
}
#RequestMapping(value = "/read", method = RequestMethod.GET)
public String read(#RequestParam("article_no") int article_no, Model model) throws Exception {
logger.info("read ...");
model.addAttribute("article", articleService.read(article_no));
return "/article/read";
}
#RequestMapping(value = "/modify", method = RequestMethod.GET)
public String modifyGET(#RequestParam("article_no") int article_no, Model model) throws Exception {
logger.info("modifyGet ...");
model.addAttribute("article", articleService.read(article_no));
return "/article/modify";
}
#RequestMapping(value = "/modify", method = RequestMethod.POST)
public String modifyPOST(ArticleVO articleVO, RedirectAttributes redirectAttributes) throws Exception {
logger.info("modifyPOST ...");
articleService.update(articleVO);
redirectAttributes.addFlashAttribute("msg", "modSuccess");
return "redirect:/article/list";
}
#RequestMapping(value = "/remove", method = RequestMethod.POST)
public String remove(#RequestParam("article_no") int article_no, RedirectAttributes redirectAttributes)
throws Exception {
logger.info("remove ...");
articleService.delete(article_no);
redirectAttributes.addFlashAttribute("msg", "delSuccess");
return "redirect:/article/list";
}
}
DAO
#Controller
#RequestMapping("/article")
public class ArticleController {
private static final Logger logger = LoggerFactory.getLogger(ArticleController.class);
private final ArticleService articleService;
#Inject
public ArticleController(ArticleService articleService) {
this.articleService = articleService;
#RequestMapping(value = "/write", method = RequestMethod.GET)
public String writeGET() {
logger.info("write GET...");
return "/article/write";
}
#RequestMapping(value = "/write", method = RequestMethod.POST)
public String writePOST(ArticleVO articleVO, RedirectAttributes redirectAttributes) throws Exception {
logger.info("writePOST...");
logger.info(articleVO.toString());
articleService.create(articleVO);
;
redirectAttributes.addFlashAttribute("msg", "regSuccess");
return "redirect:/article/list";
}
#RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(Model model) throws Exception {
logger.info("list ...");
model.addAttribute("articles", articleService.listAll());
return "/article/list";
}
#RequestMapping(value = "/read", method = RequestMethod.GET)
public String read(#RequestParam("article_no") int article_no, Model model) throws Exception {
logger.info("read ...");
model.addAttribute("article", articleService.read(article_no));
return "/article/read";
}
#RequestMapping(value = "/modify", method = RequestMethod.GET)
public String modifyGET(#RequestParam("article_no") int article_no, Model model) throws Exception {
logger.info("modifyGet ...");
model.addAttribute("article", articleService.read(article_no));
return "/article/modify";
}
#RequestMapping(value = "/modify", method = RequestMethod.POST)
public String modifyPOST(ArticleVO articleVO, RedirectAttributes redirectAttributes) throws Exception {
logger.info("modifyPOST ...");
articleService.update(articleVO);
redirectAttributes.addFlashAttribute("msg", "modSuccess");
return "redirect:/article/list";
}
#RequestMapping(value = "/remove", method = RequestMethod.POST)
public String remove(#RequestParam("article_no") int article_no, RedirectAttributes redirectAttributes)
throws Exception {
logger.info("remove ...");
articleService.delete(article_no);
redirectAttributes.addFlashAttribute("msg", "delSuccess");
return "redirect:/article/list";
}
}
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure --> <!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven /> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up
static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<resources mapping="/plugins/**"
location="/resources/plugins/" />
<resources mapping="/dist/**" location="/resources/dist/" /> <!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan
base-package="com.cameldev.httpsession" />
</beans:beans>
root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy" />
<property name="url"
value="jdbc:log4jdbc:mysql://127.0.0.1:3306/injo?serverTimezone=UTC&useSSL=false" />
<property name="username" value="root" />
<property name="password" value="howang12" />
</bean>
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation"
value="classpath:/mybatis-config.xml" />
<property name="mapperLocations"
value="classpath:mappers/**/*Mapper.xml" />
</bean>
<bean id="sqlSession"
class="org.mybatis.spring.SqlSessionTemplate"
destroy-method="clearCache">
<constructor-arg name="sqlSessionFactory"
ref="sqlSessionFactory" />
</bean>
<context:component-scan base-package="com.cameldev.httpsession" />
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param> <!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

Simple RestFul WebService with Component-scan

I am trying to autowire an object using component-scan in my restFul Webservice. But getting Nullpointer exception when userDao object is used.
I dont want to use Spring MVC or spring boot. Just want to simply inject the dependency using component-scan. Please help!!!
UserDao.java
#Component
public class UserDao {
public List<User> getAllUsers(){
//return a list
}
}
UserService.java
#Component
#Path("/UserService")
public class UserService {
#Autowired
private UserDao userDao;
#PostConstruct
public void initialize() {
System.out.println("userDao object: " + userDao);
}
#GET
#Path("/users")
#Produces(MediaType.APPLICATION_JSON)
public List<User> getUsers(){
return getUserDao().getAllUsers();
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
applicationContext.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:aop = "http://www.springframework.org/schema/aop"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<context:annotation-config/>
<context:component-scan base-package="com.rest"/>
<aop:aspectj-autoproxy/>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns = "http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id = "WebApp_ID" version = "3.0">
<display-name>User Management</display-name>
<servlet>
<servlet-name>Jersey RESTful Application</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.rest</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Jersey RESTful Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
You will need to define a bean in your applicationContext.xml file. Spring container initializes this bean when the application is started.
eg.
<bean id="userDAO" class="your.package.name.UserDAO">
<!-- In case if you use hibernate -->
<property name="sessionFactory" ref="sessionFactory" />
</bean>
As an analogy, you can think of this as spring is doing UserDAO userDAO = new UserDAO(); for you.

WARNING: No mapping found for HTTP request with URI [/SpringLoginApplication/] in DispatcherServlet with name 'SpringLoginApplication'

My project is a maven project when i run the project on tomcat it shows
org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringLoginApplication/] in DispatcherServlet with name 'SpringLoginApplication'
I tried all possibilities to resolve but all in vein, can somebody help me out to resolve this issue
my controller :
package com.spring.login.controller;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import com.spring.login.beans.Customer;
import com.spring.login.services.CustomerService;
import com.spring.login.validation.CustomerValidation;
#Controller
public class CustomerController {
#Autowired
private CustomerService customerService;
#RequestMapping(value="/" , method=RequestMethod.GET)
public String login(ModelMap model){
//model.put("Info", new Customer());
return "/login";
}
#RequestMapping(value="/register", method = RequestMethod.GET)
public String showForm(ModelMap model){
model.put("customerData", new Customer());
return "/register";
}
#RequestMapping(value= "/register", method= RequestMethod.POST)
public String saveForm(ModelMap model, #ModelAttribute("customerData") #Valid Customer customer, BindingResult br, HttpSession session){
CustomerValidation customerValidation = new CustomerValidation();
customerValidation.validate(customerValidation, br);
if(br.hasErrors()){
return "/register";
}
else{
customerService.saveCustomer(customer);
session.setAttribute("customer", customer);
return "redirect:success";
}
}
#RequestMapping(value="/logout", method = RequestMethod.GET)
public String logOut(ModelMap model, HttpSession session){
session.removeAttribute("customer");
return "redirect:login";
}
#RequestMapping(value="/success", method = RequestMethod.GET)
public String logOut(ModelMap model){
model.put("customer", new Customer());
return "redirect:success";
}
}
my web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" >
<display-name>SpringLoginApplication</display-name>
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<listener>
<listener-
class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>SpringLoginApplication</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/SpringLoginApplication-servlet.xml
</param-value>
</init-param>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringLoginApplication</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
my SpringLoginApplication-servlet.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.spring.login.controller" />
<context:component-scan base-package="com.spring.login.dao" />
<context:component-scan base-package="com.spring.login.beans" />
<context:component-scan base-package="com.spring.login.services" />
<context:component-scan base-package="com.spring.login.validation" />
<mvc:annotation-driven />
<context:annotation-config />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean class="com.spring.login.beans.Customer" init-method="getC_id" destroy-
method="getC_name">
<property name="c_id" value="1234"/>
<property name="c_name" value="Sanjay"/>
</bean>
</beans>
A working response would be highly appreciated!
ANY OTHER INFO REQUIRED, PLS LET ME KNOW
I had the same problem few days before, and I got bellow solution.
#Controller
#RequestMapping(value="/" )
public class CustomerController {
//do your stuff here
#RequestMapping(method=RequestMethod.GET)
public String login(ModelMap model){
//model.put("Info", new Customer());
return "/login";
}
//Rest of your stuff goes here
}
Since you have configured your Dispatcher servlet to handle your context in stead of all possibility which people generally do by adding this (/*), so above provided code snippet will work and redirect your context to /login which you want(if i'm not wrong). Cheers!!!!

Page not found. Spring MVC + Jetty

I'm trying to start up Jetty with Spring MVC that contains jsp and #Controller. After start jetty I've got every time WARN if I try to call any pages. For example
ttp://localhost:8080/getMessageStats/
No mapping found for HTTP request with URI [/resources/css/bootstrap.min.css] in DispatcherServlet with name 'org.springframework.web.servlet.DispatcherServlet-57ad85ed' No mapping found for HTTP request with URI [/resources/js/bootstrap.min.js] in DispatcherServlet with name 'org.springframework.web.servlet.DispatcherServlet-57ad85ed'
web.xml
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/cloud/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="net.cloud.web.statistics"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
WebServer.class
public class WebServer {
private static final Logger log = LoggerFactory.getLogger(WebServer.class);
private static final String CONTEXT_PATH = "/";
private Server httpServer;
#Value("${http_statistics_port}")
private Integer port;
#Value("${start_page_path}")
private String startPagePath;
public void init() {
try {
httpServer = new Server(port);
httpServer.setHandler(getServletContextHandler());
httpServer.setStopAtShutdown(true);
httpServer.start();
log.info("WebServer start ...");
httpServer.join();
} catch (Exception ex) {
log.error("Exception in http server. Exception: {}", ex.getMessage());
}
}
private static ServletContextHandler getServletContextHandler() throws IOException {
WebAppContext contextHandler = new WebAppContext();
contextHandler.setErrorHandler(null);
contextHandler.setContextPath(CONTEXT_PATH);
WebApplicationContext context = getContext();
contextHandler.addServlet(new ServletHolder(new DispatcherServlet(context)), CONTEXT_PATH);
contextHandler.addEventListener(new ContextLoaderListener(context));
contextHandler.setResourceBase(new ClassPathResource("webapp").getURI().toString());
contextHandler.setDescriptor("/webapp/WEB-INF/web.xml");
return contextHandler;
}
private static WebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("webapp/WEB-INF/");
log.info("CONTEXT name {} locations {}", context.getDisplayName(), context.getConfigLocations());
return context;
}
}
GetMessagesStatsController.class
#Controller
#RequestMapping("/getMessageStats")
public class GetMessageStatsController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
GetMessageStatsRPC rpc = new GetMessageStatsRPC();
model.addAttribute("result", rpc.getResult());
return "getMessageStats";
}
#RequestMapping(value = "/json", method = RequestMethod.GET)
public #ResponseBody
String generateJsonResponse() {
GetMessageStatsRPC rpc = new GetMessageStatsRPC();
return rpc.getResult().toString();
}
}
Project tree (Sorry, no rating to upload picture). Classes:
src/java/main/net/.../WebServer.class;src/java/main/net/.../GetMessagesStatsController.class
src/main/webapp/WEB-INF/web.xml; src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml; src/main/webapp/WEB-INF/pages/*.jsp; src/main/webapp/resources/css and src/main/webapp/resources/js
Guys, any idea?
First when the application is deployed it checks the web.xml and gets
<url-pattern>/*</url-pattern>
Then it initializes the DispatcherServlet and initializes the initialization paramerters using
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
(WEB-INF must start with /)
then in mvc-dispatcher-servlet.xml the view resolver resolves the rendering pages.
Change <property name="prefix" value="WEB-INF/pages/"/>
to
<property name="prefix" value="/WEB-INF/pages/"/>
Finally in your controller #RequestMapping("/getMessageStats")
so finally launching the application as
http://localhost:8080/ProjectName/getMessageStats/
invokes printWelcome() of GetMessagesStatsController and
http://localhost:8080/ProjectName/getMessageStats/json
invokes generateJsonResponse()
Looks like the viewResolver has problem. change the prefix to /WEB-INF/pages/, as follow:
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
Without the slash it means a relative path, so it will find the page at relativePath(getMessageStats/) + prefix(WEB-INF/pages/) + request(getMessageStats) +suffix(.jsp).

Web Application based on Spring Security crashes during startup (NullPointerException)

My application, which make use of Spring Security, is crashing during the startup. Tracking the execution of the application, I could verify the error is happening in method onStartup from class MainWebAppInitializer:
public class MainWebAppInitializer implements WebApplicationInitializer {
/**
* Register and configure all Servlet container components necessary to power the web application.
*/
#Override
public void onStartup(final ServletContext sc) throws ServletException {
// Create the 'root' Spring application context
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.scan("com.spring.web.config");
// Manages the lifecycle of the root application context
sc.addListener(new ContextLoaderListener(root));
// Handles requests into the application
final ServletRegistration.Dynamic appServlet = sc.addServlet("horariolivreapp", new DispatcherServlet(new GenericWebApplicationContext()));
appServlet.setLoadOnStartup(1);
final Set<String> mappingConflicts = appServlet.addMapping("/");
if (!mappingConflicts.isEmpty()) {
throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
}
}
}
More specificly, the error occurs in the line
appServlet.setLoadOnStartup(1)
where a NullPointerException is triggered. Follow it is my configuration files, for reference:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>HorarioLivre</display-name>
<!-- Spring MVC -->
<servlet>
<servlet-name>horariolivreapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>horariolivreapp</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.spring.web.config</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
horariolivreap-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.horariolivreapp.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
webSecurityConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<http use-expressions="true">
<intercept-url pattern="/login*" access="isAnonymous()" />
<intercept-url pattern="/**" access="isAuthenticated()"/>
<form-login
login-page='/form_login.html'
login-processing-url="/usuario_login.html"
default-target-url="/usuario_start.html"
authentication-failure-url="/form_login"
always-use-default-target="true"/>
<logout logout-success-url="/login.html" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="user1Pass" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
Looking in this files, someone can find the reason for this problem?
UPDATE 1
This is my Controller (DispatcherServlet) class:
package com.horariolivreapp.controller;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.horariolivreapp.core.Sessao;
import com.horariolivreapp.data.UsuarioDAO;
#Controller
public class HorarioLivreController {
private Sessao sessao;
#RequestMapping("/cadastra_evento")
public ModelAndView cadastra_evento() {
return null;
}
#RequestMapping(value="/listagem_evento", method=RequestMethod.GET)
public ModelAndView listagem_evento() {
return null;
}
#RequestMapping("/cadastra_horario")
public ModelAndView cadastra_horario() {
return null;
}
#RequestMapping("/listagem_horario")
public ModelAndView listagem_horario() {
return null;
}
#RequestMapping("/cadastra_usuario")
public ModelAndView cadastra_usuario() {
return null;
}
#RequestMapping("/listagem_usuario")
public ModelAndView listagem_usuario() {
return null;
}
#RequestMapping("/cadastra_tipo")
public ModelAndView cadastra_tipo() {
return null;
}
#RequestMapping("/cadastra_campo")
public ModelAndView cadastra_campo() {
return null;
}
#RequestMapping("/cadastra_autorizacao")
public ModelAndView cadastra_autorizacao() {
return null;
}
#RequestMapping("/usuario_perfil")
public ModelAndView usuario_perfil() {
return null;
}
#RequestMapping("/usuario_config")
public ModelAndView usuario_config() {
return null;
}
#RequestMapping(value="/usuario_login", method=RequestMethod.POST)
public ModelAndView usuario_login(#RequestParam("j_username") String username, #RequestParam("j_password") String password) {
UsuarioDAO usuario = new UsuarioDAO(username, password);
if(usuario.getUsuario() != null) {
this.sessao = new Sessao(usuario.getUsuario());
}
return new ModelAndView("usuario_start","usuario",usuario.getUsuario());
}
#Configuration
#ImportResource({ "classpath:webSecurityConfig.xml" })
public class SecSecurityConfig {
public SecSecurityConfig() {
super();
}
}
}
An NPE at that point means that appServlet is null, which in turn means that sc.addServlet(...) returned null.
The Javadoc for addServlet says this:
"Returns: a ServletRegistration object that may be used to further configure the given servlet, or null if this ServletContext already contains a complete ServletRegistration for a servlet with the given servletName or if the same servlet instance has already been registered with this or another ServletContext in the same container."
Now you are instantiating the Servlet object at that point, so it cannot have previously been registered. But there could be another Servlet with the same name ... and that's the probable immediate cause of the problem.
And in fact, it looks like you have already registered a servlet called "horariolivreapp" by declaring it in the web.xml file.

Categories