Spring MVC and java script(addRows function) binding - spring-mvc

I have question/issue with javascript function binding in Spring MVC . As per our requirement I need to insert a NEW ROW in a table when the user clicks on “ADD” button .
Step1 : So when the user clicks on “Add MORE” button I inserting a new row within a table , I am handling this using javascript
Step 2: When user clicks on the submit button , I Need to send the values entered by user to my Controller (Spring MVC Controller) .
So how can binding the values to controller dynamically ?
Please help me to resolve this issue ASAP .

I do the following when I need to bind a dynamic list of objects coming from the front end :
Post the data as a json array, i.e. in the following format
{ data : [{a:1, b:2}, {a:3, b:4}] }
In the Controller
#RequestMapping(value="save", method=RequestMethod.POST)
public void save(JSONObject object)
{
List<YourType> list = new ArrayList<YourType>();
JSONArray array = object.getJSONArray("data")
for(int i=0; i<array.length(); i++)
{
//getObjectFromJson is your method for converting json to an object of your type.
list.add(JsonUtils.fromJson(array.getJSONObject(i).toString(), YourType.class);
}
}

Spring can bind maps and lists of objects if you give create an appropriate class to hold your form data then use the #ModelAttribute annotation on your controller method.
For example, if your JavaScript creates table rows like this:
<tr>
<td><input name="bells[0]" /></td>
<td><input name="whistles[0]" /></td>
</tr>
<tr>
<td><input name="bells[1]" /></td>
<td><input name="whistles[1]" /></td>
</tr>
Then you can create a model class that contains a list for each repeating field in your HTML form, like this:
public class AsapForm {
private List<String> bells;
private List<String> whistles;
// add getters and setters here
}
And then you can create a controller method that uses that class as a parameter with the #ModelAttribute annotation:
public void postAsapForm(#ModelAttribute("contactForm") AsapForm asapForm, BindingResult result) {
...
}
You can then access the values for each row using asapForm.getBells() and asapForm.getWhistles() etc.

I have achieved this using LazyList.
You need to do this in following way.
Operation.java
package com.xxx.xxx.model;
// Generated Feb 9, 2012 11:30:06 AM by Hibernate Tools 3.2.1.GA
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.apache.commons.collections.FactoryUtils;
import org.apache.commons.collections.list.LazyList;
#Entity
#Table(name="Operations"
,schema="dbo"
)
public class Operations implements java.io.Serializable {
private int operationId;
#Embedded
private Services services;
private String operationName;
private String isHqlsql;
private String isMultipleTables;
private String listOfTablesAffected;
private String hqlQuery;
private String typeOfOperation;
private String operationDetail;
private String inputVariables;
private String outputparamdatatype;
private String isCountQuery;
private String isDynamicWhereQry;
private String isPaginationRequired;
private String biInputParameters;
private List<OperationParameters> operationParameterses = LazyList
.decorate(new ArrayList<OperationParameters>(),
FactoryUtils.instantiateFactory(OperationParameters.class));
public Operations() {
}
public Operations(int operationId, Services services, String operationName) {
this.operationId = operationId;
this.services = services;
this.operationName = operationName;
}
public Operations(int operationId, Services services, String operationName, String isHqlsql, String isMultipleTables, String listOfTablesAffected, String hqlQuery, String typeOfOperation, String operationDetail, String inputVariables, String outputparamdatatype, String isCountQuery, List operationParameterses) {
this.operationId = operationId;
this.services = services;
this.operationName = operationName;
this.isHqlsql = isHqlsql;
this.isMultipleTables = isMultipleTables;
this.listOfTablesAffected = listOfTablesAffected;
this.hqlQuery = hqlQuery;
this.typeOfOperation = typeOfOperation;
this.operationDetail = operationDetail;
this.inputVariables = inputVariables;
this.outputparamdatatype = outputparamdatatype;
this.isCountQuery = isCountQuery;
this.operationParameterses = operationParameterses;
}
#Id
#GeneratedValue
#Column(name="operationId", unique=true, nullable=false)
public int getOperationId() {
return this.operationId;
}
public void setOperationId(int operationId) {
this.operationId = operationId;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="serviceId", nullable=false)
public Services getServices() {
return this.services;
}
public void setServices(Services services) {
this.services = services;
}
#Column(name="operationName", nullable=false, length=250)
public String getOperationName() {
return this.operationName;
}
public void setOperationName(String operationName) {
this.operationName = operationName;
}
#Column(name="isHQLSQL", length=50)
public String getIsHqlsql() {
return this.isHqlsql;
}
public void setIsHqlsql(String isHqlsql) {
this.isHqlsql = isHqlsql;
}
#Column(name="isMultipleTables", length=50)
public String getIsMultipleTables() {
return this.isMultipleTables;
}
public void setIsMultipleTables(String isMultipleTables) {
this.isMultipleTables = isMultipleTables;
}
#Column(name="listOfTablesAffected", length=500)
public String getListOfTablesAffected() {
return this.listOfTablesAffected;
}
public void setListOfTablesAffected(String listOfTablesAffected) {
this.listOfTablesAffected = listOfTablesAffected;
}
#Column(name="hqlQuery")
public String getHqlQuery() {
return this.hqlQuery;
}
public void setHqlQuery(String hqlQuery) {
this.hqlQuery = hqlQuery;
}
#Column(name="typeOfOperation", length=50)
public String getTypeOfOperation() {
return this.typeOfOperation;
}
public void setTypeOfOperation(String typeOfOperation) {
this.typeOfOperation = typeOfOperation;
}
#Column(name="operationDetail")
public String getOperationDetail() {
return this.operationDetail;
}
public void setOperationDetail(String operationDetail) {
this.operationDetail = operationDetail;
}
#Column(name="inputVariables", length=5000)
public String getInputVariables() {
return this.inputVariables;
}
public void setInputVariables(String inputVariables) {
this.inputVariables = inputVariables;
}
#Column(name="outputparamdatatype", length=50)
public String getOutputparamdatatype() {
return this.outputparamdatatype;
}
public void setOutputparamdatatype(String outputparamdatatype) {
this.outputparamdatatype = outputparamdatatype;
}
#Column(name="isCountQuery", length=10)
public String getIsCountQuery() {
return this.isCountQuery;
}
public void setIsCountQuery(String isCountQuery) {
this.isCountQuery = isCountQuery;
}
public String getIsDynamicWhereQry() {
return isDynamicWhereQry;
}
public void setIsDynamicWhereQry(String isDynamicWhereQry) {
this.isDynamicWhereQry = isDynamicWhereQry;
}
public String getIsPaginationRequired() {
return isPaginationRequired;
}
public void setIsPaginationRequired(String isPaginationRequired) {
this.isPaginationRequired = isPaginationRequired;
}
public String getBiInputParameters() {
return biInputParameters;
}
public void setBiInputParameters(String biInputParameters) {
this.biInputParameters = biInputParameters;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="operations")
public List<OperationParameters> getOperationParameterses() {
return this.operationParameterses;
}
public void setOperationParameterses(List<OperationParameters> operationParameterses) {
this.operationParameterses = operationParameterses;
}
}
OperationParameters.java
package com.xxx.xxx.model;
// Generated Feb 9, 2012 11:30:06 AM by Hibernate Tools 3.2.1.GA
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="OperationParameters"
,schema="dbo"
)
public class OperationParameters implements java.io.Serializable {
private int parameterId;
private Operations operations;
private String inputOutputParamName;
private String inputOutputParamType;
private String inputOutputParamDataType;
public OperationParameters() {
}
public OperationParameters(int parameterId, Operations operations, String inputOutputParamName, String inputOutputParamType, String inputOutputParamDataType) {
this.parameterId = parameterId;
this.operations = operations;
this.inputOutputParamName = inputOutputParamName;
this.inputOutputParamType = inputOutputParamType;
this.inputOutputParamDataType = inputOutputParamDataType;
}
#Id
#GeneratedValue
#Column(name="parameterId", unique=true, nullable=false)
public int getParameterId() {
return this.parameterId;
}
public void setParameterId(int parameterId) {
this.parameterId = parameterId;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="operationId", nullable=false)
public Operations getOperations() {
return this.operations;
}
public void setOperations(Operations operations) {
this.operations = operations;
}
#Column(name="inputOutputParamName", nullable=false, length=250)
public String getInputOutputParamName() {
return this.inputOutputParamName;
}
public void setInputOutputParamName(String inputOutputParamName) {
this.inputOutputParamName = inputOutputParamName;
}
#Column(name="inputOutputParamType", nullable=false, length=250)
public String getInputOutputParamType() {
return this.inputOutputParamType;
}
public void setInputOutputParamType(String inputOutputParamType) {
this.inputOutputParamType = inputOutputParamType;
}
#Column(name="inputOutputParamDataType", nullable=false, length=250)
public String getInputOutputParamDataType() {
return this.inputOutputParamDataType;
}
public void setInputOutputParamDataType(String inputOutputParamDataType) {
this.inputOutputParamDataType = inputOutputParamDataType;
}
}
Conroller method to serve the post request to add new Operation.
/**
* Method that will serve the post request to add the operation and operation parameters submitted by the user.
* #param operations
* #param map
* #return {#link String} The view name that will redirect to the get request to display the previous page with newly entered operation in the list.
*/
#RequestMapping(value="/add", method=RequestMethod.POST)
public String addOperations(#ModelAttribute Operations operations, ModelMap map) {
operations.getOperationParameterses().removeAll(Collections.singleton(null));
for(int i=0; i<operations.getOperationParameterses().size(); i++) {
System.out.println("parameterName :: " + ((OperationParameters)operations.getOperationParameterses().get(i)).getInputOutputParamName());
if(((OperationParameters)operations.getOperationParameterses().get(i)).getInputOutputParamName() == null || "".equalsIgnoreCase((((OperationParameters)operations.getOperationParameterses().get(i))).getInputOutputParamName())) {
operations.getOperationParameterses().remove(i);
System.out.println("empty parameter removed....");
}
}
return "redirect:/operations/" + operations.getServices().getServiceId();
}
Hope this helps you.

Related

Spring JPA: Adding an entity with current user ID as foreign key

I'm using a Thymeleaf HTML registration form and simple save/update method to save/update a 'dish' object to a mySQL database. Restaurant Id is a foreign key for the 'dish' but using the below methods it saves as 'null',
I would like to make it so that the Restaurant id of the currently logged in restaurant owner saves automatically when they add a dish.
Is there an uncomplicated way to do this? The closest tutorial I've found on Youtube involves using JSON requests in Postman and I've had issue adapting that to a HTML registration form in the past.
I'm quite new to all of this so any help would be very much appreciated!
See Dish class:
package com.bron.demoJPA.appuser;
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
#Builder
#ToString(exclude = "reqlist")
public class Dish {
#Id
#SequenceGenerator(name = "dish_sequence", sequenceName = "dish_sequence", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "dish_sequence")
#Column(name = "dish_Id")
private Long dishId;
#Column(name = "dish_name")
private String dname;
#Column(name = "dish_description")
private String description;
#Column(name = "dish_price")
private double price;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "Rest_ID", referencedColumnName = "Rest_ID")
private AppUser app;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "dish_requirment_mapping", joinColumns = #JoinColumn(name = "dish_Id", referencedColumnName = "dish_Id"), inverseJoinColumns = #JoinColumn(name = "Require_ID", referencedColumnName = "Require_ID"))
private List<Requirments> reqlist;
public void addRequirments(Requirments req) {
if (reqlist == null)
reqlist = new ArrayList<>();
reqlist.add(req);
}
}
See AppUser(restaurant owner) Class
#Column(name = "Rest_Password")
private String password;
#Column(name = "Rest_Email_Address")
private String email;
#Enumerated(EnumType.STRING)
private AppUserRole appUserRole;
private Boolean locked = false;
// don't enable user until email verification
private Boolean enabled = false;
public AppUser(String restname, String email, String pass, AppUserRole app) {
this.restaurantName = restname;
this.email = email;
this.password = pass;
this.appUserRole = app;
}
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(appUserRole.name());
return Collections.singletonList(authority);
}
#Override
public String getUsername() {
return email;
}
#Override
public String getPassword() {
return password;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return !locked;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return enabled;
}
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = true)
#JoinColumn(name = "openingHourID", referencedColumnName = "OpeningHour_ID")
private OpeningHour opening;
}
See Controller class:
package com.bron.demoJPA.conroller;
#Controller
public class DishController {
//display list of employees
#Autowired
private DishService dishService;
#GetMapping("/dish")
public String viewHomePage(Model model) {
model.addAttribute("listDish", dishService.getAllDish());
return "index";
}
#GetMapping("/showNewDishForm")
public String showNewDishForm(Model model) {
// Create model attribute to bind form data
Dish dish = new Dish();
model.addAttribute("dish", dish);
return "new_dish";
}
#PostMapping("/saveDish")
public String saveDish(#ModelAttribute("dish") Dish dish) {
// save dish to database
dishService.saveDish(dish);
return "redirect:/dish";
}
#GetMapping("/showFormForUpdate/{dishId}")
public String showFormForUpdate(#PathVariable(value = "dishId") long dishId, Model model) {
// get dish from service
Dish dish = dishService.getDishByDishId(dishId);
// set dish as model to pre-populate the form data
model.addAttribute("dish", dish);
return "update_dish";
}
}
See Service implementation
package com.bron.demoJPA.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bron.demoJPA.appuser.Dish;
import com.bron.demoJPA.repository.DishRepository;
#Service
public class DishServiceImpl implements DishService {
#Autowired
private DishRepository dishRepository;
#Override
public List<Dish> getAllDish() {
return dishRepository.findAll();
}
#Override
public void saveDish(Dish dish) {
this.dishRepository.save(dish);
}
#Override
public Dish getDishByDishId(long dishId) {
Optional<Dish> optional = dishRepository.findById(dishId);
Dish dish = null;
if (optional.isPresent()) {
dish = optional.get();
} else {
throw new RuntimeException("Dish not found for: " + dishId);
}
return dish;
}
}
See Service class
public interface DishService {
List<Dish> getAllDish();
void saveDish(Dish dish);
Dish getDishByDishId(long dishId);
}
Can you make sure Dish's "app" attribute is being set correctly before trying to save it?
If it's null or it's a brand new instance of AppUser class it makes sense that when trying to match and persist it ends up on null.
Greetings!

Is there a way we can put the decorator /interceptor on all the objects that are being declared as field of a class?

I have a class Teacher which have two variables one is a collection of Student class and another is a Student class Object. I intercept the Teacher class as per my understanding all the objects under the Teacher class should have the interceptor attached to it.
so for instance one we call a getter method on the Student variable retrieved from the Teacher class or from the list .It should call the intercept method is not called.This makes our axiom for design false.So my question is : Is there a way we can automatically intercept all the objects declared within the class and this could extend to the further down hierarchy within the tree?
Below is the code :
//Teacher class
package com.anz.interceptorproject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by mehakanand on 4/24/16.
*/public class Teacher {
private String userName;
private String cource;
private List<Student> students=new ArrayList<Student>( );
public Student getComplexObjectStudent() {
return complexObjectStudent;
}
public void setComplexObjectStudent( Student complexObjectStudent ) {
this.complexObjectStudent = complexObjectStudent;
}
private Student complexObjectStudent=new Student();
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getCource() {
return cource;
}
public void setCource(String cource) {
this.cource = cource;
}
}
//Student Class
package com.anz.interceptorproject;
/**
* Created by mehakanand on 4/24/16.
*/public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
//Interceptor Class
package com.anz.interceptorproject.change;
import java.lang.reflect.*;
import net.sf.cglib.proxy.*;
/**
* Created by mehakanand on 4/24/16.
*/
public class ClassFacadeCglib implements MethodInterceptor{
private Object target;
public Object getInstance(Object target) {
this.target = target;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(this.target.getClass());
// callback method
enhancer.setCallback(this);
// create proxy object
return enhancer.create();
}
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
Object res=null;
if(method.getName().startsWith("set")){
System.out.println(method.getName()+" start");
res = method.invoke(target, args);
proxy.invokeSuper(obj, args);
System.out.println(method.getName()+" end..");
}
if(method.getName().startsWith("get")){
System.out.println(method.getName()+" start");
res = method.invoke(target, args);
proxy.invokeSuper(obj, args);
System.out.println(method.getName()+" end");
}
return res;
}
}
//Delegate class
package com.anz.interceptorproject;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import net.sf.cglib.proxy.MethodInterceptor;
import org.junit.Test;
public class SimpleUnitTest {
// this test is being used to test if when object is being intercepted will all its child object be intercepted automatically or not
#Test
public void TestifchildrenObjectIntercepted() {
String proxyStudentName="";
ClassFacadeCglib cglib=new ClassFacadeCglib();
Student studentMehak=new Student();
studentMehak.setAge( 30 );
studentMehak.setName( "Mehak Anand" );
Student studentComploexproxy=new Student();
studentComploexproxy.setAge( 23 );
studentComploexproxy.setName( "proxystudent Complex" );
//let us assume the Teacher object is an object return from JCR after the adapTo() function is called on a resource
Teacher teacher=new Teacher();
teacher.setComplexObjectStudent( studentComploexproxy );
teacher.getStudents().add( studentMehak );
teacher.setCource("Math");
teacher.setUserName("Mehak");
teacher.getUserName();
Teacher proxyTeacher=(Teacher)cglib.getInstance(teacher);
/ proxyTeacher.getClass().getDeclaredMethods();
for (Student proxyStudentList:proxyTeacher.getStudents())
{
//the intercept method is not called.
proxyStudentName= proxyStudentList.getName();
}
Student testComplexStudent=teacher.getComplexObjectStudent();
assertEquals("Math",proxyTeacher.getCource());
//the intercept method is not called
testComplexStudent.getAge();
System.out.println( teacher.getUserName());
assertTrue(true);
}
}
my understanding all the objects under the Teacher class should have the interceptor attached to it. so for instance one we call a getter method on the Student variable retrieved from the Teacher class or from the list .It should call the intercept method
This is not true. Method interceptors are attached only to the object created with enhancer.create(). Any object created with class constructor - such as your Student objects - are not enhanced and thus have no interceptors attached. The one possible solution is to use factory method instead of public constructor to produce enhanced objects:
public class Student {
protected Student() {
}
public static Student getInstance() {
Enhancer e = new Enhancer();
// set superclass, interceptors etc here....
return (Student) e.create();
}
}

Th:each iterate specific variables from a hashSet Thymeleaf Spring MVC

So I"m using Thymeleaf and spring MVC and I have a Course object which has a TreeSet of Posts and the set of posts are similar to a reddit post. I'm trying to represent a set of Posts, on a user homepage that I created. I want the posts to come in chronological order, in a newsfeed sort of way, and I already have the user's courses that they are subscribed to on the model.
My problem is that when I try to iterate through each of the posts I can only pull up the post's id, which looks something like this [com.quizbanks.domain.Post#26], and when I try to show the title, which is the variable for the title of the post I always get a spring processor error.
So here's what my thymeleaf code looks like
<table class="table table-bordered">
<tr th:each="course : ${courses}" th:object="${course}">
<td><span th:text="${course.posts}"></span></td>
</tr>
</table>
and then I tried this, but this gives me the spring processor error
<table class="table table-bordered">
<tr th:each="course : ${courses}" th:object="${course}">
<td><span th:text="${course.posts.title}"></span></td>
</tr>
</table>
So I'm not really sure what to do, if anyone can see my issue and help me out that would be great, thanks in advance.
Also if you want to see my controller code or anything else, let me know and I'll post it.
UPDATE
User Class
package com.quizbanks.domain;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.quizbanks.security.Authorities;
import com.quizbanks.validators.ValidEmail;
#Entity
#Table(name="users")
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "#id")
public class User
{
private Long id;
#ValidEmail
#NotNull
#NotEmpty
private String email;
private String username;
private String password;
private University university;
private Set<Authorities> authorities = new HashSet<>();
private Set<Course> courses = new HashSet<>();
private Set<Post> posts = new HashSet<>();
private Set<Comment> comments = new HashSet<>();
private Set<StudySet> studySet = new HashSet<>();
private Set<Course> myCourses = new HashSet<Course>();
public User ()
{
}
public User(User user)
{
this.id = user.getId();
this.email = user.getEmail();
this.username = user.getUsername();
this.password = user.getPassword();
this.university = user.getUniversity();
this.authorities = user.getAuthorities();
this.courses = user.getCourses();
this.posts = user.getPosts();
this.comments = user.getComments();
this.studySet = user.getStudySet();
this.myCourses = user.getMyCourses();
}
#Id
#GeneratedValue
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="user", orphanRemoval=true)
public Set<Course> getCourses()
{
return courses;
}
public void setCourses(Set<Course> courses)
{
this.courses = courses;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="user", orphanRemoval=true)
public Set<Post> getPosts() {
return posts;
}
public void setPosts(Set<Post> posts) {
this.posts = posts;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
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;
}
#ManyToOne
public University getUniversity() {
return university;
}
public void setUniversity(University university) {
this.university = university;
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="user")
#JsonManagedReference
#JsonIgnoreProperties(allowGetters=true, value = "user" )
public Set<Comment> getComments() {
return comments;
}
public void setComments(Set<Comment> comments) {
this.comments = comments;
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="user")
public Set<Authorities> getAuthorities()
{
return authorities;
}
public void setAuthorities(Set<Authorities> authorities)
{
this.authorities = authorities;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="user", orphanRemoval=true)
public Set<StudySet> getStudySet() {
return studySet;
}
public void setStudySet(Set<StudySet> studySet) {
this.studySet = studySet;
}
#ManyToMany(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
#JoinTable(name="user_myCourses")
public Set<Course> getMyCourses()
{
return myCourses;
}
public void setMyCourses(Set<Course> myCourses)
{
this.myCourses = myCourses;
}
}
Post Class
package com.quizbanks.domain;
import java.util.Set;
import java.util.TreeSet;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
#Entity
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "#id")
public class Course
{
private Long id;
#Size(min=1, max=50)
private String name;
#Size(min=1, max=50)
private String professor;
#Size(min=1, max=50)
private University university;
private Set<Post> posts = new TreeSet<>();
private User user;
#Id
#GeneratedValue
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
#ManyToOne
public User getUser()
{
return user;
}
public void setUser(User user)
{
this.user = user;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getProfessor()
{
return professor;
}
public void setProfessor(String professor)
{
this.professor = professor;
}
#ManyToOne
public University getUniversity() {
return university;
}
public void setUniversity(University university) {
this.university = university;
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="course")
public Set<Post> getPosts()
{
return posts;
}
public void setPosts(Set<Post> posts)
{
this.posts = posts;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Course other = (Course) obj;
if (id == null)
{
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
Post
package com.quizbanks.domain;
import java.util.Set;
import java.util.TreeSet;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
#Entity
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "#id")
public class Post
{
private Long id;
#Size(min=1, max=140)
#NotNull
private String title;
#Size(min=1, max=1000)
private String content;
private Course course;
private Set<Comment> comments = new TreeSet<>();
private User user;
#Id
#GeneratedValue
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#ManyToOne
public Course getCourse()
{
return course;
}
public void setCourse(Course course)
{
this.course = course;
}
#ManyToOne
public User getUser()
{
return user;
}
public void setUser(User user)
{
this.user = user;
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="post")
public Set<Comment> getComments() {
return comments;
}
public void setComments(Set<Comment> comments) {
this.comments = comments;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Post other = (Post) obj;
if (id == null)
{
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
Controller
#RequestMapping(value="{user}", method=RequestMethod.GET)
public String userPageGet (ModelMap model, #AuthenticationPrincipal User user)
{
List<User> usersList = userRepo.findAll();
model.addAttribute("usersList", usersList);
List<StudySet> studySets = studySetRepo.findByUser(user);
model.addAttribute("studySets", studySets);
List<Course> courses = courseRepo.findByUser(user);
model.addAttribute("courses", courses);
return "user";
}
${courses} is a list of Courses with posts set inside.
It seems that the problem is that posts is a TreeSet, so you should iterate for each element inside that set to get actual Posts and then get titles.
UPDATE:
List<Course> courses = courseRepo.findByUser(user); here you get all courses for your user. So, next step is to iterate over that list to get all posts:
Set<Post> posts = new TreeSet<>();
for (Course course : courses) {
posts.addAll(course.getPosts);
}
model.addAttribute("posts", posts);

How do i use abstraction to modify this class so it shows both colors of keys?

So Currently, our Key class can only produce white keys. This is because I have hard-coded the file names of the key images ("white-key.png" and "white-key-down.png"). How do I use abstraction to modify the Key class so that it can show either white or black keys?
import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot)
public class Key extends Actor
{
private boolean isDown;
private String key;
private String sound;
/**
* Create a new key.
*/
public Key(String keyName, String soundFile)
{
key = keyName;
sound = soundFile;
}
/**
* Do the action for this key.
*/
public void act()
{
if ( !isDown && Greenfoot.isKeyDown(key))
{
play();
setImage("white-key-down.png");
isDown = true;
}
if ( isDown && !Greenfoot.isKeyDown(key))
{
setImage("white-key.png");
isDown = false;
}
}
/**
* Play the note of this key.
*/
public void play()
{
Greenfoot.playSound(sound);
}
}
I understand from your question that you want different classes that have different images, rather than an option for changing the image within the same class.
There are several ways to do this; here's a simple one just to give you an idea:
import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot)
abstract public class Key extends Actor
{
private boolean isDown;
private String key;
private String sound;
abstract String getImageFileName();
abstract String getDownImageFileName();
/**
* Create a new key.
*/
public Key(String keyName, String soundFile)
{
key = keyName;
sound = soundFile;
}
/**
* Do the action for this key.
*/
public void act()
{
if ( !isDown && Greenfoot.isKeyDown(key))
{
play();
String image = getDownImageFileName();
setImage(image);
isDown = true;
}
if ( isDown && !Greenfoot.isKeyDown(key))
{
String image = getImageFileName();
setImage(image);
isDown = false;
}
}
/**
* Play the note of this key.
*/
public void play()
{
Greenfoot.playSound(sound);
}
}
Then you can add new classes, each with its own image:
public class WhiteKey extends Key
{
#Override
String getImageFileName()
{
return "white-key.png";
}
#Override
String getDownImageFileName()
{
return "white-key-down.png";
}
}
public class BlackKey extends Key
{
#Override
String getImageFileName()
{
return "black-key.png";
}
#Override
String getDownImageFileName()
{
return "black-key-down.png";
}
}

I am new In spring & Hibernate How To add profile image path in database using Springs 3 MVC

Value Object Class
package com.admin.modelVO;
import java.sql.Timestamp;
public class UserProfileVO{
private String userName;
private String password;
private String fName;
private String lName;
private String dob;
private String emailId;
private String contactNo;
private String gender;
private String photo;
private Timestamp createdDate;
private Boolean status;
private Integer rollId;
public Integer getRollId() {
return rollId;
}
public void setRollId(Integer rollId) {
this.rollId = rollId;
}
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 String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public Timestamp getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Timestamp createdDate) {
this.createdDate = createdDate;
}
}
Second Controller
package com.admin.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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 org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.admin.modelVO.UserProfileVO;
import com.admin.service.UserProfileService;
#Controller
public class UserProfileController{
#Autowired
UserProfileService userProfileService;
#RequestMapping(value="/userprofile1",method = RequestMethod.GET)
public String userprofile1(#ModelAttribute("UserProfileVO") UserProfileVO userProfileVO,ModelMap modelMap, HttpServletRequest request, HttpServletResponse response){
return "userprofile1";
}
#RequestMapping(value="/userprofile",method = RequestMethod.POST)
public String userprofile(#ModelAttribute("UserProfileVO") UserProfileVO userProfileVO,ModelMap modelMap, HttpServletRequest request, HttpServletResponse response,RedirectAttributes redirect){
String result=userProfileService.listUserProfile(userProfileVO);
request.setAttribute("userlist", result);
System.out.println("dfghdfg"+result);
return "success";
}
}
3.DaoImplement
package com.admin.daoImpl;
import java.sql.Timestamp;
import java.util.Date;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.admin.dao.UserProfileDao;
import com.admin.entity.Usermaster;
import com.admin.modelVO.UserProfileVO;
#Repository
public class UserProfileDaoImpl implements UserProfileDao{
#Autowired
SessionFactory sessionFactory;
Date date=new Date();
public String listUserProfile(UserProfileVO userProfileVO) {
String userId=null;
Usermaster userMaster=new Usermaster();
sessionFactory.getCurrentSession().beginTransaction();
userMaster.setUsername(userProfileVO.getUserName());
userMaster.setPassword(userProfileVO.getPassword());
userMaster.setFname(userProfileVO.getfName());
userMaster.setLname(userProfileVO.getfName());
userMaster.setDob(userProfileVO.getDob());
userMaster.setEmail(userProfileVO.getEmailId());
userMaster.setGender(userProfileVO.getGender());
userMaster.setContactNo(userProfileVO.getContactNo());
userMaster.setPhoto(userProfileVO.getPhoto());
userMaster.setStatus(true);
userMaster.setCreatedDate(date);
userMaster.setRoleId(2);
sessionFactory.getCurrentSession().save(userMaster);
System.out.println("dsfsf"+userMaster);
sessionFactory.getCurrentSession().getTransaction().commit();
return userId;
}
}
I want to upload profile picture with registration page and i want to set contxt path on database and image is perticulor folder. i will post you DaoImpl VO and Controller where we put the code and my object is "PHOTO" so i want to stored it
You can refer following method to handle image uploading i.e. multipart request. You can not this method directly in your code. This is for understanding only.
For this you will need :
commons-fileupload.jar
and
commons-io.jar
public String handleFileUpload(HttpServletRequest request,
#RequestParam CommonsMultipartFile[] fileUpload) throws Exception {
System.out.println("description: " + request.getParameter("description"));
if (fileUpload != null && fileUpload.length > 0) {
for (CommonsMultipartFile aFile : fileUpload) {
System.out.println("Saving file: " + aFile.getOriginalFilename());
if (!aFile.getOriginalFilename().equals("")) {
aFile.transferTo(new File(saveDirectory + aFile.getOriginalFilename()));
}
}
}
// returns to the view "Result"
return "Result";
}
Here: "saveDirectory" string variable can be any path on your server, where you want to store files.
in configuration you will need to add:
#Bean(name = "multipartResolver")
public CommonsMultipartResolver getMultipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxInMemorySize(1048576);
multipartResolver.setMaxUploadSize(20971520);
return multipartResolver;
}
EDIT :
// get absolute path of the application
ServletContext context = request.getServletContext();
String saveDirectory = context.getRealPath("");
System.out.println("saveDirectory = " + saveDirectory);
You dont have to store whole path to the file. Just store file name (that you can give any unique name every time). So in DAOImpl write code for storing filename.

Resources