DropDownlist how to load the data using Spring boot Mysql - spring

i am beginner of spring boot and mysql. i need to load DropDownList. i don't know how to load them.what tried so far i attached below.i want load the student name on the dropdown.
index.html- DropDown load
<select class="form-control" name="example" id="example">
<option value="0">ALL</option>
<option th:each="Student : ${allStudents}"
th:value="${Student.id}"
th:selected="${Student.isSelected(lastselected)}"
th:text="${Student.studentname}">
</option>
</select>
Student Class
package com.example.StudentCrud.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Student {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String studentname;
private String course;
private int fee;
public Student() {
}
public Student(Long id, String studentname, String course, int fee) {
this.id = id;
this.studentname = studentname;
this.course = course;
this.fee = fee;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public int getFee() {
return fee;
}
public void setFee(int fee) {
this.fee = fee;
}
}
Contorller i wrote like this. i stuck with this area how to get the Student names only
#ModelAttribute("allStudent")
public List<Student> allUsers() {
List<Student> userList= service.listAll();
return userList;
}

Here, I'm using <form:select /> , <form:option /> and <form:options /> tags to render HTML dropdown box. And <c:forEach /> for loop each student.
Don't forget to import below taglib to jsp.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
For example, POST request path is /students. And modelAttribute="studentForm" will be used to bind Student POJO.
Index.jsp
<form:form modelAttribute="studentForm"
action="${pageContext.request.contextPath}/students" method="POST">
<form:select path="studentName">
<form:option value="NONE" label="Select" />
<c:forEach var="student" items="${allStudents}">
<form:option value="${student.id}" label="${student.studentName}"/>
</c:forEach>
</form:select>
</form:form>
By the way, I used camelCase for studentName.
Supposed service.listAll() works fine. When GET request /students is called -
Controller be like
#ModelAttribute(name = "studentForm")
public Student setUp() {
return new Student();
}
#GetMapping
public String list(Model model) {
List<Student> students = service.listAll();
// add to model
model.addAttribute("allStudent", students);
// view
return "index";
}
Method level #ModelAttribute will be invoked before any other method in controller. To use studentForm model attribute in form, we need to initialize first. You can do it without using method level #ModelAttribute.

Related

Spring MVC Form not taking object path

Error shown is Bean property 'emergencyComplaint.emergencyComplaint' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
The getters and setters have the same return type, still it is showing this error.
JSP Page
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CRS | Kolkata</title>
</head>
<body>
<div>
<h1>Lodge an Emergency Complaint Now</h1>
<form:form action="" method="post" modelAttribute="people">
<form:label
path="emergencyComplaint.emergencyComplaint"
for="emergencyComplaint"
>
Emergency Complaint
</form:label>
<form:input
type="text"
name="emergencyComplaint"
id="emergencyComplaint"
path="emergencyComplaint.emergencyComplaint"
/>
<form:label
path="emergencyComplaint.status"
for="emergencyComplaintStatus"
>Status</form:label
>
<form:input
type="text"
name="emergencyComplaintStatus"
id="emergencyComplaintStatus"
path="emergencyComplaint.status"
></form:input>
<form:label path="name" for="name">Name</form:label>
<form:input path="name" type="text" name="name" id="name" />
<form:label path="phoneNumber" for="phoneNumber"
>Phone Number</form:label
>
<form:input
path="phoneNumber"
type="text"
name="phoneNumber"
id="phoneNumber"
/>
<button type="submit">Lodge</button>
</form:form>
</div>
</body>
</html>
Model Class
package com.naha.crimereportingsystem.people;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import com.naha.crimereportingsystem.emergencyComplaint.EmergencyComplaint;
#Entity
public class People {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String phoneNumber;
#OneToMany(targetEntity = EmergencyComplaint.class, cascade = CascadeType.ALL)
private List<EmergencyComplaint> emergencyComplaint;
public People() {
}
public People(long id, String name, String phoneNumber) {
this.id = id;
this.name = name;
this.phoneNumber = phoneNumber;
this.emergencyComplaint = (List<EmergencyComplaint>) new EmergencyComplaint();
}
public List<EmergencyComplaint> getEmergencyComplaint() {
return emergencyComplaint;
}
public void setEmergencyComplaint(List<EmergencyComplaint> emergencyComplaint) {
this.emergencyComplaint = emergencyComplaint;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setName(final String name) {
this.name = name;
}
}
Mapped Other Model Class
package com.naha.crimereportingsystem.emergencyComplaint;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class EmergencyComplaint {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
long id;
private String emergencyComplaint;
private String status;
public String getEmergencyComplaint() {
return emergencyComplaint;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public void setEmergencyComplaint(String emergencyComplaint) {
this.emergencyComplaint = emergencyComplaint;
}
public EmergencyComplaint(long id, String emergencyComplaint, String status) {
this.id = id;
this.emergencyComplaint = emergencyComplaint;
this.status = status;
}
public EmergencyComplaint(String emergencyComplaint, String status) {
this.emergencyComplaint = emergencyComplaint;
this.status = status;
}
public EmergencyComplaint() {
}
}
This is a valid error. Take a close look at your Entity and your modelAttribute. There is no such thing emergencyComplaint.emergencyComplaint.
So, instead of:
<form:input type="text" name="emergencyComplaint" id="emergencyComplaint" path="emergencyComplaint.emergencyComplaint" />
Try this:
<form:input type="text" name="emergencyComplaint" id="emergencyComplaint" path="emergencyComplaint" />
I do not have OneToMany example handy but I think you are smart enough to identify the issue by now while reading this. If not then to get an idea, take a look at this and this.

how do I pass the selected parameters in the checkbox from one jsp page to another jsp page?

I have to make the switch to selected values ​​within some checkboxes in a jsp page but after the selection and after pressing the "Send" button, I generate this error with the following description: HTTP Status 400: The request sent by the client was syntactically incorrect.
Where am I wrong?
TaskController.java
#RequestMapping(value="/newTask", method = RequestMethod.GET)
public String task(#ModelAttribute Task task, Model model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String s = auth.getName();
Student student = studentFacade.retrieveUser(s);
List<Job> jobs = new ArrayList<>();
if(!(auth instanceof AnonymousAuthenticationToken)) {
jobs = facadeJob.retriveAlljobs();
model.addAttribute("job", getMathRandomList(jobs));
model.addAttribute("image", imageFacade.retriveAllImages());
List<Image> img = imageFacade.retriveAllImages();
task.setImages(img);
task.setStudent(student);
taskFacade.addTask(task);
List<Long> images = new ArrayList<>();
for(Image i : img)
images.add(i.getId());
model.addAttribute("images", images);
}
return "users/newTask";
}
#RequestMapping(value="/taskRecap", method = RequestMethod.POST)
public String taskRecap(#ModelAttribute Task task, Model model,BindingResult result) {
model.addAttribute("task", task);
return "users/taskRecap";
}
newTask.jsp
<form:form method="post" action="taskRecap" modelAttribute="task" name="form">
<form:checkboxes path="images" items="${images}" value="yes" />
<td><input type="submit" value="Send" /></td>
</form:form>
taskRecap.jsp Immages
<c:forEach var="image" items="${task.images}">
<c:out value="${image.id}" />
</c:forEach>
Task.java
#Entity
public class Task {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne
private Student student;
#ManyToMany
List<Image> images;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Task() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Task(Long id, Student student, List<Image> images) {
super();
this.id = id;
this.student = student;
this.images = images;
}
public List<Image> getImages() {
return images;
}
public void setImages(List<Image> images) {
this.images = images;
}
}
Using Query parameter
<a href="edit.jsp?Name=${user.name}" />
Using Hidden variable .
<form method="post" action="update.jsp">
<input type="hidden" name="Name" value="${user.id}">
if you use either of the first 2 methods you can access your value like this:
String userid = session.getParameter("Name");
you can send Using Session object.
session.setAttribute("Name", UserName);
These values will now be available from any jsp as long as your session is still active.
if you use the third option you can access your value like this:
String userid = session.getAttribute("Name");

Spring MVC test failure

I'm writing simple integration tests for my app using the Spring MVC Test framework. I have two basic test cases:
The Add link form is filled in correctly (the URL and optional description input fields are entered) and a link is added to a database via POST and then the client is redirected to the /link URL.
The Add link form is empty, so the /links/create view is rendered and form errors from BindingResult are presented.
The testAddLink() test passes successfully, but the problem occurs with the testAddEmptyLink() test method.
In this test, the 'links/create' view should be rendered and I should get a 200 status code once the expression
result.hasErrors()
is true.
However, I'm getting a 302 response, which should be sent when there are no errors in the form (the URL has been set correctly)
It seems the test method testAddEmptyLink() cannot deal with form errors with BindingResult.
Do you have any ideas what could be the cause it cannot deal with form errors?
Thanks in advance.
Link Entity
#Entity
#Table(name = "links")
public class Link {
#Id #GeneratedValue
private Integer ID;
#Column(name = "url") #NotNull #NotEmpty #URL
private String URL;
private String description;
#Column(name="created_at", nullable = false)
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private LocalDateTime createdAt;
#Column(name="updated_at", nullable = true)
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private LocalDateTime updatedAt;
#ManyToOne
#JoinColumn(name = "category_id")
private Category category;
public Integer getID() {
return ID;
}
public void setID(Integer ID) {
this.ID = ID;
}
public String getURL() {
return URL;
}
public void setURL(String URL) {
this.URL = URL;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdateddAt() {
return updatedAt;
}
public void setUpdateddAt(LocalDateTime updateddAt) {
this.updatedAt = updateddAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
LinkController
#Controller
public class LinkController {
#Autowired(required = true) #Qualifier(value = "linkService")
private LinkService linkService;
#Autowired
private CategoryService categoryService;
#RequestMapping(value = "/links")
public String getLinks(Model model) {
model.addAttribute("results", linkService.getLinks());
return "links/index";
}
#RequestMapping(value = "/links/create", method = RequestMethod.GET)
public ModelAndView showLinkForm() {
ModelAndView model = new ModelAndView("links/create");
model.addObject("link", new Link());
model.addObject("categories", categoryService.getCategories());
return model;
}
#RequestMapping(value = "/links/create", method = RequestMethod.POST)
public String addLink(#Valid #ModelAttribute("link") Link link, BindingResult result, Model model) {
if (result.hasErrors()) {
model.addAttribute("categories", categoryService.getCategories());
return "links/create";
}
linkService.addLink(link);
return "redirect:/links";
}
}
LinkControllerTest
#ContextConfiguration(classes = {AppInitializer.class})
#RunWith(SpringJUnit4ClassRunner.class)
public class LinkControllerTest {
#Mock
private LinkService linkService;
#InjectMocks
private LinkController linkController;
private MockMvc mockMvc;
#Before
public void setUp() {
// Process mock annotations
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(linkController).build();
}
#Test
public void testAddLink() throws Exception {
mockMvc.perform(post("/links/create")
.param("URL", "http://test.com")
.param("description", "Lorem Ipsum")
.param("category.ID", "1"))
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/links"));
}
#Test
public void testAddEmptyLink() throws Exception {
mockMvc.perform(post("/links/create")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.sessionAttr("link", new Link())
)
.andExpect(status().isOk())
.andExpect(view().name("links/create"))
.andExpect(forwardedUrl("/WEB-INF/views/links/create.jsp"))
.andExpect(model().attributeHasFieldErrors("link", "URL", "description"))
.andExpect(model().attribute("link", hasProperty("URL", isEmptyOrNullString())))
.andExpect(model().attribute("link", hasProperty("description", isEmptyOrNullString())));
}
}
create.jsp (View)
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<title>Create Category</title>
</head>
<body>
<form:form action="" modelAttribute="category">
<div>
<form:label path="name">Name</form:label>
<form:input path="name" />
<form:errors path="name" cssClass="error"></form:errors>
</div>
<div>
<form:label path="description">Description</form:label>
<form:input path="description" />
<form:errors path="description" cssClass="error"></form:errors>
</div>
<div>
<input type="submit" value="Create Category">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</div>
</form:form>
</body>
</html>

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'search' available as request attribute

I'm new to Spring MVC and I have an error with a form validation and I don't know why.
This is the model:
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;
import org.springframework.stereotype.Component;
#Component
public class Search implements Serializable {
#Size(max = 20)
private String userInput;
#Size(max = 10)
private String ascending;
#Size(max = 10)
private String descending;
#Temporal(TemporalType.DATE)
private Date fromDate;
#Temporal(TemporalType.DATE)
private Date toDate;
#Size(max=100)
private String genres;
public String getGenres() {
return genres;
}
public void setGenres(String genres) {
this.genres = genres;
}
public String getUserInput() {
return userInput;
}
public void setUserInput(String userInput) {
this.userInput = userInput;
}
public Date getFromDate() {
return fromDate;
}
public void setFromDate(Date fromDate) {
this.fromDate = fromDate;
}
public Date getToDate() {
return toDate;
}
public void setToDate(Date toDate) {
this.toDate = toDate;
}
}
Here is the form:
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<sf:form action="/newSearch" method="post" modelAttribute="search">
<sf:input path="userInput" type="text" class="input_style" id="userInput" />
<button class="search_button"><img class="search_icon" src="resources/img/search/search_icon.png" /></button>
<sf:select id="genres" path="genres" multiple="multiple">
</sf:select>
<sf:input id="fromDate" path="fromDate" />
<sf:input id="toDate" path="toDate" type="text" />
<sf:input id="ascending" path="ascending" type="radio" checked="checked" />
<sf:input id="descending" path="descending" type="radio" />
</sf:form>
and here is the Controller:
#RequestMapping(value = "/newSearch", method = RequestMethod.POST)
public String getSearch(#Valid Search search, BindingResult result, Model m) {
if(result.hasErrors()) {
return "home";
}
System.out.println("----------------Search--------------------");
System.out.println(search.getGenres());
System.out.println(search.getUserInput());
return "search";
}
The error is:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'search' available as request attribute
Add #ModelAttribute("search") before #Valid making the method's signature look like
public String getSearch(#ModelAttribute("search") #Valid Search search, BindingResult result, Model m)
Also try
<sf:form action="/newSearch" method="post" commandName="search">
instead of
<sf:form action="/newSearch" method="post" modelAttribute="search">

javax.el.PropertyNotFoundException: Property 'name' not found on type java.lang.String [duplicate]

This question already has answers here:
c:forEach throws javax.el.PropertyNotFoundException: Property 'foo' not found on type java.lang.String
(3 answers)
Closed 7 years ago.
I'm getting the error above.
What i'm trying to do is write an app that takes in an unknown number of names, then prints them out on a new page. This is supposed to be for a bowling scoring app, but for now I just want to get a list of names. The idea is for each name to go into a player object, then in turn be stored in the players arraylist. If anyone can help, I would appreciate it.
This is my controller code:
package multiplayergame;
import java.util.ArrayList;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
#Controller
#SessionAttributes
public class MultiplayerController {
int score;
int roll;
Game game = new Game();
GameProperties gameProps = new GameProperties();
int playerNo = 0;
ArrayList<PlayerGame> players = new ArrayList<>();
PlayerGame player;
#RequestMapping(value = "/home", method = RequestMethod.GET)
public ModelAndView home() {
return new ModelAndView("home", "command", gameProps);
}
#RequestMapping(value = "/nextName", method = { RequestMethod.POST, RequestMethod.GET})
public ModelAndView homeNext(MContact mcontact, BindingResult result) {
player = new PlayerGame();
player.setName(mcontact.getName());
players.add(player);
gameProps.setPlayers(players);
playerNo++;
return new ModelAndView("home", "command", gameProps);
}
#RequestMapping(value = "/test", method = RequestMethod.POST)
public ModelAndView playNext(GameProperties gameProps2, ModelMap model) {
model.addAttribute("players", gameProps.getPlayers());
model.addAttribute("name", gameProps.getPlayers().get(playerNo).getName());
return new ModelAndView("test", "players", gameProps2);
}
}
This holds details for each player:
package multiplayergame;
public class PlayerGame {
private int score;
private int pins;
private String name;
private int roll;
private int nOfPlayers;
private int playerNo;
Game game = new Game();
public Game getGame() {
return game;
}
public void setGame(Game game) {
this.game = game;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getPins() {
return pins;
}
public void setPins(int pins) {
this.pins = pins;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRoll() {
return roll;
}
public void setRoll(int roll) {
this.roll = roll;
}
public int getnOfPlayers() {
return nOfPlayers;
}
public void setnOfPlayers(int nOfPlayers) {
this.nOfPlayers = nOfPlayers;
}
public int getPlayerNo() {
return playerNo;
}
public void setPlayerNo(int playerNo) {
this.playerNo = playerNo;
}
}
This is the code for all Game properties, such as scoring etc.
package multiplayergame;
import java.util.ArrayList;
public class GameProperties {
private int score;
private int pins;
private String name;
private int roll;
private int nOfPlayers;
PlayerGame player;
private ArrayList<PlayerGame> players;
private int playerNo;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getPins() {
return pins;
}
public void setPins(int pins) {
this.pins = pins;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRoll() {
return roll;
}
public void setRoll(int roll) {
this.roll = roll;
}
public int getnOfPlayers() {
return nOfPlayers;
}
public void setnOfPlayers(int nOfPlayers) {
this.nOfPlayers = nOfPlayers;
}
public ArrayList<PlayerGame> getPlayers() {
return players;
}
public void setPlayers(ArrayList<PlayerGame> players) {
this.players = players;
}
public int getPlayerNo() {
return playerNo;
}
public void setPlayerNo(int playerNo) {
this.playerNo = playerNo;
}
}
The following are my JSP files, the output first:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Test output</title>
</head>
<body>
<h2>Test Roll</h2>
<c:forEach var="player" items="players">
Name <c:out value="${player.name}"/><p>
</c:forEach>
</body>
</html>
This is the home page:
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Bowling</title>
</head>
<body>
<h2>Welcome players!</h2>
<h2>Please enter your names.</h2>
<form:form method="post" action="/multiplayergame/nextName">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name = "button" value="Next Player"/>
</td>
</tr>
</table>
</form:form>
<form:form method="post" action="/multiplayergame/test">
<tr>
<td colspan="2">
<input type="submit" name = "button" value="Play"/>
</td>
</tr>
</form:form>
</body>
</html>
Change this <c:forEach var="player" items="players"> to <c:forEach var="player" items="${players}">
As your referring "players" string. it is trying to find the property name in string.

Resources