What is the problem here , i am learning spring boot - spring

#PostMapping("/addStudent")
String addStudent(#ModelAttribute ("student")Students student, Model model) {
model.addAttribute("fname", fname);
model.addAttribute("lname", lname);
model.addAttribute("dob", dob);
model.addAttribute("mobile", mobile);
model.addAttribute("address", address);
Students student = new Students();
student.setFname(fname);
student.setLname(lname);
student.setDob(dob);
student.setMobile(mobile);
student.setAddress(address);
studentsRepository.save(student);
return "index";
}

Related

Spring Boot - GET atributes in common from repository jpa

I started working with spring boot's rest API and ended up having some specific problems returning the last two topics
1- GET animals/number/{number}
You should list the animals with the number/code {number}
2- GET animals/name/{name}
You should list the animals with the name {name}
3- GET animals/species/{species}
You should list the animalsof the species {species}. Note, more than one animal can be returned for each species.
4- GET animals /type/{type}
You should list the animals of the type {type}. Note, more than one animal can be returned for each type. Due to the nature of this field, you should perform a substring search. For example, the value “poison” for the {type} should return the animals with the type "reptile/Poison".
what I got
#RequestMapping(value="/animals/number/{number}", method=RequestMethod.GET)
public ResponseEntity<?> getNumber(#PathVariable(name = "number") String number) {
Optional<Animal> o = repository.findByNumber(number);
if (!o.isPresent())
return new ResponseEntity<>(o, HttpStatus.NOT_FOUND);
return new ResponseEntity<>(o, HttpStatus.FOUND);
}
#RequestMapping(value="/animals/name/{name}", method=RequestMethod.GET)
public ResponseEntity<?> getName(#PathVariable(name = "name") String name) {
Optional<Animal> o = repository.findByName(name);
if (!o.isPresent())
return new ResponseEntity<>(o, HttpStatus.NOT_FOUND);
return new ResponseEntity<>(o, HttpStatus.FOUND);
}
I tried to do topic 3 but I'm not able to:
#RequestMapping(value="/animals/species/{species}", method=RequestMethod.GET)
public ResponseEntity<?> getSpecies(#PathVariable(name = "species") String species) {
List<Animal> p = repository.findAll();
if (species == null)
repository.findAll().forEach(p::contains);
else
repository.findByTitleContaining(species).forEach(p::contains);
if (p.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(p, HttpStatus.OK);
}
#Repository
public interface AnimalRepository extends JpaRepository<Animal, Integer> {
Optional<Animal> findByNumber(String number);
Optional<Animal> findByName(String name);
Optional<Animal> findByspecie(String species);
}
i put for test //localhost:8081/animals/name/Animalname
You can query all animals matching the searched specie using a Spring Data generated query (as the one you seem to have defined):
List<Animal> findByTitleContaining(String specie);
Then you can group the returned elements using the java.util.stream.Collectors#groupingBy using the Animal types:
#RequestMapping(value="/animals/species/{species}", method=RequestMethod.GET)
public ResponseEntity<?> getSpecies(#PathVariable(name = "species") String species) {
List<Animal> matchingAnimals = repository.findByTitleContaining(species);
if (!matchingAnimals.isEmpty()) {
final Map<String, List<Animal>> groupedAnimals = matchingAnimals.stream()
.collect(Collectors.groupingBy(Animal::getType));
return new ResponseEntity<>(groupedAnimals, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}

Spring mvc when editing , user can't validate

I have a user registration application in spring mvc.
When saving the user class, it normally validates the user and saves according to my UserValidator class, but when editing the same user, I can't validate in the same way.it goes to endless loop.
this is the case when saving
#RequestMapping(value = "/registration", method = RequestMethod.GET)
public String registration(Model model) {
model.addAttribute("userForm", new User());
return "registration";
}
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(#ModelAttribute("userForm") User userForm, BindingResult bindingResult, HttpServletRequest request) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.saveUser(userForm);
securityService.autologin(userForm.getUsername(), userForm.getPasswordConfirm());
LOGGER.info("user with username %s successfully registered", userForm.getUsername());
return "redirect:/welcome";
}
this one is the case when editing
#RequestMapping(value = {"/edit-user-{id}"}, method = RequestMethod.GET)
public String editUser(#PathVariable Long id, ModelMap model) {
User user = userService.findById(id);
if (!user.getUsername().equals(context.getUserPrincipal().getName())) {
return "login";
}
model.addAttribute("userForm", user);
model.addAttribute("edit", true);
return "registration";
}
#RequestMapping(value = {"/edit-user-{id}"}, method = RequestMethod.POST)
public String updateUser(#Valid User userForm, BindingResult bindingResult, ModelMap model, #PathVariable Long id) {
model.addAttribute("edit", true);
model.addAttribute("success", "User " + userForm.getFirstName() + " " + userForm.getLastName() + " updated successfully");
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.updateUser(userForm);
return "registrationsuccess";
}
anybody please help, what is wrong with this code, when I press the edit button, it does nothing, like it falls into endless loop.
The Problem solved by changing the code
if (bindingResult.hasErrors()) {
return "registration";
}
to
if (bindingResult.hasErrors()) {
return "forward:/registration";
}

Render a view based on the conditional statement in Spring

I am kind of new to Spring. I am trying to render a view based on the the value returned from DBDAOImplementation class using a conditional if statement inside processController. I am trying to return successuseraddstatus jsp file for success scenarios and faileduseraddstatus jsp file for failed scenarios.
ProcessController.java:
#RequestMapping(value = "/adduserstatus", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb")Process process,ModelMap model) {
model.addAttribute("fname", process.getFname());
model.addAttribute("lname", process.getLname());
model.addAttribute("email", process.getEmail());
model.addAttribute("phone", process.getPhone());
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
DBDAOImp dbd =
(DBDAOImp)context.getBean("JDBCTemplate");
dbd.createuser(process.getFname(), process.getLname(), process.getEmail(), process.getPhone());
if (true){ //This is where I am having trouble
return "successuseraddstatus";
}
return "faileduseraddstatus";
}
DBDAOImplementation.java:
#Override
public Boolean createuser(String fname, String lname, String email, String phone) {
isExists(email);
if (isExists==false){
String SQL = "insert into USERS (user_id,f_name,l_name,creation_date,email,phone) values (seq_users.nextval,?,?,sysdate,?,?)";
jdbcTemplateObject.update( SQL, fname,lname,email,phone);
System.out.println("Created Record");
return true;
} else {
return false;
}
}
Below if condition works. But I am not too sure if this is the right approach.
ProcessController.java:
#RequestMapping(value = "/adduserstatus", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb")Process process,ModelMap model) {
model.addAttribute("fname", process.getFname());
model.addAttribute("lname", process.getLname());
model.addAttribute("email", process.getEmail());
model.addAttribute("phone", process.getPhone());
DBDAOImp dbd =
(DBDAOImp)context.getBean("JDBCTemplate");
if (dbd.createuser(process.getFname(), process.getLname(), process.getEmail(), process.getPhone())){
return "useraddstatus";
} else {
return "faileduseraddstatus";
}
}

How to list data from database in a web page in spring framework

I have created a database called student base on the tutorial provided by tutorials point PDF, they have covered how to map the form and insert values in to the database using controllers, but they have not explained how to display the data from the database on to the webpage.
My code to list all students.
#Override
public List<Student> listStudents() {
String SQL = "select * from Student";
List<Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
return students;
}
How to call this from my controller in spring and return the list to my webpage.
My contoller is given below
#Controller
public class StudentController {
#RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student()
{
return new ModelAndView("student", "command", new Student());
}
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb")Student student, ModelMap model)
{
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
studentJDBCTemplate.create(student.getName(), student.getAge());
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("msg", "Student Enrolled");
return "result";
}
// How to write the listing controller?
}
From the details you provide ,
public String ListStudents(ModelMap model)
{
List<Student> list= YourServiceClassObj.listStudents();
model.addAttribute("result", list);
return "View Name here";
}
public class AccountDAO {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
public Account getAll(String user, String pass) {
String query = "SELECT * FROM dbo.USERR WHERE username=? AND password =?";
try {
conn = new DBContext().getConnection();
ps = conn.prepareStatement(query);
ps.setString(1, user);
ps.setString(2, pass);
rs = ps.executeQuery();
while (rs.next()) {
return new Account(rs.getString(1),
rs.getString(2),
rs.getString(3));
}
} catch (Exception e) {
}
return null;
}
}
your controller and service methods should be like this .and then in the view use the controller returned attribute students.
#Controller
#RequestMapping(value = "/students", method = RequestMethod.GET)
public String students(ModelMap model)
{
List<Student> students= studentService.getStudents();
model.addAttribute("students", students);
return "student/studentList.html";
}
Service :
public interface StudentService {
List<Student> getStudents();
}
#Service
public class StudentServiceImpl implements StudentService {
#Override
public List<Student> getStudents() {
return studentRepository.findAll();
}

Spring : timely/late binding of #ModelAttribute

I'm using the following code to bind the users to the model [to be used in the view/jsp]:
#ModelAttribute("users")
public Collection<User> populateUsers() {
return userService.findAllUsers();
}
But sometimes I just need to load few users with a particular Role, which I'm trying by using the following code:
int role = 2; //this is being set in a Controller within a method #RequestMapping(method = RequestMethod.GET) public String list(
#ModelAttribute("users")
public Collection<User> populateUsers() {
if(role == 2)
return userService.findAllUsersByRole(role);
else
return userService.findAllUsers();
}
but the populateUsers is always called at the start of the controller, before the role is set in list method, Could you please help me on how to set the users [something like late binding]
Regards
-- adding code
#Controller
#RequestMapping("/users")
public class UserController {
#Autowired
UserService userService;
#RequestMapping(method = RequestMethod.POST)
public String create(#Valid User user, BindingResult bindingResult,
Model uiModel, HttpServletRequest httpServletRequest) {
if (bindingResult.hasErrors()) {
uiModel.addAttribute("user", user);
addDateTimeFormatPatterns(uiModel);
return "users/create";
}
uiModel.asMap().clear();
userService.saveUser(user);
return "redirect:/users/"
+ encodeUrlPathSegment(user.getId().toString(),
httpServletRequest);
}
#RequestMapping(params = "form", method = RequestMethod.GET)
public String createForm(Model uiModel) {
uiModel.addAttribute("user", new User());
addDateTimeFormatPatterns(uiModel);
return "users/create";
}
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String show(#PathVariable("id") Long id, Model uiModel) {
addDateTimeFormatPatterns(uiModel);
uiModel.addAttribute("user", userService.findUser(id));
return "users/show";
}
#RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
public String updateForm(#PathVariable("id") Long id, Model uiModel) {
uiModel.addAttribute("user", userService.findUser(id));
addDateTimeFormatPatterns(uiModel);
return "users/update";
}
#ModelAttribute("users")
public Collection<User> populateUsers() {
return userService.findAllUsers();
}
#ModelAttribute("userroles")
public Collection<UserRole> populateUserRoles() {
return Arrays.asList(UserRole.class.getEnumConstants());
}
void addDateTimeFormatPatterns(Model uiModel) {
uiModel.addAttribute(
"user_modified_date_format",
DateTimeFormat.patternForStyle("M-",
LocaleContextHolder.getLocale()));
}
}
#PathVariable("id") Long id is the ID I require in populateUsers, hope it is clear.
If role is in the current request, this method binding role to variable role.
#ModelAttribute("users")
public Collection<User> populateUsers(#RequestParam(required=false) Integer role) {
if(role != null && role == 2)
return userService.findAllUsersByRole(role);
else
return userService.findAllUsers();
}
Setting the model attribute in the required method has solved my issue:
model.addAttribute("users", return userService.findAllUsersByRole(role));
Thanks!

Resources