#RequestAttribute in springMVC is not binding Object of Entitiy class [duplicate] - java

This question already has an answer here:
Spring MVC Missing request attribute
(1 answer)
Closed 3 years ago.
I am new to spring,i am trying to develop basic java project with spring MVC using Annotations,i am trying to create an object of my Entity class(Information.java) in the controller using #RequestAttribute and send it to the view,my code as follows
My controller class
package org.practice.spring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView
#Controller()
public class HelloController
{
#RequestMapping("/hello")
public ModelAndView helloWorld(#RequestAttribute Information userInfo)
{
ModelAndView model = new ModelAndView("hello");
model.addObject("firstname", userInfo.getFirstName());
model.addObject("lastname", userInfo.getLastName());
return model;
}
#RequestMapping("/")
public ModelAndView homePage() {
ModelAndView model = new ModelAndView("index", "info", new Information());
return model;
}
}
My Entity class
package org.practice.spring;
public class Information {
private String firstName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
private String lastName;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>Hello,Please Enter Name</h3>
<form:form action="hello" modelAttribute="info">
First Name:<form:input path="firstName"/><br>
Last Name:<form:input path="lastName"/><br>
<input type="submit" value="Submit">
</form:form>
</body>
</html>
hello.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
Hello World
<h3>Hello ${firstName} ${lastName}</h3>
</body>
</html>
and Tomcat is giving me this
org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver logException
WARNING: Resolved [org.springframework.web.bind.ServletRequestBindingException: Missing request attribute 'userInfo' of type Information]
When i run the application browser is giving me this
HTTP Status 400 – Bad Request Type Status Report
Message Missing request attribute 'userInfo' of type Information
Description The server cannot or will not process the request due to
something that is perceived to be a client error (e.g., malformed
request syntax, invalid request message framing, or deceptive request
routing).
So far i dont have any syntax errors in my code,but my code is not working,i struck here for almost 2 days,did alot of googling but no luck,any help would be appreciated.

You can try this: #RequestAttribute(name="info").

Related

How to handle Dot Char in Url Mapping

I have a spring boot project but, I have some links from past and users are linking url on their websites and I cannot request client to change their urls. I am trying to navigate jsp link to React app. I have just found a solution but I got stuck.
Here is the link example: abc/Dashboard.jsp#/company/88
I am handling abc/Dashbord but I cannot handle abc/Dasboard.jsp to navigate a jsp page.
There is my handling endpoint;
#Controller
#RequestMapping("")
public class DashboardController {
#GetMapping("/Dashboard")
public String viewBooks() {
return "view-dashboard";
}
}
#GetMapping("/Dashboard.jsp")
public String viewBooks2() {
return "view-dashboard";
}
My Jsp Page
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>e-ŞİRKET</title>
</head>
<body>
</body>
</html>
<script>
const url = window.location.href.split('/')
if(url && url.length > 0) {
const id = url[url.length -1]
if(id) {
window.location.replace(window.location.origin + '?page=company&company=' + id)
}
}
</script>
It is working for abc/Dashboard#company/88 but;
how I can handle abc/Dashboard.jsp#/company/123. I am getting 404.

Followed Spring MVC Guide, But Template Literal Values Won't Display Correctly?

So I was following a guide on how to create a Spring MVC, but an issue I'm running into is that it seems to not display the template literal values correctly.
Here's the guide and the code:
https://www.youtube.com/watch?v=7ArHUCL_RRc
https://github.com/RameshMF/spring-mvc-tutorial/tree/master/springmvc5-helloworld-exmaple
Essentially, I'm following it one to one, creating a model, controller, and config that should display the message and the current date and time. However, it does not display template literals correctly, showing them as literally ${helloWorld.message}. I'm not sure if it's an issue of the helloWorld not being created, or of it's something else. Any tips?
helloworld.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring 5 MVC - Hello World Example | javaguides.net</title>
</head>
<body>
<h2>${helloWorld.message}</h2>
<h4>Server date time is : ${helloWorld.dateTime}</h4>
</body>
</html>
HelloWorldController.java
package net.te549.springmvc.controller;
import java.time.LocalDateTime;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.ui.Model;
import net.te549.springmvc.model.HelloWorld;
#Controller
public class HelloWorldController {
#RequestMapping("/helloworld")
public String handler(Model model) {
HelloWorld helloWorld = new HelloWorld();
helloWorld.setMessage("Hello World from TE549!!!");
helloWorld.setDateTime(LocalDateTime.now().toString());
model.addAttribute("helloWorld", helloWorld);
return "helloworld";
}
}
HelloWorld.java
package net.te549.springmvc.model;
public class HelloWorld {
private String message;
private String dateTime;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message=message;
}
public String getDateTime() {
return dateTime;
}
public void setDateTime(String dateTime) {
this.dateTime=dateTime;
}
}
(If I need to show more code, let me know)
Kindly Check if there is any errors/exception in logs if not Try Adding this in your JSP:
<%#page isELIgnored="false"%>

c:foreach doesn't print objects

I'm extremely new to JSP. Anyway, I'm trying to print every object in a list using c:foreach but it does not work and I can't figure out why. I've already checked out similar issues but nothing has solved my problem.
<h2>
Your account information:
<%
LinkedList<BankAccount> accounts = null;
accounts = account1.getAccountList();
request.setAttribute("accounts", account1.getAccountList());
%>
</h2>
<c:foreach items="${accounts}" var="acct">
<p>${acct.accountName}</p><br/>
<p>$${acct.AccountBalance}</p><br/>
</c:foreach>
<TD valign="top"><B><%=accounts.get(0).accountName%></b><br>
<TD valign="top"><b>$<%=accounts.get(0).AccountBalance%></b></br>
</br></br>
<TD valign="top"><b><%=accounts.get(1).accountName%></b><br>
<TD valign="top"><b>$<%=accounts.get(1).AccountBalance%></b></br>
The bottom code works --- accounts.get(0), etc. But I can't use this because if I add data to the database then I have to add more code every time.
Thanks for the help.
You didn't provide info about your BankAccount class, therefore i would make an assumption:
package testingThings.EL.linkedlist;
public class BankAccount {
protected String accountName;
protected double accountBalance;
public BankAccount(String accountName, double accountBalance) {
this.accountName = accountName;
this.accountBalance = accountBalance;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public double getAccountBalance() {
return accountBalance;
}
public void setAccountBalance(double accountBalance) {
this.accountBalance = accountBalance;
}
}
I changed AccountBalance accountBalance to stick to the conventions.
In your JSP you need the line that LeHill mentioned.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
Don't forget the protocol: http://
The JSP:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="testingThings.EL.linkedlist.BankAccount"%>
<%# page import="java.util.LinkedList"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
LinkedList<BankAccount> accounts = new LinkedList<BankAccount>();
accounts.add(new BankAccount("acc1", 1000.00));
accounts.add(new BankAccount("acc2", 2000.00));
pageContext.setAttribute("accounts", accounts);
%>
<c:forEach items="${accounts}" var="acct">
<p>${acct.accountName}</p>
<br />
<p>${acct.accountBalance}</p>
<br />
</c:forEach>
</body>
</html>
The Output in Browser:
acc1
1000.0
acc2
2000.0
It looks like you don't have getters and setters.
Your scriptlet has the attribute name as "accountName".
JSTL expects "get" or "is" as the beggining of the beans method name.
you can't call the attribute directly. You have to use getter methods.
if you created a method called "getAccountName" it should work.

JSP output plain text in Web Browser

I am using Eclipse, Spring MVC, Maven and Tomcat. This index.jsp displays exactly as show below in the web browser. It is not rendering properly.
Any idea what is wrong?
index.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>Insert title here</title>
</head>
<body>
<h1>Index</h1>
</body>
</html>
#Controller
public class HelloController {
#RequestMapping("/greeting")
public String sayHello() {
System.out.println("Greeting");
return "hello";
}
#RequestMapping("/")
public String index() {
System.out.println("Index page");
return "index";
}
}
A controller has a GET and a POST RequestMethod.However at a quick glance you need to change #RequestMapping("/greeting") to #RequestMapping(value = "/greeting") just for starters. By default your jsp file should be in /src/main/webapp/WEB-INF/views (Spring MVC Starter Project)
When you return a String - Spring MVC will look for a jsp with that .jsp. So in this example you just want to have greeting.jsp
#Controller
public class GreetingController {
/**
* GET
*/
#RequestMapping(value = "/greeting", method = RequestMethod.GET)
public String handleRequest() {
// This will be used when you GET the URL
return "greeting";
}
/**
* POST
*/
#RequestMapping(value = "/greeting", method = RequestMethod.POST)
public String processSubmit(){
// This will be used when you POST to the URL
//TODO Do something here and it will put you right back in your page
return "greeting";
}
}
Go ahead and comment if you have any other questions. Also check my account for my other example Neither BindingResult nor plain target object for bean name available as request attr
Hope this helps. Good Luck!
Just a note Spring has more RequestMethod's but GET and POST are the most used and easiest to understand.
It could be that the only thing you're missing is to
Right click on the jsp page and click RUN AS, then RUN ON SERVER.

How do I reset a ModelAttribute in Spring 3?

I just started with Spring MVC so it's probably a rookie mistake.
The ModelAttribute is reused every request. How can I make sure every POST starts with a clean object?
My controller (MyController.java):
#Controller
public class MyController {
#RequestMapping(method = RequestMethod.POST)
public String processChoice(#ModelAttribute("myData") MyData myData, BindingResult bindingResult) {
System.out.println("POST: myData = " + myData);
return "redirect:/myview?choice=" + myData.getChoice();
}
#RequestMapping(method = RequestMethod.GET)
public String displayChoice(#RequestParam(required = false) String choice, Model model) {
System.out.println("GET: Choice = " + choice);
model.addAttribute("myData", new MyData(choice));
return "myview";
}
}
My view (myview.jsp):
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!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=UTF-8">
<title>Spring Tests</title>
</head>
<body>
<form:form modelAttribute="myData" method="POST">
<form:select path="choice">
<option></option>
<option value="one">One</option>
<option value="two">Two</option>
</form:select>
<input type="submit" value="Choose"/>
</form:form>
<c:if test="${not empty myData.choice}">Choice = ${myData.choice}</c:if>
<c:if test="${empty myData.choice}">No choice</c:if>
</body>
</html>
Successive clicks on the "Choose" button appends the chosen values instead of just POST-ing the current one:
GET: Choice = null
POST: myData = MyData [choice=two]
GET: Choice = two
POST: myData = MyData [choice=two,one]
GET: Choice = two,one
POST: myData = MyData [choice=two,one,]
GET: Choice = two,one,
POST: myData = MyData [choice=two,one,,one]
GET: Choice = two,one,,one
Add this into your controller:
#ModelAttribute("myData")
public MyData getMyData() {
return new MyData();
}

Categories