how to display logged in user's todo - java

I'm new spring boot and making todo application.
I'm trying to display logged in user's todo but it results in all todos are displayed.
Does anyone help?
TodoRepository
package com.portfoilo.fullstackbackend.Repository;
import com.portfoilo.fullstackbackend.Model.Todo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface TodoRepository extends JpaRepository<Todo, Integer> {
#Query(value = "SELECT * FROM todos WHERE user_id = :id", nativeQuery = true)
List<Todo> find(#Param("id") Integer id);
}
TodoController
package com.portfoilo.fullstackbackend.Controller;
import com.portfoilo.fullstackbackend.Model.Todo;
import com.portfoilo.fullstackbackend.Model.User;
import com.portfoilo.fullstackbackend.Model.UserDetailsImpl;
import com.portfoilo.fullstackbackend.Repository.TodoRepository;
import com.portfoilo.fullstackbackend.Service.TodoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
#Controller
 public class TodoController {
#Autowired
TodoRepository todoRepository;
#Autowired
TodoService todoService;
#GetMapping("/todo/{id}")
public String home(#PathVariable("id")Integer id, Model model, HttpServletResponse httpServletResponse, #AuthenticationPrincipal UserDetailsImpl userDetails, User user)
{
System.out.println(userDetails.getUsername());
System.out.println(user.getId());
httpServletResponse.addCookie(new Cookie("user_id", user.getId().toString()));
List<Todo> list = todoRepository.find(id);
model.addAttribute("list", list);
model.addAttribute("todo", new Todo());
return "home";
}
public String showCookie(#CookieValue("user_id") String cookieValue) {
System.out.println(cookieValue);
return "home";
}
#PostMapping("/todo/{id}")
public String createTodo(#Validated Todo todo, BindingResult result, Model model) {
todoService.addTodo(todo);
return "redirect:/todo/{id}";
 }
 }
Todo.java
package com.portfoilo.fullstackbackend.Model;
import com.portfoilo.fullstackbackend.SignupForm;
import lombok.Data;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Date;
#Entity
#Data
#Table(name = "todos")
public class Todo {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "user_id")
private Integer user_id;
#NotNull
#NotBlank
#Column(name = "title")
private String title;
#NotNull
#NotBlank
#Column(name = "description")
private String description;
#Column(name = "due_date")
private Date due_date;
#Column(name = "priority")
private Integer priority;
#ManyToOne
#JoinColumn(name = "user_id" ,insertable = false, updatable = false)
private User user;
}
User.java
package com.portfoilo.fullstackbackend.Model;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name = "users")
public class User {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "email")
private String email;
#Column(name = "password")
private String password;
#Column(name = "authority")
private String authority;
#OneToMany(mappedBy = "user")
private List<Todo> todos;
public User(String email, String password, String authority) {
this.email = email;
this.password = password;
this.authority = authority;
}
public User() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public List<Todo> getTodos() {
return todos;
}
public void setTodos(List<Todo> todos) {
this.todos = todos;
}
}
Home.html
<html xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<link th:href="#{/css/home.css}" rel="stylesheet"/>
<title>Todo</title>
</head>
<body>
<div th:text="'Hello ' + ${#authentication.name}"></div>
<h1>Todo</h1>
<h2>Add</h2>
<div>
<form method="post" th:action="#{/todo}" th:object="${todo}">
<p th:errors="*{title}" class="todo-error-message"></p>
<input th:field="*{title}" class="add-input" type="text" placeholder="title">
<input th:field="*{description}" class="add-input" type="text"
placeholder="details">
<input th:field="*{due_date}" class="add-input-third" type="text">
<br/>
<div class="add-form">
<span>Priority</span>
<input type="radio" name="priority" value="3" checked>大
<input type="radio" name="priority" value="2">中
<input type="radio" name="priority" value="1">小<br/>
</div>
<button type="submit" class="add-btn">Add</button>
</form>
</div>
<h2>List</h2>
<div>
<tr th:each="list:${list}">
<td th:text="${list.title}">
<td th:text="${list.user_id}">
</tr>
</div>
<form th:action="#{/logout}" method="post">
<button class="logout-button" type="submit" value="logout">logout</button>
</form>
</body>
</html>
I thought TodoRepository's query is may be wrong but I couldn't find something like correct answer.
I would appreciate it if you could help...!

Related

Resolved [org.springframework.beans.TypeMismatchException: Issue

I'm attempting to build a twitter clone website using spring boot. I'm getting an error and looked through my code. I'm not sure what I'm doing wrong:
2022-03-15 12:23:51.067 WARN 4580 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'com.example.demo.Tweet'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Integer] for value 'Test'; nested exception is java.lang.NumberFormatException: For input string: "Test"]
This is a springboot application using postgres as its database. I also have a User repository in the code that does sign me in properly. I would appreciate any assistance with this. Thank you.
Edit: Added full stacktrace.
Edit2: Added an image of the tweeting.html to show where the string "Test" came from.
Tweet.java
package com.example.demo;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
#Entity
#Table(name="tweets")
public class Tweet {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id",unique=true, nullable = false)
private Integer id;
#Column(name="userid", unique=true, nullable=false)
private Integer userid;
#Column(name="tweet", nullable=false)
private String tweet;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userid;
}
public void setUserId(Integer userid) {
this.userid = userid;
}
public String getTweet() {
return tweet;
}
public void setTweet(String tweet) {
this.tweet = tweet;
}
}
TweetRepository.java
package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface TweetRepository extends JpaRepository<Tweet, Integer>{
public Tweet findAllById(Integer userid);
}
TwitterController.java
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#Controller
public class TwitterController{
#Autowired
private UserRepository userRepo;
private TweetRepository tweetRepo;
#RequestMapping("/")
public String index(Model model) {
//model.addAttribute("message", "Welcome to spring!");
return "index";
}
#RequestMapping("/testing")
public String testing(Model model) {
model.addAttribute("message", "Welcome to spring boot!");
return "testing";
}
#GetMapping("/register")
public String signup(Model model) {
User user = new User();
model.addAttribute("user", user);
return "register";
}
#RequestMapping("/login")
public String login(Model model) {
return "login";
}
#RequestMapping("/tweeting")
public String tweeting(Model model) {
Tweet tweet = new Tweet();
model.addAttribute("tweet", tweet);
return "tweeting";
}
#PostMapping("/process_register")
public String processRegister(User user) {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String encodedPassword = encoder.encode(user.getPassword());
user.setPassword(encodedPassword);
userRepo.save(user);
return "register_success";
}
#PostMapping("/process_tweet")
public String processTweet(Tweet tweet) {
tweetRepo.save(tweet);
return "tweet_success";
}
}
tweeting.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Tweet</title>
<link href="webjars/bootstrap/5.1.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container col-xl-10 col-xxl-8 px-4 py-5">
<div class="row align-items-center g-lg-5 py-5">
<div class="col-md-10 mx-auto col-lg-5">
<form class="p-4 p-md-5 border rounded-3 bg-light" th:action="#{/process_tweet}" th:object="${tweet}" method="post">
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInput" placeholder=tweet th:field="*{tweet}">
<label for="floatingInput">Tweet</label>
</div>
<button class="w-100 btn btn-lg btn-info" type="submit">Post</button>
</form>
</div>
</div>
</div>
<script src="webjars/jquery/3.6.0/jquery.min.js"></script>
<script src="webjars/bootstrap/5.1.0/js/bootstrap.min.js"></script>
<script>
</script>
</body>
</html>

There was an unexpected error (type=Not Found, status=505),

1.This is my entity class.
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Leads {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String firstName;
private String lastname;
private String email;
private String source;
private String mobile;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
This is my controller layer
package com.mento1.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.mento1.entities.Leads;
import com.mento1.service.LeadsService;
#Controller
public class LeadsController {
#Autowired
private LeadsService leadService;
#RequestMapping("/leads")
public String showLeadsPage() {
return "saveLeads";
}
#RequestMapping("/saveLead")
public String saveLead(#ModelAttribute("lead")Leads lead, ModelMap modelMap) {
leadService.saveLead(lead);
modelMap.addAttribute("msg", "Lead is saved");
return "saveLeads";
}
}
3.This is my view layer
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>lead</title>
</head>
<body>
<h2>Create new leads</h2>
<form action="saveLead" method="post">
<pre>
first name <input type="text" name="firstName"/>
last name <input type="text" name= "lastName"/>
email <input type="text" name="email" />
source <select name="source">
<option value="News Paper">News Paper</option>
<option value="TV Commercial">TV Commercial</option>
<option value="Online">Online</option>
<option value="radio">radio</option>
</select>
mobile <input type="text" name="mobile" />
<input type="Submit" value="save" />
</pre>
</form>
</body>
</html>
application properties file- here I have configure my data base
spring.datasource.url=jdbc:mysql://localhost:3306/mentoDB
spring.datasource.username=root
spring.datasource.password=Subrat02
spring.mvc.view.suffix=.jsp
spring.mvc.view.prefix=/WEB-INF/jsps/
This is my Repository layer extended jpa repository
package com.mento1.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.mento1.entities.Leads;
public interface LeadsRepository extends JpaRepository<Leads, Long> {
}
6.This is my service layer interface
package com.mento1.service;
import com.mento1.entities.Leads;
public interface LeadsService {
public void saveLead(Leads lead);
}
This is my service layer class.
package com.mento1.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mento1.entities.Leads;
import com.mento1.repositories.LeadsRepository;
#Service
public class LeadsServiceImpl implements LeadsService {
#Autowired
private LeadsRepository leadRepo;
#Override
public void saveLead(Leads lead) {
leadRepo.save(lead);
}
}
Error Coming:-
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Feb 13 09:24:29 IST 2022
There was an unexpected error (type=Not Found, status=505)
The problem is I am not able to save the data in the data base.
I reviewed your codes. I think your problem is related to entity class. You don't have got constructor methods in Leads class. You must be add this methods with parameter and non-parameter. This really a huge problem.
And you haven't got all annotations. I recommend to use"Lombok" dependencies for constructor and annotations. You don't need to write getter/setter or constructor methods if you use Lombok.
Then you add Lombok to dependencies and set up it. (You can search to how install lombok to spring-boot project). You just should add some annotations to your entity.
I write my entity class as an example.
package datum....entities.concretes;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Data
#Entity
#Table(name = "column_table")
#AllArgsConstructor
#NoArgsConstructor
public class ColumnTable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "clmn_id")
public int clmnId;
#Column(name = "database_id")
public int databaseId;
#Column(name = "schema_id")
public int schemaId;
#Column(name = "table_id")
public int tableId;
#Column(name = "column_id")
public int columnId;
#Column(name = "column_name")
public String columnName;
#Column(name = "type_name")
public String typeName;
#Column(name = "max_len")
public int maxLen;
#Column(name = "prec")
public int prec;
#Column(name = "nullable")
public int nullable;
#Column(name = "columnDescription")
public String columnDescription;
#Column(name = "sample_name")
public String sampleName;
}

JSTL Spring Boot - Bean property 'email' is not readable or has an invalid getter method

I am fairly new to using Spring Boot and JSTL. I am currently trying to implement something in my view where I can select multiple checkboxes and send the data over to my controller to operate on. I think I have done everything correctly but can't seem to find the root of the problem here. Can someone please help? Getting the following error:
021-02-09 17:49:45.227 ERROR 16216 --- [nio-8080-exec-6]
o.s.web.servlet.tags.form.CheckboxTag : Invalid property 'email' of
bean class [java.util.ArrayList]: Bean property 'email' is not
readable or has an invalid getter method: Does the return type of the
getter match the parameter type of the setter?
org.springframework.beans.NotReadablePropertyException: Invalid
property 'email' of bean class [java.util.ArrayList]: Bean property
'email' is not readable or has an invalid getter method: Does the
return type of the getter match the parameter type of the setter? at
org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:625)
~[spring-beans-5.3.3.jar:5.3.3] at
org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:615)
~[spring-beans-5.3.3.jar:5.3.3]
My Controller:
package com.bizlinks.mainapp.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import com.bizlinks.mainapp.models.Lead;
import com.bizlinks.mainapp.repository.UserRepository;
#Controller
public class AdminController {
#Autowired // This means to get the bean called userRepository
//Which is auto-generated by Spring, we will use it to handle the data
private UserRepository userRepository;
#RequestMapping(value = "admin", method = RequestMethod.GET)
public String List(Model model) {
List<Lead> leads = userRepository.findAll();
model.addAttribute("leads", leads);
return "admin";
}
#RequestMapping(value = "admin", method = RequestMethod.POST)
public String deleteLead(#ModelAttribute("leads")List<Lead> leads){
for(int i =0; i< leads.size();i++) {
System.out.println(leads.get(i).getEmail());
}
return "admin";
}
}
My model:
package com.bizlinks.mainapp.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "leads")
public class Lead {
#Id
#Column(name = "email")
private String email;
#Column(name = "firstName")
private String firstName;
#Column(name = "surName")
private String surName;
#Column(name ="phone")
private String phone;
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public String getSurName() {
return surName;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhone() {
return phone;
}
}
My view body:
<body>
<nav class="nav nav-fill">
<a class="nav-link" href="/">Home</a>
</nav>
<div class="container-fluid con">
<table>
<tr>
<th>First Name</th>
<th>Surname</th>
<th>Email</th>
<th>Phone</th>
</tr>
<form:form action="admin" modelAttribute="leads">
<c:forEach items="${leads}" var="item">
<tr>
<td><c:out value="${item.email}"/></td>
<td><c:out value="${item.firstName}"/></td>
<td><c:out value="${item.surName}"/></td>
<td><c:out value="${item.phone}"/></td>
<form:checkbox path="email" value="${item.email}"/>
</tr>
</c:forEach>
<input type="submit" value="Submit" />
</form:form>
</table>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.min.js"></script>
</body>

Spring+Velocity unsuccessful attempts to save object

I`ve ran into a problem with controller/vm data transfer and could not find any solution.
Ive got a User (see class below)
package com.Entity;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.*;
import java.util.Date;
#Entity
#Transactional
#Table(name = "USERS")
public class User {
private Long id;
private UserType type;
private String email;
private String password;
private String name;
private String tel;
private Date regDate;
private Date lastActive;
private Agent office;
//Constructors
public User(){
}
public User(UserType type, String email, String password, String name, String tel, Agent office) {
this.type = type;
this.email = email;
this.password = password;
this.name = name;
this.tel = tel;
this.regDate = new Date();
this.lastActive = null;
this.office = office;
}
//Getters
#Id
#SequenceGenerator(name = "USERID_SEQ", sequenceName = "USERID_SEQ",allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "USERID_SEQ")
#Column(name = "ID")
public Long getId() {
return id;
}
#Column(name = "TYPE")
public UserType getType(){
return type;
}
#Column(name = "EMAIL")
public String getEmail() {
return email;
}
#Column(name = "PASSWORD")
public String getPassword() {
return password;
}
#Column(name = "NAME")
public String getName() {
return name;
}
#Column(name = "TEL")
public String getTel() {
return tel;
}
#Column(name = "DATE_REG")
public Date getRegDate() {
return regDate;
}
#Column(name = "LAST_ACTIVE")
public Date getLastActive() {
return lastActive;
}
#ManyToOne (targetEntity = Agent.class, fetch = FetchType.EAGER)
#JoinColumn(name = "OFFICEID")
public Agent getOffice() {
return office;
}
// Setters
}
Controller for it
package com.Controllers;
import com.Entity.AgentType;
import com.Entity.User;
import com.Services.AgentService;
import com.Services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
//TODO: TEST CONTROLLER SUBJECT TO DELETE
#Controller
public class ViewController {
#Autowired
private UserService userService;
#Autowired
private AgentService agentService;
#RequestMapping(value = "/list", method = RequestMethod.GET)
public ModelAndView listUsersPage(){
List<User>list = userService.getAll();
return new ModelAndView("fragments/userss.vm","users",list);
}
#RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
public ModelAndView edit(#PathVariable Long id){
return new ModelAndView("fragments/edit.vm",
"user", (User)userService.getById(id));
}
//FUNCTIONAL
#RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public ModelAndView delete(#PathVariable Long id){
userService.delete(userService.getById(id));
return new ModelAndView("redirect:/list");
}
#RequestMapping(value = "/update", method = RequestMethod.POST)
public ModelAndView update(User user){
User user1 = user;
//userService.update(user1);
return new ModelAndView("redirect:/list");
}
//Model Attributes
#ModelAttribute
public void userTypesList(Model model){
model.addAttribute("types", userService.getPositions());
}
#ModelAttribute
public void officesList(Model model){
model.addAttribute("offices", agentService.getAllByType(AgentType.OFFICE));
}
}
and a pages (.vm) to add new or edit existing users(just one example the edit page):
<title>EDIT USER</title>
<body>
<form method="post" action="/update">
id:
<input type="text" name="id" path="id" value="$user.id"/> <br>
Type:
<select name="type" path="type">
<option hidden selected>$user.type</option>
#foreach($type in $types)
<option value="$type">$type</option>
#end
</select> <br>
e-mail:
<input type="text" name="email" path="email" value="$user.email"/> <br>
Password:
<input type="text" name="password" path="password" value="$user.password"/> <br>
Name:
<input type="text" name="name" path="name" value="$user.name"/> <br>
Tel:
<input type="text" name="tel" path="tel" value="$user.tel"/> <br>
Reg Date:
<input type="date" name="regDate" path="regDate" value="$user.regDate"/> <br>
Last Active:
<input type="date" name="lastActive" path="lastActive" value="$user.lastActive"/> <br>
Office:
<select name="office" path="office">
<option hidden selected value="$user.office">$user.office.name</option>
#foreach($office in $offices)
<option value="$office">$office.name</option>
#end
</select> <br>
<input type="submit" value="Update"/>
</form>
</body>
The problem is that I cant manage to save the updated User via /update(User user). Ive tried different ways, but still no success.
Whis this code I`m getting HTTP Status 400 – Bad Request. 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).
Could you please help me out? What is wrong with it?
In your code you are missing a couple of things.
Frist of all, you miss the model attribute specified in the form:
<form method="post" action="/update" modelAttribute="user">
Second, you are missing the model attribute specified in the post method:
#RequestMapping(value = "/update", method = RequestMethod.POST)
public ModelAndView update(#ModelAttribute("user") User user){
User user1 = user;
userService.update(user1);
return new ModelAndView("redirect:/list");
}
If you need further details, you can read Getting Started with Forms in Spring MVC

Two Database Tables with Struts 2.0 Action

I have trying to save values to two database table with one Struts 2.0 Action class.
I have tried it with Implementing ModelDriven But it didn't catch both VO's. Please give me a solution to catch both VO's in same struts 2.0 action class.
Code Snipper For UserVO.java
package com.sajeewi.struts.vo;
import static javax.persistence.GenerationType.IDENTITY;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "user")
public class UserVO {
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "idUser", unique = true, nullable = false)
private int idUser;
#Column(name = "username", unique = true, nullable = false, length = 20)
private String username;
#Column(name = "password", unique = true, nullable = false, length = 20)
private String password;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "userVO", cascade = CascadeType.ALL)
private User_DetailsVO user_DetailsVO;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "userVO")
private Set<AccountVO> accountVOs;
public UserVO() {
// TODO Auto-generated constructor stub
}
public UserVO(int idUser,String username,String password){
this.idUser = idUser;
this.username = username;
this.password = password;
}
public int getIdUser() {
return idUser;
}
public void setIdUser(int idUser) {
this.idUser = idUser;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User_DetailsVO getUser_DetailsVO() {
return user_DetailsVO;
}
public void setUser_DetailsVO(User_DetailsVO user_DetailsVO) {
this.user_DetailsVO = user_DetailsVO;
}
public Set<AccountVO> getAccountVOs() {
return accountVOs;
}
public void setAccountVOs(Set<AccountVO> accountVOs) {
this.accountVOs = accountVOs;
}
}
This is for User_DetailsVO.java
package com.sajeewi.struts.vo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
#Entity
#Table(name="user_details")
public class User_DetailsVO {
#Id
#Column(name = "User_idUser", unique = true, nullable = false)
#GeneratedValue(generator = "generator")
#GenericGenerator(name = "generator", strategy = "foreign", parameters = #Parameter(name = "property", value = "userVO"))
private int User_idUser;
#OneToOne(fetch = FetchType.LAZY)
#PrimaryKeyJoinColumn
private UserVO userVO;
#Column(name = "contact1", nullable = false, length = 15)
private String contact1;
#Column(name = "contact2", nullable = false, length = 15)
private String contact2;
#Column(name = "email", nullable = false, length = 50)
private String email;
#Column(name = "add1", nullable = false, length = 100)
private String add1;
#Column(name = "add2", nullable = false, length = 100)
private String add2;
#Column(name = "city", nullable = false, length = 50)
private String city;
public User_DetailsVO() {
// TODO Auto-generated constructor stub
}
public User_DetailsVO(UserVO userVO,String contact1,String contact2,String email,String add1,String add2,String city){
this.userVO = userVO;
this.contact1 = contact1;
this.contact2 = contact2;
this.email = email;
this.add1= add1;
this.add2 = add2;
this.city = city;
}
public int getUser_idUser() {
return User_idUser;
}
public void setUser_idUser(int user_idUser) {
User_idUser = user_idUser;
}
public UserVO getUserVO() {
return userVO;
}
public void setUserVO(UserVO userVO) {
this.userVO = userVO;
}
public String getContact1() {
return contact1;
}
public void setContact1(String contact1) {
this.contact1 = contact1;
}
public String getContact2() {
return contact2;
}
public void setContact2(String contact2) {
this.contact2 = contact2;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAdd1() {
return add1;
}
public void setAdd1(String add1) {
this.add1 = add1;
}
public String getAdd2() {
return add2;
}
public void setAdd2(String add2) {
this.add2 = add2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
This is the User Action Class
package com.sajeewi.struts.action;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.sajeewi.struts.dao.UserDAO;
import com.sajeewi.struts.dao.impl.UserDAOImpl;
import com.sajeewi.struts.vo.UserVO;
import com.sajeewi.struts.vo.User_DetailsVO;
#SuppressWarnings({ "serial" })
public class UserAction extends ActionSupport implements ModelDriven<Object>{
UserVO userVO = new UserVO();
User_DetailsVO detailsVO = new User_DetailsVO();
List<UserVO> userList = new ArrayList<UserVO>();
UserDAO userDAO = new UserDAOImpl();
public List<UserVO> getUserList() {
return userList;
}
public void setUserList(List<UserVO> userList) {
this.userList = userList;
}
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
public UserVO getUserVO() {
return userVO;
}
public void setUserVO(UserVO userVO) {
this.userVO = userVO;
}
public User_DetailsVO getDetailsVO() {
return detailsVO;
}
public void setDetailsVO(User_DetailsVO detailsVO) {
this.detailsVO = detailsVO;
}
public String addUser(){
// userDAO.saveUser(this.userVO);
// userList = null;
// try {
// userList = userDAO.searchAllUsers();
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
System.out.println(this.userVO);
System.out.println(this.detailsVO);
return SUCCESS;
}
public Object getModel() {
return userVO;
}
}
Jsp View
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!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>User</title>
</head>
<body>
<s:div>
<h2>Registration With Struts 2.0</h2>
<s:form action="addUser" method="POST">
<s:div>
<h4>Enter User Credentials</h4>
<s:textfield name="username" label="Username"></s:textfield>
<s:password name="password" label="Password"></s:password>
</s:div>
<br>
<s:textfield name="contact1" label="Contact1 "></s:textfield>
<s:textfield name="contact2" label="Contact2 "></s:textfield>
<s:textfield name="email" label="E-Mail "></s:textfield>
<s:textfield name="add1" label="Address Line 1 "></s:textfield>
<s:textfield name="add2" label="Address Line 2 "></s:textfield>
<s:textfield name="city" label="City "></s:textfield>
<br>
<s:submit name="Save" value="Save"></s:submit>
</s:form>
</s:div>
</body>
</html>
I want to save to both tables with same form
Thanks
OK, so you have a separate table to for storing user-info but all that info is being read from single form. In that case, its simple.
Dont go for model-driven as all form-fields are not present in single class else you can have a bean class for the same (I don't recommend it).Populate the corresponding values in the two class objects UserVO and User_DetailsVO using getters n setters in action class.
Now all you do is:
Session session = SessionFactory.openSession();
session.save(userVO);
int savedId = userVO.getIdUser();
detailsVO. setUser_idUser(savedId);
session.save(detailsVO);
session.close();
I am unable to guess in your table which one is primary key and which is foreign key. So save the object which is primary and then save the other object which have FK.
Got a solution. I have changed my JSP like this
Before
<s:textfield name="username" label="Username"></s:textfield>
Now
<s:textfield name="userVO.username" label="Username"></s:textfield>
All i have do is add VO name to the textfield name then it automatically catch all the data in the action class for both UserVO and User_DetailsVO
Thanks

Categories