My first controller is Login
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import javax.servlet.http.HttpSession;
import java.io.IOException;
#Controller
#SessionAttributes("session")
public class LoginController extends GlobalController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String indexAction() throws IOException {
return "login";
}
#RequestMapping(value = "/", method= RequestMethod.POST)
public String indexAction(#RequestParam String username, #RequestParam String password,HttpSession session) {
String page = "login";
if(username != "" && password != ""){
try {
if(userService.authenticationUser(username,password) == "success"){
page = "redirect:/main";
session.setAttribute("test","Salom");
//this.httpSession =session;
//System.out.println(session.getAttribute("test"));
}
else page = "login";
}
catch (Exception e){
e.fillInStackTrace();
}
}
else page = "login";
return page;
}
}
My second Controller is Test
package com.springboot.app.controllers.reports;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import javax.servlet.http.HttpSession;
#SessionAttributes("session")
public class TestController {
#RequestMapping(value = "/test",method = RequestMethod.GET)
public String index(){
#SessionAttributes("session")HttpSession session;
return "";
}
}
---------------------------------------------------------------------------- How to pass #SessionAttributes("session") from login Controller to Test controller or how to store #SessionAttributes("session") in variable
#SessionAttributes is not intended to be used (and will not work also) to store objects in the session between different controllers. The controller annotated with #SessionAttributes must also tell that it is finished (so controllerA not ControllerB). The model message from controller a is still not available for controller B.
see this conversation
you can pass from LoginController to TestController:
e.g. Username = name
LoginController:
import org.springframework.ui.ModelMap;
#Controller
#SessionAttributes("name")
public class LoginController{
#RequestMapping(value="/login", method = RequestMethod.POST)
public String showWelcomePage(ModelMap model, #RequestParam String name, #RequestParam String password){
boolean isValidUser = service.validateUser(name, password);
if (!isValidUser) {
model.put("errorMessage", "Invalid Credentials");
return "login";
}
model.put("name", name);
model.put("password", password);
return "welcome";
TestController:
#SessionAttributes("name")
public void showUsername(ModelMap model){
System.out.println("Username is: " + (String) model.get("name");
}
}
hope there is no typo!
Related
Unable to go to Servlet from hello.jsp to MainController Class. This is a maven project.
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class MainController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String welcome() {
return "Hello";
}
#RequestMapping("displayname")
public String displayName(HttpServletRequest request) {
System.out.println("Working till here");
String firstName = request.getParameter("firstName");
request.setAttribute("firstName", firstName);
return "displayName";
}
}
#RequestMapping(value = "/displayname", method = RequestMethod.POST)
public String displayName(HttpServletRequest request) {
System.out.println("Working till here");
String firstName = request.getParameter("firstName");
request.setAttribute("firstName", firstName);
return "displayName";
}
You can change method parameter on requestmapping annotation. Also you can get body in displayName method and redirect it. I checked that method is empty when it is not defined. Maybe you can use #PostMapping annotation and other annotations like #GetMapping, #PostMapping etc...
I mimic tutorial at https://howtodoinjava.com/spring-webflux/spring-webflux-tutorial/ . My MongoDB (My version https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-5.0.5-signed.msi). Postman v9.8.0 , Windows 10 x64.
My controller
package com.howtodoinjava.demo.controller;
import com.howtodoinjava.demo.model.Employee;
import com.howtodoinjava.demo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.Duration;
#RestController
public class EmployeeController {
#Autowired
private EmployeeService employeeService;
#RequestMapping(value = {"/create", "/"}, method = RequestMethod.POST)
#ResponseStatus(HttpStatus.CREATED)
#ResponseBody
public void create(#RequestBody Employee e) {
employeeService.create(e);
}
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<Mono<Employee>> findById(#PathVariable("id") Integer id) {
Mono<Employee> e = employeeService.findById(id);
HttpStatus status = e != null ? HttpStatus.OK : HttpStatus.NOT_FOUND;
return new ResponseEntity<Mono<Employee>>(e, status);
}
#RequestMapping(value = "/name/{name}", method = RequestMethod.GET)
#ResponseBody
public Flux<Employee> findByName(#PathVariable("name") String name) {
return employeeService.findByName(name);
}
#RequestMapping(method = RequestMethod.GET, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
#ResponseBody
public Flux<Employee> findAll() {
// Flux<Employee> emps = employeeService.findAll();
Flux<Employee> emps = employeeService.findAll().log().delayElements(Duration.ofSeconds(1));
emps.subscribe();
return emps;
}
#RequestMapping(value = "/update", method = RequestMethod.PUT)
#ResponseStatus(HttpStatus.OK)
public Mono<Employee> update(#RequestBody Employee e) {
return employeeService.update(e);
}
#RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
#ResponseStatus(HttpStatus.OK)
public void delete(#PathVariable("id") Integer id) {
employeeService.delete(id).subscribe();
}
}
In debug console, I see the result
The reason why the responses are empty is that no getter methods are defined in the Employee entity class. Adding the following should make it work:
public int getId() {
return id;
}
public String getName() {
return name;
}
public long getSalary() {
return salary;
}
As a side note, consider mapping your entities into EmployeeDTO instances.
I can login and logout, and display a list of users on a page doing this:
<li th:each="user : ${users}">
<span th:text="${user.firstname}+' '+${user.lastname}"></span>
</li>
I would now simply like to display the name of the currently logged in user, but I am not sure how. I would like to add it to a header fragment so every page shows clearly who the user logged in is.
LoginForm.java:
package com.demo.spring.domain;
import org.hibernate.validator.constraints.NotEmpty;
public class LoginForm {
public String getAccountname() {
return accountname;
}
public void setAccountname(String accountname) {
this.accountname = accountname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#NotEmpty
String accountname;
#NotEmpty
String password;
}
login.html:
<h3>User Login</h3>
<form action="#" th:action="#{/user/login}" th:object="${user}" method="post">
<!--<input type="hidden" th:field="*{id}"/>-->
<p>Account Name:</p> <input type="text" th:field="*{accountname}"/>
<p>Password:</p> <input type="password" th:field="*{password}"/>
<p/><input type="submit" value="Login"/>
</form>
<div th:if="${message!=null}">
<br/>
<span th:text="${message}"/>
</div>
UserController code for logging in:
package com.demo.spring.controller;
import com.demo.spring.domain.LoginForm;
import com.demo.spring.domain.User;
import com.demo.spring.domain.UserSearchForm;
import com.demo.spring.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;
#Controller
#RequestMapping(value = "/user")
public class UserController {
#Autowired
UserService userService;
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginView(Model model)
{
LoginForm user = new LoginForm();
model.addAttribute("user", user);
return "login";
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(Model model, #Valid #ModelAttribute("user") LoginForm user, BindingResult bindingResult, HttpSession session)
{
if(bindingResult.hasErrors())
{
model.addAttribute("user", user);
model.addAttribute("message", "Please provide information in each field");
return "login";
}
if (userService.validateLogin(user)==false)
{
model.addAttribute("user", user);
model.addAttribute("message", "Your accountname and/or password are incorrect");
return "login";
}
session.setAttribute("login", true);
return "redirect:/";
}
UserService
package com.demo.spring.service;
import com.demo.spring.domain.LoginForm;
import com.demo.spring.domain.UserSearchForm;
import com.demo.spring.domain.User;
import com.demo.spring.domain.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class UserService {
public boolean validateLogin(LoginForm user)
{
List<User> users = userRepository.checkUserInput(user.getAccountname(),user.getPassword());
return users !=null && users.size()>0;
}
We put the logged in users' name in the session
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(Model model, #Valid #ModelAttribute("user") LoginForm user, BindingResult bindingResult, HttpSession session)
{
...
session.setAttribute("accountName", user.getAccountName());
session.setAttribute("login", true);
return "redirect:/";
}
Once put in the session, the session variables can simply be accessed as ${session.accountName}. So you can use <span th:text="${session.accountName}"></span> in your header fragment.
I am getting an error as No qualifying bean of type 'com.springmvc.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate. for the following code, My base class is "com.springmvc"
My Controller Class is
package com.springmvc.controller;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.bind.annotation.RequestParam;
import com.springmvc.dao.UserDAO;
import com.springmvc.dao.UserDAOImpl;
import com.springmvc.type.User;
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
private UserDAO usrdao;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("Date", formattedDate );
return "index";
}
/*
#RequestMapping(value="/login",method = RequestMethod.POST)
public String welcome(Locale locale,Model model,#ModelAttribute("LoginBean")LoginBean login){
if(login != null && login.getUserName() != "" && login.getPassword() != ""){
if(login.getUserName().equals("ajith") && login.getPassword().equals("123")){
model.addAttribute("msg","Welcome "+login.getUserName());
return "welcome";
}
else{
model.addAttribute("error","Invalid Login Details");
return "index";
}
}
else{
model.addAttribute("error","Please Enter Login Details");
return "index";
}
}
*/
#RequestMapping(value="/checkLogin",method = RequestMethod.POST)
public String CheckUser(Model model,#ModelAttribute("User")User user){
if(user != null && user.getUserName() != "" && user.getPass() != ""){
boolean isActive = usrdao.isActiveUser(user.getUserName(), user.getPass());
if(isActive){
List<User> usrLst = usrdao.ListAllUsers();
model.addAttribute("message",user.getUserName());
model.addAttribute("usrLst",usrLst);
return "home";
}
else{
model.addAttribute("error","Invalid Login Details");
return "index";
}
}
return "index";
}
#RequestMapping(value="/createUser", method = RequestMethod.GET)
public String RedirectCreateUser(Model model){
return "createUser";
}
public String createUser(Model model, #ModelAttribute User user){
usrdao.CreateOrUpdateUser(user);
return "";
}
}
UserDAO
package com.springmvc.dao;
import java.util.List;
import com.springmvc.type.User;
public interface UserDAO {
public void CreateOrUpdateUser(User user);
public void DeleteUser(int uid);
public User GetUser(int uid);
public List<User> ListAllUsers();
public boolean isActiveUser(String userName,String pass);
}
UserDAOImpl
package com.springmvc.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Repository;
import com.springmvc.type.User;
#Repository("UserDAO")
public class UserDAOImpl implements UserDAO {
private JdbcTemplate jdbc;
/*
public void setJdbc(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
*/
public UserDAOImpl(DataSource DS) {
jdbc = new JdbcTemplate(DS);
}
#Override
public void CreateOrUpdateUser(User user) {
if(user.getUid() == 0){
String query = "INSERT INTO userdetails(UserName,Name,Pass) VALUES(?,?,?)";
jdbc.update(query,user.getUserName(),user.getName(),user.getPass());
}
else{
String query = "UPDATE userdetails SET UserName = ?,Name = ?,Pass = ?,isActive = ? WHERE id = ?";
jdbc.update(query, user.getUserName(),user.getName(),user.getPass(),user.getIsActive(),user.getUid());
}
}
#Override
public void DeleteUser(int uid) {
String query = "DELETE FROM userdetails WHERE id = ?";
jdbc.update(query, uid);
}
#Override
public User GetUser(int uid) {
String query = "SELECT * FROM userdetails WHERE id = ?";
return jdbc.query(query, new ResultSetExtractor<User>() {
#Override
public User extractData(ResultSet rs) throws SQLException, DataAccessException {
if(rs.next()){
User user = new User();
user.setUid(rs.getInt("id"));
user.setUserName(rs.getString("UserName"));
user.setName(rs.getString("Name"));
user.setIsActive(rs.getInt("isActive"));
return user;
}
return null;
}
});
}
#Override
public List<User> ListAllUsers() {
String query = "SELECT * FROM userdetails";
List <User> usrLst = jdbc.query(query, new RowMapper<User>() {
#Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setUid(rs.getInt("id"));
user.setUserName(rs.getString("UserName"));
user.setName(rs.getString("Name"));
user.setIsActive(rs.getInt("isActive"));
return user;
}
});
return usrLst;
}
#Override
public boolean isActiveUser(String userName, String pass) {
String query = "SELECT id FROM userdetails WHERE UserName = ? AND Pass = ? AND isActive = 1";
SqlRowSet rs = jdbc.queryForRowSet(query,userName,pass);
if(rs.next())
return true;
else
return false;
}
}
Thank You
UserDAOImpl do not have default constructor. either add default constructor or autowire the construction arg.
Spring is using a strong naming convention.
Try to use as a variable userDao as the autowired variable and use the same string in the #repository.
See this little explanation here:
https://www.tutorialspoint.com/spring/spring_beans_autowiring.htm
Does anyone have a full spring boot REST CRUD example? The spring.io site just has a RequestMapping for GET. I'm able to get POST and DELETE working but not PUT.
I suspect it's how I'm trying to get the params where the disconnect is, but I have not seen an example where someone is performing an update.
I'm currently using the SO iPhone app so I can't paste my current code. Any working examples would be great!
As you can see I have implemented two way to update.
The first one will receive a json, and the second one will receive the cusotmerId in the URL and json also.
#RestController
#RequestMapping("/customer")
public class CustomerController {
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Customer greetings(#PathVariable("id") Long id) {
Customer customer = new Customer();
customer.setName("Eddu");
customer.setLastname("Melendez");
return customer;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public List<Customer> list() {
return Collections.emptyList();
}
#RequestMapping(method = RequestMethod.POST)
public void add(#RequestBody Customer customer) {
}
#RequestMapping(method = RequestMethod.PUT)
public void update(#RequestBody Customer customer) {
}
#RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public void updateById(#PathVariable("id") Long id, #RequestBody Customer customer) {
}
#RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public void delete() {
}
class Customer implements Serializable {
private String name;
private String lastname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getLastname() {
return lastname;
}
}
}
An alternative update returns ResponseEntity object.
#RestController
#RequestMapping("/fruits")
public class FruitController {
private final Logger LOG = LoggerFactory.getLogger(FruitController.class);
#Autowired
private FruitService fruitService;
#RequestMapping(method = RequestMethod.GET)
public ResponseEntity<List<Fruit>> getAll(#RequestParam(value = "offset", defaultValue = "0") int index,
#RequestParam(value = "numberOfRecord", defaultValue = "10") int numberOfRecord) {
LOG.info("Getting all fruits with index: {}, and count: {}", index, numberOfRecord);
List<Fruit> fruits = fruitService.getAll(index, numberOfRecord);
if (fruits == null || fruits.isEmpty()) {
return new ResponseEntity<List<Fruit>>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<Fruit>>(fruits, HttpStatus.OK);
}
#RequestMapping(value = "{id}", method = RequestMethod.GET)
public ResponseEntity<Fruit> get(#PathVariable("id") int id) {
LOG.info("Getting fruit with id: {}", id);
Fruit fruit = fruitService.findById(id);
if (fruit == null) {
return new ResponseEntity<Fruit>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<Fruit>(fruit, HttpStatus.OK);
}
#RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Void> create(#RequestBody Fruit fruit, UriComponentsBuilder ucBuilder) {
LOG.info("Creating fruit: {}", fruit);
if (fruitService.exists(fruit)) {
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
fruitService.create(fruit);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/fruit/{id}").buildAndExpand(fruit.getId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
#RequestMapping(value = "{id}", method = RequestMethod.PUT)
public ResponseEntity<Fruit> update(#PathVariable int id, #RequestBody Fruit fruit) {
LOG.info("Updating fruit: {}", fruit);
Fruit currentFruit = fruitService.findById(id);
if (currentFruit == null) {
return new ResponseEntity<Fruit>(HttpStatus.NOT_FOUND);
}
currentFruit.setId(fruit.getId());
currentFruit.setName(fruit.getName());
fruitService.update(fruit);
return new ResponseEntity<Fruit>(currentFruit, HttpStatus.OK);
}
#RequestMapping(value = "{id}", method = RequestMethod.DELETE)
public ResponseEntity<Void> delete(#PathVariable("id") int id) {
LOG.info("Deleting fruit with id: {}", id);
Fruit fruit = fruitService.findById(id);
if (fruit == null) {
return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
}
fruitService.delete(id);
return new ResponseEntity<Void>(HttpStatus.OK);
}
}
From Spring MVC RESTFul Web Service CRUD Example
I have prepared a set of tutorials on Spring Boot CRUD Operations. Following are the content of tutorials:
How to create Spring Boot Project using Spring Tool Suite
How to implement GET & POST method in spring boot restful web service
How to implement PUT & DELETE method in spring boot restful web service
Integrate PostgreSQL database using spring boot JPA with spring boot restful web service
Use of CURL commands
Youtube Tutorials:
Spring Boot Restful Web Service Tutorial | Tutorial 1 -
Introduction
Spring Boot Restful Web Services CRUD Example GET & POST | Tutorial - 2
Spring boot CRUD Operations example PUT & DELETE | Tutorial - 3
Spring Boot JPA | In 5 Simple Steps Integrate PostgreSQL Database | Tuorial - 4
Visit Blog for more details.
You can get my full RESTful server and client app using SpringBoot at Spring RESTFul Examples at github
package com.controllers;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.cats.hcm.bussinessObjects.Address;
import com.cats.hcm.bussinessObjects.Employee;
import com.cats.hcm.bussinessObjects.EmployeeBO;
import com.cats.hcm.bussinessObjects.MaritalStatus;
import com.cats.hcm.bussinessObjects.State;
import com.cats.hcm.repository.EmployeeRepositoryImpl;
import com.cats.hcm.repository.MaritalStatusRepositoryImpl;
import com.cats.hcm.repository.Repository;
import com.cats.hcm.repository.StateRepositoryImpl;
import com.cats.hcm.services.EmployeeServiceImpl;
import com.google.gson.Gson;
#Controller
#RequestMapping("/newemployee")
public class NewEmployeeController {
private static final Logger logger = LoggerFactory.getLogger(Repository.class);
#Autowired
Repository repository;
#Autowired
StateRepositoryImpl stateRepositoryImpl;
#Autowired
MaritalStatusRepositoryImpl maritalStatusRepositoryImpl;
#Autowired
EmployeeRepositoryImpl employeeRepositoryImpl;
#Autowired
EmployeeServiceImpl employeeServiceImpl;
#RequestMapping(value="/save", method=RequestMethod.POST)
public #ResponseBody String addEmployee(#RequestBody EmployeeBO employeeBO, BindingResult bindingResult) throws SecurityException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException, IOException {
logger.info("==========="+new Gson().toJson(employeeBO));
logger.info("========Employee ID========"+employeeBO.getEmployeeId());
repository.addToDataBase(employeeBO);
String msg="Success";
return msg;
}
#RequestMapping(value="/update", method=RequestMethod.POST)
public #ResponseBody String updateEmployee(#RequestBody EmployeeBO employeeBO, BindingResult bindingResult) throws SecurityException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException, IOException {
logger.info("==========="+new Gson().toJson(employeeBO));
logger.info("========Employee ID========"+employeeBO.getEmployeeId());
//Deleting Existing Employee
Boolean isDeleted = employeeServiceImpl.deleteEmployeeDetails(employeeBO.getEmployeeId());
if(isDeleted) {
repository.addToDataBase(employeeBO);
}
String msg="Success";
return msg;
}
#RequestMapping("/employeeData")
public #ResponseBody List<Employee> getEmployeeDataTablePage() {
logger.info("======getEmployeeDataTablePage======");
List<Employee> employeeList = employeeRepositoryImpl.readAll();
logger.info("========EmployeeList========="+new Gson().toJson(employeeList));
return employeeList;
}
#RequestMapping("/modifyPage")
public #ResponseBody List<Employee> getEmployeeModifyPage(#RequestParam("employeeId") String employeeId) {
logger.info("========getEmployeeModifyPage====EmployeeID:===="+employeeId);
//List<State> stateList = stateRepositoryImpl.readAll();
//List<MaritalStatus> maritalStatusList = maritalStatusRepositoryImpl.readAll();
//model.addAttribute("stateList", stateList);
//model.addAttribute("maritalStatusList", maritalStatusList);
List<Employee> employeeList = employeeRepositoryImpl.readAll();
logger.info("========employeeList:===="+employeeList);
EmployeeBO employeeBO = employeeServiceImpl.getEmployeeBO(employeeId);
logger.info("========getEmployeeModifyPage====EmployeeBO:===="+employeeBO);
return employeeList;
//return new ModelAndView("apps-mod-employee", "employee", employeeBO);
}
#RequestMapping("/delete")
public #ResponseBody String deleteEmployee(#RequestParam("employeeId") String employeeId) {
logger.info("========deleteEmployee===EmployeeID:===="+employeeId);
//employeeRepositoryImpl.delete(employeeServiceImpl.getEmployeeBO(employeeId));
Boolean isDeleted = employeeServiceImpl.deleteEmployeeDetails(employeeId);
if(isDeleted) {
logger.info("========Employee Record Deleted===EmployeeID:===="+employeeId);
}
return "redirect:/employee/employeeDataTable";
}
/*#RequestMapping("/employeeDataByEmpId")
public String getEmployeeAddPage(Map<String, Object> model) {
public ModelAndView getEmployeeDataByEmpId(ModelMap model,HttpServletRequest request, HttpServletResponse response) {
logger.info("======getEmployeeDataByEmpId======");
String EmployeeID=request.getParameter("empId");
Employee employee = employeeRepositoryImpl.read(EmployeeID);
logger.info("========Employee========="+new Gson().toJson(employee));
model.addAttribute(new EmployeeBO());
model.addAttribute("employeeByEmpId", employee);
//return "apps-add-employee";
//return new ModelAndView("apps-add-employee");
return new ModelAndView("apps-employee", "employee", new EmployeeBO());
}*/
}