Spring MVC, tomcat url 404 error - java

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.

Related

404 error in java spring mvc

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>

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>

Interceptor preHandle() not redirecting to login.html

I have a spring application. I introduced a sessionInterceptor to prevent direct access to index.jsp. If the user is not logged in it shouldn't be able to access index.jsp and should be redirected to login.html. The code is hitting the preHandle() method and running all the code but after return false it's not redirecting to login.html. What's wrong? Any gurus out there for help? Thanks in advance.
My preHandle() in SessionInterceptor.java is:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
// if displaying the home page, make sure the user is reloaded.
if (request.getRequestURI().endsWith("login.html")) {
session.removeAttribute("isUserLoggedIn");
}
if (session.getAttribute("isUserLoggedIn") == null && !request.getRequestURI().endsWith("login")) {
response.sendRedirect(request.getContextPath() + "/login.html");
return false;
}
return true;
}
I have tried the following as well but all in vain.
RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/login.html");
dispatcher.forward(request, response);
My dispatcher-servlet.xml settings are:
<bean id="sessionInterceptor" class="com.xxx.xxx.xxx.SessionInterceptor" />
<bean id="annotationMapper" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<ref bean="sessionInterceptor" />
</list>
</property>
</bean>
<!-- Configures Handler Interceptors -->
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.xxx.xxx.xxx.SessionInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
The web.xml is:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
you can try redirecting to a logical path that will be catched from a controller
Try
response.sendRedirect("/NotLogged");
And then create a function like this:
#RequestMapping(value = {"/NotLogged"}, method = RequestMethod.GET)
public String notLogged() {
return "login.html";
}
I hope it will work for you!
When i use return false, i take "Error: Exceeded maxRedirects. Probably stuck in a redirect loop http://localhost:8080/api/login"
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if(true){
response.sendRedirect("/api/login");
return false;
}
return true;
}

Change Name of a .JSP file

I am developing a simple spring application. I have a few jsps and I would like to change the name and the URL of a jsp. I changed the controller:
#RequestMapping(value = "/simpleForm.html", method = RequestMethod.GET)
public void simpleForm(Model model) {
model.addAttribute(new User());
}
to
#RequestMapping(value = "/newName.html", method = RequestMethod.GET)
public void simpleForm(Model model) {
model.addAttribute(new User());
}
and the name of the old simpleForm.jsp to newName.jsp user is a class I use in the form in simpleform.jsp
I couldn't make it work. I am getting 404 that simpleform.jsp is not found. I am pretty stuck.
Edit: My view resolver tags:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
My url pattern is like:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/forms/*</url-pattern>
</servlet-mapping>
I've found out that all of the links are getting the same error ()
resource not available. Even the ones that I didn't change the name
of.
I also tried directly starting from newName.jsp. Still the same error!
change:
#RequestMapping(value = "/newName.html", method = RequestMethod.GET)
to:
#RequestMapping(value = "/newName.jsp", method = RequestMethod.GET)
Double-check you still have the #Controller annotation on the class. I've seen 404s when has been accidentally deleted.
Try changing it to
#RequestMapping(value = "/newName.html", method = RequestMethod.GET)
public String simpleForm(Model model) {
model.addAttribute(new User());
return "newName"; // returning the desired view
}
And make sure you have defined viewResolver accordingly like
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
Change prefix as per your application structure.It will take the view (String returned by controller) and will add prefix and suffix. So the view resolved will be /WEB-INF/jsp/newName.jsp.
A 404 error is an HTTP status code that means that the page you were trying to reach on a website couldn't be found on their server.
As I can see, your suffix is .jsp. So try this (if there is any newName.jsp in the WebContent)
#RequestMapping(value = "/newName", method = RequestMethod.GET)
public void simpleForm(Model model) {
model.addAttribute(new User());
}
It should work
If you try this URL
http://localhost:<port>/AppNAme/forms/newName.html
and your controller is
#RequestMapping(value = "/newName.html", method = RequestMethod.GET)
public ModelAndView simpleForm(Model model) {
model.addAttribute(new User());
ModelAndView mv = new ModelAndView("jspViewName");
return mv;
}
The forward slash is missing in the prefix of your ViewResolver. This should fix your 404. Give it a shot.
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>

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