404 error in java spring mvc - java

I am building a Java Spring web application and getting a 404 error when running it from Eclipse, the manager section in tomcat shows the app as deployed and the console is not showing any error either.
Can anyone please help here and tell the missing links?
Dispatacher Servlet
Links for Spring beans here - removed to make it clean
<mvc:default-servlet-handler/>
<context:component-scan base-package="net.kzn.onlineshopping.controller"/>
<bean id ="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name ="prefix" value ="/WEB-INF/views/"/>
<property name ="suffix" value =".jsp"/>
</bean>
<!-- loading static resources -->
<mvc:annotation-driven/>
<mvc:resources location="/assets/" mapping="/resources/**"/>
</beans>
Page Controller
package net.kzn.onlineshopping.controller;
....Spring imports...
#Controller
public class PageController {
#RequestMapping(value= {"/","/home","/index"})
public ModelAndView index() {
ModelAndView mv = new ModelAndView("page");
mv.addObject("title","Home");
mv.addObject("userClickHome","true");
return mv;
}
#RequestMapping(value= "/about")
public ModelAndView about() {
ModelAndView mv = new ModelAndView("page");
mv.addObject("title","About us");
mv.addObject("userClickAbout","true");
return mv;
}
#RequestMapping(value= "/contact")
public ModelAndView contact() {
ModelAndView mv = new ModelAndView("page");
mv.addObject("title","Contact us");
mv.addObject("userClickContact","true");
return mv;
}
}
Code below for Web.xml file
<display-name>Archetype Created Web Application</display-name>
<!-- Configuring front Controller -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

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 : null pointer exception when calling service in controller

I am using pure xml in spring configuration. I have applicationContext.xml and servletContext.xml. In applicationContext.xml, I created the dao and service bean while in servletContext.xml, I created controller bean that references the service bean in applicationContext. Then in controller class, I have this code to initialize the bean
private PersonService personService
public void setPersonService(PersonService personService){
this.personService = personService;
}
When I call method in personService, Im getting a null pointer exception. I guess that the service bean is null. What am I doing wrong?
This is my beans xml
applicationContext.xml
<bean id="personDao" class="com.training.hibernate.dao.impl.PersonDaoImpl">
<constructor-arg>
<ref bean="sessionFactory"/>
</constructor-arg>
</bean>
<bean id="personService" class="com.training.hibernate.services.impl.PersonServiceImpl">
<constructor-arg>
<ref bean="personDao"/>
</constructor-arg>
</bean>
servletContext.xml
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean class="com.training.hibernate.controller.PersonController">
<property name="personService" ref="personService"/>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
This is my controller
public class PersonController extends MultiActionController {
private PersonService personService;
public void setPersonService(PersonService PersonService){
this.personService = personService;
}
public ModelAndView getAllPersons(HttpServletRequest request, HttpServletResponse response) throws Exception{
List<PersonDto> personDtos = personService.getAllPersons();
ModelAndView model = new ModelAndView("index");
model.addObject("persons",personDtos);
model.addObject("roles",personService.getRoles());
return model;
}
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
ModelAndView model = new ModelAndView("person");
return model;
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app 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"
version="2.4">
<display-name>Spring Web Application</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servletContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</web-app>

Spring MVC, tomcat url 404 error

I have problem with spring-mvc/tomcat, and more specifically with Url
When I'm trying to execute: http://localhost:8080/HelloWeb/index.html
WARNING: No mapping found for HTTP request with URI [/HelloWeb/index.html] in DispatcherServlet with name 'HelloWeb'
HelloWeb-servlet.xml:
<context:component-scan base-package="pl.solsoft.web"/>
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/pages"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true"/>
<property name="prefix" value=""/>
<property name="suffix" value=".ftl"/>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
StudentController:
#Controller
public class StudentController{
private static List<User> userList=new ArrayList<User>();
static {
userList.add(new User("Bill", "Gates"));
userList.add(new User("Kasia", "K"));
}
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String index (#ModelAttribute("model") ModelMap model){
model.addAttribute("userList", userList);
return "index";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(#ModelAttribute("user") User user){
if (null != user && null != user.getName()
&& null != user.getLastName() && !user.getName().isEmpty()
&& !user.getLastName().isEmpty()) {
synchronized (userList) {
userList.add(user);
}
}
return "redirect:index.html";
}
}
web.xml:
<display-name>HW</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
Thank U for all tips
What if you add .html to your RequestMappings e.g. #RequestMapping(value="/index.html")
In your web.xml, you've mapped the DispatcherServlet to handle requests matching *.html. But your StudentController is not mapped to handle such requests.
Modify the value in #RequestMapping to include .html extension.
#RequestMapping(value = "/index.html", method = RequestMethod.GET)
public String index (#ModelAttribute("model") ModelMap model){
......
return "index";
}
#RequestMapping(value = "/add.html", method = RequestMethod.POST)
public String add(#ModelAttribute("user") User user){
.....
return "redirect:index.html";
}
Now try to access your page by going to http://localhost:8080/HelloWeb/index.html
-----------Edit-----------------------------
Verify the Controller is getting initialized by Spring. To do that, create a no-arg constructor and try to print something to the console.
#Controller
public class StudentController{
public StudentController(){
System.out.println("Hey, I'm in StudentController");
}
}
I do not see <mvc:annotation-driven/>
in your servlet config. Can you add and check. Thanks.
If you are trying to deploy your HTML files as simple static files, you should configure them as such. Add this to your dispatcher servlet, making sure you have the proper namespace declared:
<mvc:resources mapping="*.html" location="/" />
You don't need a controller method to serve this file. If you want additional logic on the back-end, you can have your request to /index do its thing and then redirect to your file, or just convert index.html to a .jsp file. Right now, your controller is most likely trying to find a JSP view named index.html, which does not exist.

SpringMVC 3.2.4 Request method 'PUT' not supported

Just started working with Java and Spring, coming from a C# background and I am having trouble getting a 'PUT' request to work.
I am on Spring 3.2.4 running on Jetty 9.0.6.
I have a simple controller with the following method
#RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public ResponseEntity<String> update(#PathVariable Integer id, #RequestBody Employee employee) {
HttpHeaders headers = new HttpHeaders();
headers.set("content-location", "/api/employees/" + id);
return new ResponseEntity<>("", headers, HttpStatus.OK);
}
When this request is executed, I get the following error:
Oct 31, 2013 10:16:16 AM org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleHttpRequestMethodNotSupported
WARNING: Request method 'PUT' not supported
If I change the RequestMethod to 'POST' it works fine.
Does Spring support 'PUT' requests? How do I get it to recognize the 'PUT'
Joe
EDIT
Turns out I was being stupid. Affe clued me in when he mentioned the url.
I was accessing it like 'api/employees?id=32' when it should have been 'api/employees/32'
In the hopes this helps someone else, here is the web descriptor, the servlet and the controller.
Web Descriptor
<web-app 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'
version='3.0'>
<display-name>timesheet-app</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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 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-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd'>
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package='org.timesheets.web' />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean class='org.springframework.web.servlet.view.InternalResourceViewResolver'>
<property name='prefix' value='/WEB-INF/views/' />
<property name='suffix' value='.jsp' />
</bean>
</beans>
Controller
#Controller
#RequestMapping("/api/employees")
public class EmployeeController {
#RequestMapping(method = RequestMethod.GET)
public #ResponseBody List<Employee> get() {
List<Employee> employees = new ArrayList<>();
for(int i = 1; i <= 10; i++){
employees.add(new Employee(i, "Test " + i, "Department " + i));
}
return employees;
}
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public #ResponseBody Employee get(#PathVariable Integer id) {
return new Employee(1, "Test", "IT");
}
#RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> create(#RequestBody Employee employee) {
HttpHeaders headers = new HttpHeaders();
headers.set("content-location", "/api/employees/32");
return new ResponseEntity<>("", headers, HttpStatus.CREATED);
}
#RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public ResponseEntity<String> update(#PathVariable Integer id, #RequestBody Employee employee) {
HttpHeaders headers = new HttpHeaders();
headers.set("content-location", "/api/employees/" + id);
return new ResponseEntity<>("", headers, HttpStatus.OK);
}
}
The problem was as #Affe pointed out that it could not find the url in the mapping because I was requesting the wrong url!
I was accessing the url like '/api/employees?id=32' instead of '/api/employees/32', though I would have thought the parameter binding would still pick it up.

Spring MVC + Apache tiles, form validation and redirect

I have a problem with redirecting page.
Controller:
#Controller
#RequestMapping("/user")
public class UserController {
#RequestMapping(method = RequestMethod.POST)
public String processSubmit(#Valid User user,
BindingResult result) {
if (result.hasErrors()) {
return "userForm";
**It will show error - Could not resolve view with name 'userForm' in servlet with name 'dispatcher'**
return "redirect:user.htm";
**It will redirect page but without error messages**
} else {
**same problem here**
return "userResult";
}
}
#RequestMapping(method = RequestMethod.GET)
public ModelAndView initForm(ModelAndView model) {
User us = new User();
model.addObject("user", us);
return model;
}
}
dispatcher-servlet:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
web.xml:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
Without tiles is everything ok. But when I configure dispatcher to use tiles, redirecting dont work and I dont know how to fix it.
Solution:
I must return name of tile not the jsp file. Thanks to jerome.

Categories

Resources