display single row by id - spring mvc - java

so i want to display single row by its id on spring mvc
i have this dao:
public Message getMessageById(int id){
String sql="select * from tb_message where id_message=?;";
return template.queryForObject(sql, new Object[]{id},new BeanPropertyRowMapper<Message>(Message.class));
}
and this is my controller:
#RequestMapping(value="/replymessageto/{id}")
public String viewforreply(#PathVariable int id, Model m){
Pesan currentmessage=dao_send_message.getMessageById(id);
m.addAttribute("command", currentmessage);
return "viewcurrentmessage";
}
i can display the value if i use this on my jsp:
<form:form>
<form:input type="text" path="message_title" name="message_title" class="form-control"/>
</form:form>
but what i want is to show the value only on <p></p> tag

Related

Write value from Select in DTO Thymeleaf

I have an Entity "User". I have an Enum "Usertyp". Users have a field "usertyp". I want to change the "Usertyp" by passing a DTO to my controller. The problem is that the usertype gets changed to Null in the DB
Another minor problem is that I want the default value of the selectfield to have the users current usertype as default value. I tried with "
th:selected="${u.usertyp}">
and also with an if statement. Neither worked.
I am very grateful for any help. I really struggle with Thymeleaf.
Controller:
#PostMapping("editUser/{userId}")
public String editUser(#ModelAttribute("sessionUser") User sessionUser, #Valid #ModelAttribute("userDTO") UserDTO userDTO, #PathVariable Long userId, Model model){
if(sessionUser==null || sessionUser.getUsertyp() == Usertyp.USER)
{
return "redirect:/";
}
else {
User changedUser = userService.findById(userId);
changedUser.setUsertyp(Usertyp.fromString(userDTO.getUsertyp()));
userService.save(changedUser);
return "redirect:/administration";
}
}
DTO
public class UserDTO {
//TODO usertyp anpassem
private String usertyp;
public UserDTO(String usertyp) {
this.usertyp = usertyp;
}
public String getUsertyp() {
return usertyp;
}
public void setUsertyp(String usertyp) {
this.usertyp = usertyp;
}
}
Template
<ul class="list-group list-group-flush">
<span th:each="u : ${userList}">
<li class="list-group-item">
<span th:text="${u.username}"></span>
<form th:object="${userDTO}" th:action="#{/editUser/{userId}(userId=${u.id})}" method="Post" id="Rolle">
<select th:field="*{usertyp}" form="Rolle">
<option
th:each="usertyp : ${T(com.example.myproject.entities.Usertyp).values()}"
th:text="${usertyp.displayText}"
th:value="${usertyp.displayText}">
</option>
</select>
<input class="btn btn-primary" type="submit" value="Speichern">
</form>
</li>
</span>
</ul>
I already changed my DTO field type from "Usertyp" to String
th:selected="${u.usertyp}">
The th:selected property should convert to selected="selected" or just selected in raw html, I think instead you want something like th:selected="${u.usertyp == usertyp}"
You didn't show your #GetMapping setup for the thyme leaf page, so I didn't include a user list, but here's a basic example of what I think you're attempting to do:
User Controller:
#Controller
public class UserController {
#GetMapping("user")
public String getUserTypePage(#ModelAttribute("userDTO") UserDTO userDTO) {
// just setting it to admin so that it will show the default selection of not the first item
userDTO.setUserType(UserType.ADMIN);
return "user";
}
#PostMapping("user")
public void postUserTypePage(#ModelAttribute("userDTO") UserDTO userDTO) {
System.out.println("USER DTO TYPE - " + userDTO.getUserType().getDisplayText());
}
}
UserType enum:
public enum UserType {
USER("Standard User"),
ADMIN("Administrator");
private final String displayText;
UserType(String displayText) {
this.displayText = displayText;
}
public String getDisplayText() {
return displayText;
}
}
UserDTO:
public class UserDTO {
private UserType userType;
public UserDTO(UserType userType) {
this.userType = userType;
}
public UserType getUserType() {
return userType;
}
public void setUserType(UserType userType) {
this.userType = userType;
}
}
Thymeleaf view:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
<title>User Type</title>
</head>
<body>
<ul class="list-group list-group-flush">
<li class="list-group-item">
<form th:object="${userDTO}" th:action="#{/user}" method="POST" id="Rolle">
<select th:field="*{userType}" form="Rolle">
<option
th:each="uType : ${T(com.example.demo.models.UserType).values()}"
th:text="${uType.displayText}"
th:value="${uType}"
th:selected="${userType == uType}">
</option>
</select>
<input class="btn btn-primary" type="submit" value="Speichern">
</form>
</li>
</ul>
</body>
</html>
Specifically you want the th:value to be bound to the enum value (if you'd prefer to use an enum rather than a string):
th:value="${uType}"
And then the th:selected set based off of equality of the enum to the UserType option in being looped through:
th:selected="${userType == uType}">
A few additional things to check:
Are you establishing the #ModelAttribute("userDTO") in the GET variant of your controller?
Log out the value of the userType in your post method to confirm it's value before any database operation (to confirm that it is actually coming in as null from the post and not being set to null somewhere in the db operation).
Try just passing along the value for the userType in the form (instead of using a select input item) to confirm that the currentValue for your model is getting fed through i.e.: <input th:field="*{userType}" th:value="${userType}">

Search table with method query spring boot thymeleaf

I have a problem when I try to add search form to my table. I wont to search in some table column with method query. I use parameter with #RequestParam and process it to method but when I input something to search, it always show me whole table. There are no errors in Spring boot console.
Here are my classes:
predmeti.html
<form class="form-horizontal" th:object="${predmet}" th:action="#{/predmeti}" method="get">
<p class="col-sm-2"><input type="text" th:name="imeZaPretragu" th:value="${search}" class="form-control"/></p>
<p><input type="submit" class="btn btn-primary" value="Pretraži"/></p>
<div th:if="${not #lists.isEmpty(predmeti)}">
<table class="table table-striped">
<tr>
<th>Prezime</th>
PredmetController
private PredmetiRepository predmetiRepository;
#Autowired
public void setPredmetiRepository(PredmetiRepository predmetiRepository) {
this.predmetiRepository = predmetiRepository;
}
#GetMapping("/predmeti/")
public String pretraziPredmet(#RequestParam(value="search", required = true) String imeZaPretragu, Model model) {
model.addAttribute("predmeti", predmetiRepository.findByPrezime(imeZaPretragu));
return "predmeti";
}
PredmetRepository
public interface PredmetiRepository extends JpaRepository<Predmet, Long> {
Iterable<Predmet> findByPrezime(String imeZaPretragu);
}
Thank you in advance.

Spring MVC: #PathVariable form

I have a data base which contains some items. I want to create a form which edits item with some id. I did it, form opens fine. Adress is /itemproject/edit_item/{id} Problems start when I'm trying to activate POST method. Instead of directing me to page with item list (/itemproject/view_items) programm sends me to /itemproject/edit_item/edit_item. itemproject is context path (for example).
#RequestMapping(value = "/edit_item/{id}", method = RequestMethod.GET)
public String editItem(#PathVariable("id") Integer id, Model model) {
Item item;
item = dbService.findItem(item).get(0);
model.addAttribute("item", item);
return "edit_item";
}
#RequestMapping(value = "/edit_item/{id}", method = RequestMethod.POST)
public String editItemComplete(#PathVariable("id") Integer id, #ModelAttribute("item") Item item, Model model) {
dbService.updateItem(item);
model.addAttribute("items",dbService.findAllItems());
return "view_items";
}
dbService works with data base.
I want that programm sent me to list of all items after ediding chosen item and updating it in database.
Here is example of edit form (url: /itemproject/edit_item/{id}
<spring:url value="edit_item" var="formURL"/>
<form:form action="${formURL}"
method="post" cssClass="col-md-8 col-md-offset-2"
modelAttribute="item"
>
<div class="form-group">
<label for="item-stuff">Stuff</label>
<form:input id="item-stuff"
cssClass="form-control"
path="stuff"/>
</div>
<button type="submit" class="btn btn-default">Edit item</button>
</form:form>
This is how my item list page looks (url: /itemproject/view_items)
<body>
<table class="table table-hover">
<tbody>
<tr>
<th>Stuff</th>
</tr>
<c:forEach items="${items}" var="item">
<tr>
<td>${item.stuff}</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
From Spring docs:
In Spring MVC you can use the #PathVariable annotation on a method
argument to bind it to the value of a URI template variable
That means that #PathVariable annotation is suitable when you use the GET method because when you use GET method you can pass your query string.
Instead, try to use #RequestBody in order to try to bind your POST HTTP body message to your parameter
For example:
#RequestMapping(value = "/edit_item", method = RequestMethod.POST)
public String editItemComplete(#RequestBody String body) {
//in here you'll have to pull the body content
return "view_items";
}
Let's say that you're sending an Integer id on HTTP POST body, then you can pull the data from the body like this:
#RequestMapping(value = "/edit_item", method = RequestMethod.POST)
public String editItemComplete(#RequestBody String body) {
ObjectMapper objectMapper = new ObjectMapper();
try {
idJson = objectMapper.readTree(body).path("id").asInt();
} catch (IOException e) {
e.printStackTrace();
}
return "view_items";
}
assuming that you're sending json from client to service.
Rather than loading the items and returning the view_items template, you can return "redirect:/itemproject/view_items" and that will cause your handler for view_items to be invoked, which will load the items etc.

Adding values from a controller to a dropdown Spring MVC

In my Controller I have
#RequestMapping(value="/getCounties", method = {RequestMethod.GET},produces=MediaType.Application_JSON_VALUE)
public #Responcebody List<Counties>(#RequestParam String province){
List<Counties> county = this.xService.getCounties(county);
return county;
}
This method send the province chosen in the form down to the repository and join on the counties within that province.
In my dropdown on the form how do I return these values into the dropdown.
I currently have
<tr>
<td>
<form:select path="cdGcd" class="textbox" onclick="getCounty()">
<form:option value="-" label="Please Select"/>
<form:options path="county" items='${county}' itemValue = "countycode" itemLabel="countydescription"/>
</form:select>
</td>
</tr>
You can not return List directly form controller.
For passing data from controller to JSP you need to add data in Model and return respective JSP page.
So you need to change your method to,
#RequestMapping(value="/getCounties", method = {RequestMethod.GET})
public String getCountries(#RequestParam String province, Model model){
List<Counties> county = this.xService.getCounties(county);
model.addAttribute("county",county);
return "jsp page";
}
If you want to achieve this using AJAX then,you need to return JsonObject from controller.

Spring MVC Formatter and ManyToOne Entity

I am working on a spring mvc project. A Name class has a many to one relationship with a gender class. I have a Genderformatter to handle the select list needed for create and update name:
public class GenderFormatter implements Formatter<Gender> {
#Autowired
private GenderRepository genderRepository;
public String print(Gender gender, Locale locale) {
return gender.getId().toString();
}
public Gender parse(String id, Locale locale) throws ParseException {
Gender gender = this.genderRepository.findOne(Integer.valueOf(id));
return gender;
}
}
Here is relavent portion of the addupdatename.jsp
<form:form modelAttribute="name" method="${method}"
class="form-horizontal" id="add-name-form">
...
<!-- Gender Select List -->
<spring:bind path="gender">
<c:set var="cssGroup"
value="control-group ${status.error ? 'error' : '' }" />
<div class="${cssGroup}">
<label class="control-label">Gender</label>
<div class="controls">
<form:select path="gender">
<form:option value="${name.gender.id}" label="${name.gender.gender}" />
<form:options items="${genders}" itemValue="id" itemLabel="gender" />
</form:select>
<span class="help-inline">${status.errorMessage}</span>
</div>
</div>
</spring:bind>
The NameController relevant GET and POST:
#RequestMapping(value = "/names/new", method = RequestMethod.GET)
public String initCreationForm(ModelMap model) {
Name name = new Name();
model.addAttribute(name);
model.put("genders", this.nameAdminService.findGenders());
return "name/addupdatename";
}
#RequestMapping(value = "/names/new", method = RequestMethod.POST)
public String processCreationForm(#Valid Name name, BindingResult result,
SessionStatus status) {
if (result.hasErrors()) {
return "name/addupdatename";
} else {
this.nameRepository.save(name);
status.setComplete();
return "redirect:/names/" + name.getId();
}
}
This all works fine. Now I'm adding CRUD functions for the Gender entity and running into problems. The GenderController and jsp objects follow the same pattern as the Name code. As long as the GenderFormatter is registered as a conversion service, the gender forms wont process add or updates to the data. I assume because on the gender add or update form post, the formatter is trying to convert the gender field to a gender object.
Is there a way to specify when or which fields a formatter should format?

Categories