Search code examples
springjspspring-mvcjsp-tags

Link to / goes to Apache root


Here is the controller :

@Controller
public class HomeController {

    @Autowired
    private UserDAO userDao;

    @RequestMapping("/")
    public ModelAndView accueil() throws Exception {
        List<User> listUsers = userDao.list();
        ModelAndView model = new ModelAndView("UserList");
        model.addObject("userList", listUsers);
        return model;
    }

    @RequestMapping(value = "/new", method = RequestMethod.GET)
    public ModelAndView newUser() {
        ModelAndView model = new ModelAndView("UserForm");
        model.addObject("user", new User());
        return model;      
    }

    ...

}

Inside a jsp I placed a button inside a link so that when clicked then the action "accueil" in the controller would be called :

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
...
<tr>
                <td>
                    <input type="submit" value="Save">
                </td>
                <td><a href="/"><input type="button" value="Annuler" /></a></td>
            </tr>        
            </form:form>
...

The problem is that when I click the "Annuler" button then I reach to localhost:8080 ! So how to write correctly the link target ?


Solution

  • If the application is not the root application, you need to prepend the context path of the application to the URLs.

    Use

    href="${pageContext.request.contextPath}/"
    

    or add the JSTL core library to your JSP, and use

    href="<c:url value='/' />"