Java - HTTP Status 404 – Not Found - java

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.

Related

Properly configure dispatcher-servlet, applicationContext and web.xml

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>

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.

Error creating bean with name 'userServicesDao': Unsatisfied dependency expressed through field 'connectionPool';

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.

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>

Request resource not found status 404

package com.test.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.test.dao.UserDAOImpl;
import com.test.model.User;
#Controller
#RequestMapping("/service/user/")
public class SpringRestController {
UserDAOImpl userDAOImpl=new UserDAOImpl();
#RequestMapping(value = "/{id}", method = RequestMethod.GET,headers="Accept=application/json")
public User getUser(#PathVariable int id) {
User user=userDAOImpl.getUserById(id);
return user;
}
#RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
public List<User> getAllUsers() {
List<User> users=userDAOImpl.getAllUsers();
return users;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>sample</display-name>
<servlet><servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
url
localhost:8080/sample/service/user/
I am getting this error please help me to resolve this error.I am using spring json rest. This error mostly comes at the time of giving request.

Categories

Resources