Properly configure dispatcher-servlet, applicationContext and web.xml - java

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>

Related

Java - HTTP Status 404 – Not Found

I'm studying spring mvc and want to test some very simple annotation-based controllers,It works fine on home page but when I enter /home/user it gives me HTTP Status 404 – Not Found error and I haven't found anything to fix it.
web.xml
<web-app version="3.1" 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">
<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>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
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"
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">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<context:component-scan base-package="spring" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--<bean id="viewResolver"
</beans>
HomeController.java
package spring.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
//#RequestMapping(value = "/home")
public class HomeController {
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String showHomeMessage() {
return "home";
}
}
UserController.java
package spring.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/home/user")
public class UserController {
#RequestMapping(method = RequestMethod.GET)
public String welcomeMessage(){
return "user";
}
}
redirect.jsp just uses sendRedirect() method and redirects to home.jsp.
home.jsp and user.jsp just prints a simple hello message
Where I'm doing wrong?
Regards
Have you tried nesting the RequestMapping? Something like this...
#Controller
#RequestMapping(value = "/home")
public class HomeController {
#RequestMapping(method = RequestMethod.GET)
public String showHomeMessage() {
return "home";
}
#RequestMapping(value = "/user", method = RequestMethod.GET)
public String welcomeMessage(){
return "user";
}
}
I'm not sure if you need to put a value on showHomeMessage (i.e. value="/").
After looking through this little example, I think your issue is tied to the fact that you are not specifying the #ResponseBody using the #Controller annotation. Whereas, if you use the #RequestController annotation simply implying a String type would be sufficient because it combines the use of #Controller and #ResponseBody
#Controller
#RequestMapping("/home/user")
public class UserController {
#RequestMapping(method = RequestMethod.GET)
public #ResponseBody String welcomeMessage(){
return "user";
}
}
The alternative to the same block would be...
#RestController
#RequestMapping("/home/user")
public class UserController {
#RequestMapping(method = RequestMethod.GET)
public String welcomeMessage(){
return "user";
}
}
Of course this little example doesnt demonstrate MediaType and so forth, but hopefully you get the idea.

Spring test No mapping found for HTTP request with URI [/accueil] in DispatcherServlet with name ''

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.

Default RequestMapping does not get invoked

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>

Tomcat/ApplicationContext not able to find out Filter class

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.

Spring don't see controller

I have a problem with my spring MVC app. My app don't see my controller when i try to pass data between spring controller and angular controller.
Spring configuration:
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"
version="3.0">
<display-name>PiManager</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
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:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
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/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.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-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd ">
<mvc:annotation-driven />
<context:component-scan base-package="org.inz.controller" />
<jpa:repositories base-package="org.inz.repositories"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
My services.js
PiManager.services.main = [ '$http', '$rootScope', '$state', function($http, $rootScope, $state) {
var self = this;
self.getTestEntity = function(id) {
return $http.get("/PiManager/index/"+id);
}
} ];
app.service('mainService', PiManager.services.main);
My controller.js
"use strict"
PiManager.controllers = {};
PiManager.controllers.main =
['mainService', '$scope', '$state', '$http', function(mainService, $scope, $state, $http) {
$scope.getTest = function(id) {
mainService.getTestEntity(id).then(function(response) {
$scope.testEntityPart = response;
});
}
}];
app.controller('mainController', PiManager.controllers.main);
My spring MainController
#Controller
#RequestMapping("/PiManager/")
public class MainController {
#Autowired
private TestEntityRepository testEntityRepository;
#RequestMapping(value = "/main")
public String index() {
return "/index.jsp";
}
#ResponseBody
#RequestMapping(value = "/index/{id}", method = RequestMethod.GET)
public List<TestEntity> getTestEntity(#PathVariable("id") Long id) {
return testEntityRepository.findById(id);
}
}
So when i type http://localhost:8080/PiManager/index/1 I got
GET http://localhost:8080/PiManager/index/1 404 (Not Found)
And i don't realy know what to do to make it work.
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

Categories

Resources