I am new to Spring and was trying to setup a basic Web App using the Spring Framework. But I am facing an issue where the message variables are not being passed to the view — the jsp doesn’t show the messages.
Following is my code –
Controller.java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HomeController {
@RequestMapping(method=RequestMethod.GET, value="/")
public String index(){
ModelAndView mav = new ModelAndView();
mav.setViewName("index");
String message = new String("Hello Welcome - Please click to login");
System.out.println(message);
mav.addObject("message", message);
return "index";
}
index.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>Login</title>
</head>
<body>
<c:url value="login" var="somevar" />
<h1>Click here to </h1> <a href= "${somevar}">${1+1}</a>
<c:out value="${message}"/>
</body>
</html>
The evaluation works all fine – but the string for the variable ‘message’s comes as empty.
Am I missing something? Any guidance would be much appreciated.
Your
index()controller method is returning aString, rather than aModelAndViewobject. Try: