This question already has answers here:
Why does Spring MVC respond with a 404 and report "No mapping found for HTTP request with URI [...] in DispatcherServlet"?
(13 answers)
Closed 6 years ago.
I am new to Spring. I am stuck in one problem although I have looked this in various sites and followed the question that are here with this topic but still I am not able to find a solution.
I'm getting this error
No mapping found for HTTP request with URI [/ReadingsMVC/] in DispatcherServlet with name 'spring'
My web.xml is-
<?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_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring3MVC</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>*.do</url-pattern>
</servlet-mapping>
</web-app>
My Spring-Servlet is-
<?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.abc.reading.controller"/>
<bean id="viewResolver"
class="/WEB-INF/jsp/.*jsp">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
My Java Rest Controller code is
package com.lucidtechsol.reading.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.abc.reading.exception.InvalidRangeException;
import com.abc.reading.exception.NegativeNumberException;
import com.abc.reading.utilities.RandomNumberGenerator;
#RestController
public class ReadingController {
#RequestMapping("/reading")
public String getReading() throws NegativeNumberException, InvalidRangeException {
return new Integer(new RandomNumberGenerator().generateRandomNumber(100, -50)).toString();
}
}
My TestRandomNumberGenerator is
package com.abc.testcase;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.abc.reading.exception.InvalidRangeException;
import com.abc.reading.exception.NegativeNumberException;
import com.abc.reading.utilities.RandomNumberGenerator;
public class TestRandomNumberGenerator {
int upper;
int lower;
RandomNumberGenerator generator;
/**
* #throws java.lang.Exception
*/
#Before
public void setUp() throws Exception {
generator = new RandomNumberGenerator();
}
/**
* #throws java.lang.Exception
*/
#After
public void tearDown() throws Exception {
generator = null;
}
#Test
public void testPositive() {
upper = 10;
lower = 5;
try {
assertTrue(upper >= generator.generateRandomNumber(lower, upper));
} catch (NegativeNumberException | InvalidRangeException e) {
e.printStackTrace();
}
}
#Test(expected = NegativeNumberException.class)
public void testNegativeNumberException() throws NegativeNumberException,
InvalidRangeException {
upper = 10;
lower = -5;
generator.generateRandomNumber(lower, upper);
}
#Test(expected = InvalidRangeException.class)
public void testInvalidRangeException() throws NegativeNumberException,
InvalidRangeException {
upper = 30;
lower = 10;
generator.generateRandomNumber(lower, upper);
}
}
My exception java file are-
InvalidException
/**
*
*/
package com.abc.reading.exception;
/**
* #author kuppusamys
*
*/
public class InvalidRangeException extends Exception {
/**
*
*/
private static final long serialVersionUID = 4348179544370409821L;
public InvalidRangeException() {
super();
}
public InvalidRangeException(String message) {
super(message);
}
}
NegativeException
/**
*
*/
package com.abv.reading.exception;
/**
* #author kuppusamys
*
*/
public class NegativeNumberException extends Exception {
/**
*
*/
private static final long serialVersionUID = -7903564384519771246L;
public NegativeNumberException() {
super();
}
public NegativeNumberException(String message) {
super(message);
}
}
RandomNumberGenerator is
import java.util.Random;
import com.abc.reading.exception.InvalidRangeException;
import com.abc.reading.exception.NegativeNumberException;
public class RandomNumberGenerator {
public int generateRandomNumber(int upper, int lower) throws NegativeNumberException, InvalidRangeException {
if (lower < 0) {
throw new NegativeNumberException(
"Lower bound of range is negative -->" + lower);
}
if (upper < 0) {
throw new NegativeNumberException(
"Upper bound of range is negative -->" + upper);
}
if (upper < lower) {
throw new InvalidRangeException("Upper bound of range -->" + upper
+ " is smaller than lower bound of range -->" + lower);
}
return lower + new Random().nextInt(upper - lower);
}
}
My .jsp file is- Hello
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>spring mvc</title>
</head>
<body>
${message}
</body>
</html>
I am not understanding what I am doing wrong. Please help me!
if you don't understanding please comment
Try with http://localhost:8080/reading
web.xml
<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">
<display-name>Spring Web 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>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean class="com.abc.reading.controller.ReadingController" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
Related
First time using Spring (and new to MVC architecture as well) and Apache Tomcat and I'm able to load my index just fine after following a few videos/tutorials, but now that I'm trying to add other pages, I keep getting a 404 error. Here's what I have so far and the project structure is below as well for reference. The mapping of resources also seems to not be working as my index isn't loading images/js/etc.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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>
</web-app>
dispatcher-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: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">
<mvc:annotation-driven/>
<context:component-scan base-package="org.hackathon_10_20.EasySub.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:resources mapping="/resources/**" location="/WEB-INF/theme/startbootstrap-new-age-gh-pages/" cache-period="31556926"/>
</beans>
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
IndexController.java
package org.hackathon_10_20.EasySub.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
/**
* Created by Chris Bonilla on 10/20/2018.
*/
#Controller
public class IndexController {
#GetMapping("/")
public String index(Model m) {
m.addAttribute("someAttribute", "someValue");
return "index";
}
}
SubPlanController.java
package org.hackathon_10_20.EasySub.controller;
import org.hackathon_10_20.EasySub.domain.SubPlan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;
import java.util.HashMap;
#Controller
public class SubPlanController {
Map<Long, SubPlan> subPlanMap = new HashMap<>();
#RequestMapping(value ="/subplan", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("subPlanHome", "SubPlan", new SubPlan());
}
#RequestMapping(value = "/subplan/{Id}", produces = { "application/json", "application/xml"}, method = RequestMethod.GET)
public #ResponseBody SubPlan getSubPlanById(#PathVariable final long Id) {
return subPlanMap.get(Id);
}
#RequestMapping(value = "/addSubPlan", method = RequestMethod.POST)
public String submit(#ModelAttribute("SubPlan") final SubPlan subplan, final BindingResult result, final ModelMap model) {
if (result.hasErrors()) {
return "error";
}
//model.addAttribute("name", subplan.getName());
//subPlanMap.put(subplan.getId(), subplan);
return "subPlanView";
}
}
You're missing a url-pattern value in your web.xml. It is empty.
Just change it to:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Hello I'm trying to test one of my class but I have this warning when i do mvn test : No mapping found for HTTP request with URI [/accueil] in DispatcherServlet with name ''.
This is strange because I have access to this page outside of the test.
here is the class that I want to test (I can access it via localhost:8080/accueil) :
package uVote.controllers;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import uVote.DAO.ScrutinDAO;
import uVote.model.Scrutin;
import uVote.model.Votant;
#Controller
#RequestMapping(value = "/accueil")
public class Accueil
{
#RequestMapping(method = RequestMethod.GET)
public String accueil(Model model,HttpServletRequest request)
{
Votant co = VerifCo.isConnecte(request);
if(co == null)
return "redirect:connexion";
else
{
request.setAttribute("votant", co);
List<Scrutin> scrutins = new ScrutinDAO().getToutScrutins();
List<Scrutin> scrutinsToShow = new ArrayList<Scrutin>();
for(Scrutin s : scrutins)
{
if(!s.estDansRegistre(co) || s.isTermine())
scrutinsToShow.add(s);
}
request.setAttribute("scrutins", scrutinsToShow);
}
return "accueil";
}
#RequestMapping(method = RequestMethod.POST)
public String deconnection(Model model,HttpServletRequest request)
{
VerifCo.deconnecteVotant(request);
return "redirect:accueil";
}
}
and here is the test case :
package uVote.controllers;
import java.util.HashMap;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import uVote.model.Votant;
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(classes = uVote.controllers.Accueil.class)
/**
*
* #author kirua
*/
public class AccueilTest
{
#Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
#Before
public void setup()
{
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/vues/");
viewResolver.setSuffix(".jsp");
this.mockMvc = MockMvcBuilders.standaloneSetup(new HelpController())
.setViewResolvers(viewResolver)
.build();
}
#Test
public void testVotant() throws Exception
{
HashMap<String, Object> sessionattr = new HashMap<String, Object>();
Votant vo = new Votant(1, "toto_prenom", "toto_nom", "toto_adresse", "mdp");
sessionattr.put("votant", vo);
ResultMatcher ok = MockMvcResultMatchers.status().isOk();
// ResultMatcher msg = MockMvcResultMatchers.model()
// .attribute("msg", "Spring quick start!!");
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/accueil").sessionAttrs(sessionattr);
this.mockMvc.perform(builder)
.andExpect(ok)
.andExpect(view().name("accueil"));
// .andExpect(msg);
}
}
and the HelpController :
public class HelpController extends AbstractController
{
private static Log log = LogFactory.getLog(HelpController.class);
#Override
protected ModelAndView handleRequestInternal(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception
{
log.debug("Entering HelpController.handleRenderRequestInternal()");
ModelAndView modelAndView = new ModelAndView("Help");
log.debug("Exiting HelpController.handleRenderRequestInternal() " + modelAndView);
return modelAndView;
}
}
my web.xml :
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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/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>
</web-app>
my 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 http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<!-- Anable du model #Controller -->
<annotation-driven />
<!-- Gère les requète d'éléments de ressource (css / js / images ...) -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Résolution des vues utilisées (renvoyées) par les controller - Rendu/Intepretation JSP -->
<beans:bean id="viewReslover" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> -->
<beans:property name="prefix" value="/vues/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="uVote.controllers" />
</beans:beans>
and my root-context :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
Do you have an idea of what is happening ? I'm a noob in java so I'm not sure where could be the problem.
Please ask if you need to see some other file.
Hi I am new to Spring Framework. I am just creating POC to learn Spring Concepts. While implementing the same i am getting below exception while loading of application. Please provide me you suggestions to resolve this.
"Error creating bean with name 'userServicesDao': Unsatisfied dependency expressed through method 'setDbConfiguration' parameter 0"
UserServicesDao
package com.pe.dao;
#Component
public class UserServicesDao {
private DBConfiguration dbConfiguration;
#Autowired()
public void setDbConfiguration(DBConfiguration dbConfiguration) {
this.dbConfiguration = dbConfiguration;
}
public List<User> getUser()
{
System.out.println("User Services Dao : "+this.toString());
System.out.println("Connection Info : "+this.dbConfiguration);
return new ArrayList<User>();
}
#Override
public String toString() {
return "UserServicesDao [connection Config=" + dbConfiguration + "]";
}
}
ConnectionConfig.Java
package com.pe.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
#Component(value ="dbConfiguration")
public class DBConfiguration {
#Value("com.mysql.jdbc.Driver")
private String driver;
#Value("jdbc:mysql://localhost:3306/mydb")
private String url;
#Value("root")
private String username;
#Value("root")
private String password;
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Spring-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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<context:component-scan base-package="com.pe.controller,com.pe.dao,com.pe.bean" />
<mvc:annotation-driven/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/jsp/</value>
</property>
<property name="suffix" value=".jsp">
</property>
</bean>
<mvc:resources mapping="/resources/**" location="/resources/" />
</beans>
Web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/spring</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:com/predictenergy/bean/dao-config.xml</param-value>
</context-param>
</web-app>
Click to see Class Folder Structure
It was autowiring before correction if i was doing it through xml. Please refer below xml code i was using before.
<bean id ="userServicesDao" class="com.pe.dao.UserServicesDao" autowire="byType">
<property name="dbConfiguration" ref= "dbConfiguration"></property>
</bean>
<bean id ="dbConfiguration" class ="com.pe.bean.DBConfiguration">
<property name="driver" value= "com.mysql.jdbc.Driver"></property>
<property name="url" value= "jdbc:mysql://localhost:3306/mydb"></property>
<property name="username" value= "root"></property>
<property name="password" value= "root"></property>
</bean>
Please guide me with your solution.
I am stuck with a strange situation when loading up my web application on tomcat. The welcome file gets loaded well, but the controller part is not getting invoked.
Here is my Project Directory:
Here is 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>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/application-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/WEB-INF/views/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Here is my controller class
package com.bng.monitor.controller;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.bng.monitor.util.Utility;
#Controller
public class MonitoringController {
private static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
private static SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//private static List<DBObject> pipeline=new ArrayList<DBObject>();
static HashMap<String, String> hmLatestDateTime=new HashMap<String, String>();
#Autowired
private Utility utility;
private static #Value("${pageRefresh}") String pageRefresh;
public Utility getUtility() {
return utility;
}
public void setUtility(Utility utility) {
this.utility = utility;
}
public static String getPagerefresh() {
return pageRefresh;
}
public void setPagerefresh(String pagerefresh) {
MonitoringController.pageRefresh = pagerefresh;
}
#RequestMapping(value="/version", method=RequestMethod.GET)
public ModelAndView getVersion(){
System.out.println("inside controller..");
ModelAndView mav=null;
try
{
mav=new ModelAndView("version");
if(Utility.version!=null)
mav.addObject("versionapp", Utility.version);
else if(Utility.version == null || Utility.version.equals(""))
mav.addObject("versionapp", "property not defined.. :)");
} catch (Exception e) {
e.printStackTrace();
}
return mav;
} // end of getVersion()
#RequestMapping(value="/reloadftp",method=RequestMethod.GET)
public void reloadFtpConfig(){
try {
this.utility.getFtpCred();
} catch (Exception e) {
e.printStackTrace();
}
}
#RequestMapping(value="/")
public String displayGui(ModelMap model) {
try
{
System.out.println("<<< inside root mapping for index.jsp display >>>");
model.addAttribute("map", Utility.hmServerFtpCred);
model.addAttribute("pagerefresh", pageRefresh);
String key=null;
String combinedJson=null;
JSONArray jsonArray=null;
JSONObject jsonObject1=null;
JSONObject jsonObject2=null;
String tempMod=null;
String tempStat=null;
String cpu=null;
String ram=null;
for(Map.Entry entry: Utility.hmServerFtpCred.entrySet()){
key = (String) entry.getKey();
// for each key get combinedJson (and do so in a loop as the json formed there may not be valid) and parse it to get module and system properties cached into hmGuiData
//TODO add logic to alter GUI to give some indication(color based) that the data is not updated since long time.
combinedJson = Utility.getStats(key);
jsonArray = new JSONArray(combinedJson);
System.out.println(">>> combined JSON: "+jsonArray.toString());
JSONArray moduleArr = jsonArray.getJSONObject(0).getJSONObject("details").getJSONArray("module");
for(int index=0; index<moduleArr.length() ; index++)
{
tempMod=moduleArr.getJSONObject(index).getString("module_name");
tempStat=moduleArr.getJSONObject(index).getString("live");
Utility.hmGuiData.put(key+"_"+tempMod.toLowerCase(), tempStat);
}
Utility.hmGuiData.put(key+"_"+"cpu", jsonArray.getJSONObject(1).getJSONObject("details").getString("cpu"));
Utility.hmGuiData.put(key+"_"+"ram", jsonArray.getJSONObject(1).getJSONObject("details").getString("ram"));
/*jsonObject1 = (JSONObject) jsonArray.get(0);
jsonObject2 = (JSONObject) jsonArray.get(1);
jsonObject1.getJSONObject("details").*/
} // end of inner for
System.out.println(">>> Utility.hmGuiData: "+Utility.hmGuiData);
model.addAttribute("guidata", Utility.hmGuiData);
return "index";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#RequestMapping(value="/getstatsone",method=RequestMethod.GET)
public void getStatsOne(HttpServletRequest req,HttpServletResponse resp){
}
#RequestMapping(value="/getopco",method=RequestMethod.GET)
public void getOpco(HttpServletRequest req,HttpServletResponse resp) {
PrintWriter pw=null;
System.out.println(">>> inside /getopco");
JSONObject json=null;
try
{
pw=resp.getWriter();
json=new JSONObject(Utility.hmServerFtpCred);
pw.println(json);
}
catch (Exception e)
{
e.printStackTrace();
}finally{
try {
if(pw!=null)
pw.close();
} catch (Exception ee) {
ee.printStackTrace();
}
}
}
}//end of Controller class
and here is my application-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:c="http://www.springframework.org/schema/c"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:core="http://activemq.apache.org/schema/core" xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.7.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.bng.monitor" />
<bean id="properties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/config.properties" />
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources location="/resources/css/**" mapping="/css/**"/>
<mvc:resources location="/resources/img/**" mapping="/img/**"/>
<mvc:resources location="/resources/js/**" mapping="/js/**"/>
<!-- <mvc:resources location="/WEB-INF/views/**" mapping="/js/**"/> -->
<mvc:annotation-driven />
<mvc:resources mapping="/*" location="/WEB-INF/views/" />
</beans>
Now there are two things happening...
1. When I make the url pattern as /* and make the request, then only the controller gets invoked, welcome jsp is not loaded and tomcat gives error 404, the requested resource is not available.
When i change the url pattern to /, then only welcome page gets loaded and no backend controller specific mapping is called.
In both the cases, my application is not loaded.
Please help me out to load the web app successfully.
Removing the following welcome list from web.xml solved the issue.
So, I just removed the following lines from web.xml
<welcome-file-list>
<welcome-file>/WEB-INF/views/index.jsp</welcome-file>
</welcome-file-list>
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/j2ee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/j2ee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Self Service Portal</display-name>
<welcome-file-list>
<welcome-file>home.html</welcome-file>
<welcome-file>default.html</welcome-file>
</welcome-file-list>
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET, POST, PUT, DELETE, OPTIONS, HEAD</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>login</filter-name>
<filter-class>com.app.api.filter.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>login</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
<!-- Spring Context Listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext*.xml</param-value>
</context-param>
</web-app>
Custom filter class:-
package com.app.api.filter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import com.fasterxml.jackson.databind.ObjectMapper;
#WebFilter("/*")
public class AuthenticationFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationFilter.class);
public AuthenticationFilter() {
System.out.println("Authentication - default filter !");
}
public void destroy() {
System.out.println("Authentication - destroy !");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
LOGGER.debug("Request authentication!");
HttpServletRequest httpRequest = (HttpServletRequest) request;
String uri = httpRequest.getRequestURI();
if(uri.equals("/app-api/login") || uri.equals("/app-api/logout")) {
chain.doFilter(request, response);
return;
}
HttpSession session = httpRequest.getSession(false);
if(session == null || session.getAttribute("user") == null) {
writeInvalidCredentialResponse((HttpServletResponse) response);
} else {
chain.doFilter(request, response);
}
}
private void writeInvalidCredentialResponse(HttpServletResponse response) throws IOException {
Map<String, String> errorResponse = new HashMap<String, String>();
errorResponse.put("message", "Please login with right credentials!");
ObjectMapper mapper = new ObjectMapper();
String responseMessage = mapper.writeValueAsString(errorResponse);
LOGGER.debug("Invalid request authentication!");
LOGGER.debug(responseMessage);
response.getWriter().write(responseMessage);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("Authentication - init !");
}
}
Project hierarchy:-
A - parent maven module
B - RESTful webservices sub module (contains - /WEB-INF/web.xml, /WEB-INF/dispatcher-servlet.xml)
C - persistence layer sub module (contains - /resources/applicationContext.xml, /resources/persistence.xml)
Please help me to resolve this issue to make my both spring context up and running (ui - webservices and persistence)
Many thanks in advance !
app-api
/app-api/src/main/webapp/WEB-INF/dispatcher-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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<import resource="classpath:/applicationContext-data.xml" />
<context:annotation-config />
<context:component-scan base-package="com.app" />
<context:property-placeholder location="classpath:*.properties" />
<mvc:annotation-driven/>
</beans>
app-data
/app-data/src/main/resources/applicationContext-data.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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-2.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- ************* JPA/Hibernate configuration ************* -->
<bean
name="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.app.data.*" />
<property name="persistenceXmlLocation" value="classpath:persistence.xml" />
<property name="persistenceUnitName" value="persistence-unit" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
</bean>
<bean
id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<bean
id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/app"
p:username="root"
p:password="root123"
p:initialSize="5"
p:maxActive="10">
</bean>
<context:component-scan base-package="com.app.data.*" />
<tx:annotation-driven />
</beans>
Let's see the exception:
java.lang.ClassNotFoundException: com.adobe.ssp.api.filter.AuthenticationFilter
There was a problem with your classpath, the class "com.adobe.ssp.api.filter.AuthenticationFilter" was not found. Please make sure this class is contained in: YOUR_APP\WEB-INF\classes or YOUR_APP\WEB-INF\lib
Try removing #WebFilter and make sure about your init method overriding as we can't see that in code provided.