Transfer data from Controller to Jsp addAttribute method in Spring MVC - spring-mvc

I create Spring MVC project like this.
This is Controller:
#Controller
public class HelloWorldController {
#RequestMapping("/hello")
public String doHello(Model model) {
model.addAttribute("message", "Hello Spring MVC");
return "helloworld";
}
}
And this is content of file "helloworld.jsp".
<body> <h1>${message }</h1> </body> // I don't know why I can't post full code
When i run URL "http://localhost:8080/HelloSpringMVC/hello", the result should be Hello Spring MVC but I got ${message }, what's going on?

Make sure you have javax expression language dependency in your project.

add <%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> to jsp file.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello ${message }
</h1>
</body>
</html>

try this:
#Controller
public class HelloWorldController {
#RequestMapping("/hello")
public ModelAndView doHello() {
ModelAndView model = new ModelAndView("helloworld");
model.addObject("message", "Hello Spring MVC");
return model;
}
}

Related

Spring Dispatcher Servlet causing issues when trying to load my CSS sytlesheets

When I load my JSP page home.jsp I include the stylesheet signIn.css. But something is happening where I get Failed to load resource: the server responded with a status of 404 (Not Found) for my stylesheet. I think my spring dispatcher servlet is looking for URI /customerPortal/signIn.css when my CSS file is stored at /customerPortal/src/main/webapp/WEB-INF/signIn.css (w/o using spring I have no issues). I think its something with getServletMappings where it is cutting off the file location.
My CSS page is in the exact same location as my home.jsp page. I also set up my SpringMvcInitializer class and MvcConfiguration class as I'm using Spring boot. I also have a home controller. I am not using spring-dispatcher-servlet.xml.
//MvcConfiguration.java
package Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import ShoppingCart.Cart;
#Configuration
#ComponentScan(basePackages="Controllers/")
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver getViewResolver()
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean
public Cart getCart(){
return new Cart();
}
}
//SpringMvcInitializer.java
package Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {MvcConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
//home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%#include file="header.jsp" %>
<link rel="stylesheet" href="/src/main/webapp/WEB-INF/signIn.css">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
</body
</html>
My jsp and css page are stored in
/customerPortal/src/main/webapp/WEB-INF/home.jsp
/customerPortal/src/main/webapp/WEB-INF/signIn.css
But on my eclipse console I get the following:
- DispatcherServlet with name 'dispatcher' processing GET request for [/customerPortal/signIn.css]
- Did not find handler method for [/signIn.css]
- No mapping found for HTTP request with URI [/customerPortal/signIn.css] in DispatcherServlet with name 'dispatcher'
And on my chrome console browser I get:
GET http://localhost:8035/customerPortal/signIn.css net::ERR_ABORTED 404 (Not Found)
Why is it looking for URI /customerPortal/signIn.css when my CSS file is stored at /customerPortal/src/main/webapp/WEB-INF/signIn.css ?
For your information, you can not directly access WEB-INF with URL, Java servlets will not allow it. moreover, do not place resources under WEB-INF
What should you do now?
Create a folder called, resources under webapp and then create a folder for css (resources/css). then place all css under css folder. and create another folder js and place all JavaScript files there.
then add this method to your MvcConfiguration class.
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
now you have your css inside the resources, then access it via
<link rel="stylesheet" href="resources/css/signIn.css" />
Solution for your current problem, but not recommend to put static resources under WEB-INF.
change your <link rel="stylesheet" href="/src/main/webapp/WEB-INF/signIn.css"> code to this
<style><%#include file="/WEB-INF/signIn.css"%></style>
best of luck...! Happy coding..!

Spring MVC not showing message from model

I wrote a Spring MVC 3.1.1 controller to do stuff then return showing "Done".
My controller:
#Controller
public class HomeController {
#RequestMapping(value = {"/"}, method = RequestMethod.GET)
public String home(Model model) {
return "home";
}
#RequestMapping(value = {"/dostuff"}, method = RequestMethod.GET)
public String doStuff(ModelMap model) {
doStuff();
model.addAttribute("message", "Done");
return "redirect:/";
}
}
My home.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html><body>
${message}
</body></html>
PROBLEM: When I load http://localhost/myapp/dostuff the page does not show "Done", it is just empty. Also, the URL becomes http://localhost/myapp/?message=Done instead of going back to a clean http://localhost/myapp/. What did I do wrong?

CS 1061 error on ASP.Net

im just start learning asp.net and encounter this error
i've tried many solution from google but still get this error (errr...)
Compiler Error Message: CS1061: 'Exercise1.Visitor' does not contain a definition for 'Name' and no extension method 'Name' accepting a first argument of type 'Exercise1.Visitor' could be found (are you missing a using directive or an assembly reference?)
im using VS2012 with 4.5 Net
this is my code
Model
namespace Exercise1.Models
{
public class Visitor
{
public String Name
{
set;
get;
}
}
}
Controller
namespace Exercise1.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Visitor data)
{
ViewBag.Message= "Hi my name is" + data.Name;
return View();
}
}
}
View
#{
Layout = null;
}
#model Exercise1.Visitor
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
</head>
<body>
<div>
#using(Html.BeginForm())
{
<p>
#Html.LabelFor(m=>m.Name);
</p>
}
</div>
</body>
</html>
btw, this is my first question hehe
Change model to:
#using Exercise1.Models
#model Exercise1.Models.Visitor
Do you have another Vistor class in your project? it's saying Exercise1.Visitor when it should be complaining about Exercise1.Models.Visitor
make sure you're referencing Exercise1.Models.Visitor

addError not returning error message

I am trying a login example. In the controller class i am using addError method to display error. When i enter invalid entries it goes to the error page, but doesn't display the message.Success page works fine.
LoginController.java
#Controller
public class LoginController {
#Autowired
private LoginService loginService;
#RequestMapping("login.html")
public String toLogin(Model model) {
Login login = new Login();
model.addAttribute("login",login);
return "login";
}
#RequestMapping(value ="login.html", method = RequestMethod.POST)
public ModelAndView doLogin(#Valid #ModelAttribute ("login") Login login,
BindingResult bindingresult ) {
ModelAndView view = new ModelAndView("login");
if(!bindingresult.hasErrors()){
if(!loginService.authenticateUser(login)){
bindingresult.addError(new ObjectError("invalid", "Invalid Credentials"));
return new ModelAndView("error");
}
else{
view.setViewName("success");
}
}
return view;
}
}
error.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>LoginExample2-Error</title>
</head>
<body>
<table>
<tr>
<td>Retry</td>
</tr>
</table>
</body>
</html>

Using DisplayForModel with MVC4 and the ASPX View Engine

Using ASP.NET MVC4 (.NET 4, C#) on MSVC 2010 SP1, I've noticed that I can pass a class model to a view using Razor and display the model using DisplayModelFor & EditorForModel but when I try to do the same using the ASPX view engine it doesn't work. Why is that? Code snippets from my test project below. Thanks.
My Controller:
namespace MvcApplication1.Controllers
{
public class TestController : Controller
{
public ActionResult Index()
{
TestModelClass c = new TestModelClass();
c.MyInt = 999;
return View(c);
}
}
My Model:
namespace MvcApplication1.Models
{
public class TestModelClass
{
public int MyInt { get; set; }
}
}
My View:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.TestModelClass>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<%Html.DisplayForModel(); %>
</div>
</body>
</html>
Alternate Razor (Works):
#model MvcApplication1.Models.TestModelClass
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#Html.DisplayForModel()
Successful output from Razor version:
Index
MyInt
999
You are missing a :.
The correct syntax should be
<%: Html.DisplayForModel() %>

Resources