Page not found. Spring MVC + Jetty - java

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).

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>

HTTP Status 500 - Servlet.init() for servlet spring threw exception here is my code

controller,service and dao are in different package UserSer interface and UserService class is on package com.service UserDa interface and UserDao class is on package com.dao and Controller is on Package com.controller please help me with this , if i am doing this all on the same package its working but for different package its not working
thankyou
#Controller
public class UserController {
#Autowired
public UserSer userSer;
#RequestMapping(value="/get")
public void dummytest()
{
System.out.println(userSer.SayHii());
}
}
#Service("UserSer")
public class UserService implements UserSer{
#Autowired
public UserDa userDa;
public String SayHii() {
return userDa.Say();
}
}
#Repository("UserDa")
public class UserDao implements UserDa {
public String Say()
{
return "hiiiiiiiiiiiii";
}
}
web.xml
* <servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>*
spring-servlet.xml
*<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:ctx="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/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
">
<ctx:annotation-config></ctx:annotation-config>
<mvc:annotation-driven/>
<ctx:component-scan base-package="com.controller"></ctx:component-scan>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</bean>*

NPE in my service class of rest using jersey with spring

I am new to spring and rest i am still learning it. I have a problem while calling the resource from my rest api through a client.
I have some data in my database and i am using spring to inject the values and get connection.
When i am making a GET request from the client i am getting a NPE.
Below is my DAO Class
public interface CustomerDao {
public List<Customer> getCustomersDao();
}
DAOImpl
public class CustomerDaoImpl implements CustomerDao {
private JdbcTemplate template;
#Autowired
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Customer> getCustomersDao() {
return template.query("SELECT * FROM books.customers", new RowMapper<Customer>() {
#Override
public Customer mapRow(ResultSet rs, int rownumber) throws SQLException {
Customer e = new Customer();
e.setId(rs.getString(1));
e.setName(rs.getString(2));
e.setAge(rs.getString(3));
return e;
}
});
}
Service class
public class CustomerService {
#Autowired
CustomerDao customersConnection;
public List<Customer> getAllCustomers() {
return new ArrayList<Customer>(customersConnection.getCustomersDao());
}
Resource
#Path("/persons")
public class CustomerResource {
#Autowired
CustomerService customerService;
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Customer> getAllCustomers {
return customerService.getAllCustomers();
}
}
My bean.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-4.0.xsd">
<context:component-scan base-package="com.sumanth.customers" />
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="--:--://----/---" />
<property name="username" value="----" />
<property name="password" value="-----" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="customerService" class="com.sumanth.customer.db.CustomerDaoImpl">
<property name="template" ref="jdbcTemplate"></property>
</bean>
</beans>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.sumanth.customer</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
Error:
Caused by: java.lang.NullPointerException
at com.sumanth.customer.resource.CustomerResource.getAllCustomers(CustomerResource.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
Error line 23 :
return customerService.getAllCustomers();
I used the #Autowired to wire the beans.I know that i did a mistake while wiring them can anybody please help me out
Thank you
I have made some modifications to the web xml and my bean.xml
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/bean.xml</param-value>
</context-param>
Modified my service class
#Component annotation in my service class
My bean.xml added the below
<context:annotation-config />
My Impl class.I have added the annotation above my class
#Repository("customerService")

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.

How can I map my Spring URL to a JSP file in /WEB-INF/views?

I'm having trouble doing a Spring (using 3.0.5.RELEASE) mapping. I want to map the URL http://mydomain/context-path/user/registrationform.jsp to my JSP page at
/WEB-INF/views/user/registrationform.jsp
but I'm getting a 404. I have my controller setup like so …
#Controller
#RequestMapping("registrationform.jsp")
public class RegistrationController {
private static Logger LOG = Logger.getLogger(RegistrationController.class);
…
public void setRegistrationValidation(
RegistrationValidation registrationValidation) {
this.registrationValidation = registrationValidation;
}
// Display the form on the get request
#RequestMapping(method = RequestMethod.GET)
public String showRegistration(Map model) {
final Registration registration = new Registration();
model.put("registration", registration);
return "user/registrationform";
}
here is my dispatcher-servlet.xml …
<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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven />
<context:component-scan base-package="com.burrobuie.eventmaven" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/messages" />
</bean>
</beans>
and here is my web.xml …
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
What else do I need to configure (or configure differently) to make this mapping work? This is harder than - Dave
#Controller
#RequestMapping("registrationform.jsp")
public class RegistrationController {
The RequestMapping annotation at class level should be use for a common url pattern like "item/*" and all the links that contains "/item" followed by other pattern would be mapped it to the controller. "user/" in your case
The RequestMapping annotation at method level is used for mapping the sub URL like "item/add" or "item/delete", "registrationform.jsp' in your case
So try this:
#Controller
#RequestMapping("/user")
public class RegistrationController {
private static Logger LOG = Logger.getLogger(RegistrationController.class);
…
public void setRegistrationValidation(
RegistrationValidation registrationValidation) {
this.registrationValidation = registrationValidation;
}
// Display the form on the get request
#RequestMapping(value="/registrationform.jsp",method = RequestMethod.GET)
public String showRegistration(Map model) {
final Registration registration = new Registration();
model.put("registration", registration);
return "user/registrationform";
}
This will map /user/registrationform.jsp
Change the RequestMapping to:
#RequestMapping("/user/registrationform.jsp")

Categories