I'm pretty much completely new to the world of computer programming, so it's been something of a struggle getting a really in depth understanding of many concepts. Right now, I'm working on a project in which we are implementing Spring MVC. The first step in the project is to make a login page for a website. I've tried modelling mine after one that we did in class, but I can't seem to get past the following error in my web browser:
Unsupported auto value type java.lang.String for field injuryReports.Login.userName
Here is my Login entity class:
package injuryReports;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Login implements Serializable {
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private String userName;
private String password;
private int userId;
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 int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public Login() {
}
public Login(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}
public Login(int userId, String userName2, String password2) {
this.userId = userId;
this.userName = userName2;
this.password = password2;
}
}
My LoginDao Class:
package injuryReports;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
/**
*
* #author nGent
*
*/
#Component
public class LoginDao {
#PersistenceContext private EntityManager em;
#Transactional
public void persist(Login user) {
em.persist(user);
}
public List<Login> getAllUsers() {
TypedQuery<Login> query = em.createQuery(
"Select u FROM Login u ORDER BY u.id", Login.class);
return query.getResultList();
}
public Login validateLogin(String userName, String password) {
Login login = null;
TypedQuery<Login> query = em.createQuery(
"Select u From Login u where u.userName = :userName " +
" and u.password = :password", Login.class).setParameter(
"userName", userName).setParameter("password", password);
try {
login = query.getSingleResult();
}
catch (Exception e) {
//TODO: Handle Exception
}
return login;
}
}
And my LoginController class:
package injuryReports;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class LoginController {
#Autowired
private LoginDao loginDao;
#RequestMapping(value = "/user", method = {RequestMethod.POST})
public ModelAndView userEntry(HttpServletRequest request) {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
if (userName != "" && password != "") {
loginDao.persist(new Login(userName, password));
}
return new ModelAndView("logon.jsp", "loginDao", loginDao);
}
#RequestMapping(value = "/login")
public ModelAndView login(HttpServletRequest request) {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
String page = "login.jsp";
if (userName != "" && password != "") {
try {
Login login = loginDao.validateLogin(userName, password);
if (login != null) {
request.getSession().setAttribute("UserId", login.getUserId());
page = "login.jsp";
}
}
catch (Exception e) {
//TODO: Handle Exception
}
}
return new ModelAndView(page, getDaos());
}
#RequestMapping(value = "/logon", method = {RequestMethod.GET})
public ModelAndView logon(HttpServletRequest request) {
//int userId = (Integer) request.getSession().getAttribute("userId");
//request.getSession().setAttribute("UserID", userId);
return new ModelAndView("logon.jsp", getDaos());
}
public Map<String, Object> getDaos() {
Map<String, Object> models = new HashMap<String, Object>();
models.put("loginDao", loginDao);
return models;
}
}
Sorry this is a bit long- I wanted to provide as much information as possible. I'd really appreciate any help!
You cannot use #GeneratedValue on String property. It uses database sequences or AUTOINCREMENT features depending on the underlying database engine.
Either remove this annotation:
#Id
private String userName;
or use integer/long for id:
#Id #GeneratedValue
private int userId;
Related
I'm trying to make a blog using spring boot java with auth.
I created User class the implements UserDetails, and Post class.
When using the path /posts I wish to see all the posts in the blog, problem is that each post contains creator (User obj) and it shows the password of the user - and this is what I'm trying to avoid.
I tried #JsonIgnor, #JsonProperty didn't work
Tried also #JsonProperty(access = Access.WRITE_ONLY) I get an error on the Access.WRITE_ONLY.
Does are the classes:
package com.example.blog.entities;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
import java.util.Collection;
import java.util.List;
#Entity
#Table(name = "users")
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String username;
#JsonIgnore
private String password;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Role> roles;
public User() {}
public User(String username, String password, List<Role> roles) {
this.username = username;
this.password = password;
this.roles = roles;
}
#JsonIgnore
public String getPassword() {
return password;
}
#JsonProperty
public void setPassword(String password) {
this.password = password;
}
public Integer getId() {
return id;
}
}
import javax.persistence.*;
import java.time.LocalDate;
import java.util.Date;
#Entity
public class Post {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String title;
private String body;
private LocalDate date;
#ManyToOne
private User creator;
public Post() {
}
}
import com.example.blog.entities.Post;
import com.example.blog.entities.User;
import com.example.blog.repositories.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.List;
#Service
public class PostService {
private final PostRepository postRepository;
#Autowired
public PostService(PostRepository postRepository){
this.postRepository = postRepository;
}
public List<Post> getAllPosts(){
return postRepository.findAll();
}
public void insert(Post post) {
if(post.getBody() == null || post.getTitle() == null ){
throw new IllegalArgumentException("Missing args");
}
post.setDate(LocalDate.now());
postRepository.save(post);
}
public List<Post> getPostByUsername(User user){
return postRepository.findByCreatorId(user.getId());
}
}
The endpoint:
#GetMapping(value = "/posts")
public List<Post> posts(){
return postService.getAllPosts();
}
You should not expose your internal data model (JPA). Use transport classes. And you should remove the "#JsonProperty" from "public void setPassword(String password) ...". It is contradicting ("overriding") the "#JsonIgnore". And don't store your password as plaintext! Use for example jBCrypt.
My Setup:
public static class XUser {
private String username;
#JsonIgnore
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
//#JsonProperty
public void setPassword(String password) {
this.password = password;
}
}
#Test
public void testJson() {
XUser user = new XUser();
user.setPassword("oh shit!");
user.setUsername("name");
try {
ObjectMapper om = new ObjectMapper();
System.out.println(om.writeValueAsString(user));
} catch (Exception ex) {
ex.printStackTrace();
}
}
And the output:
{"username":"name"}
I am new to spring boot as after completing a crud function rest API in spring-boot I'm badly stuck in login rest API for android application where I just want to use email and password in POSTMAPPING. Please anyone could help me here?
Controller class
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import demo.loginapi.main.model.UserModel;
import demo.loginapi.main.repository.UserRepository;
import demo.loginapi.main.repository.UserService;
#RestController
#RequestMapping("/api/user")
public class UserController {
#Autowired
UserRepository userRepository;
#Autowired
UserService userService;
#GetMapping("/getallusers")
public List<UserModel> getAllCustomer(){
List<UserModel> alluserlist = userRepository.findAll();
return alluserlist;
}
#PostMapping("/login/{email}")
public List<UserModel> getemailpassword(#PathVariable(value = "email") String email){
List<UserModel> alluseremailpassword = userRepository.findUserByEmail(email);
return alluseremailpassword;
}
#PostMapping("/login2/{email}")
public UserModel getuserbyemail(#PathVariable(value = "email") String email)
{
UserModel userByEmailForLogin = userRepository.findByEmail(email);
return userByEmailForLogin;
}
#PostMapping("/loginemailpass/{email}/{password}")
public ResponseEntity<Map<String, String>> loginUser(#RequestBody Map<String, Object> userMap){
String email = (String) userMap.get("email");
String password = (String) userMap.get("password");
UserModel userModel = userService.validate(email,password);
return new ResponseEntity<>(generateJWTToken(userModel),HttpStatus.OK);
}
private Map<String, String> generateJWTToken(UserModel userModel) {
// TODO Auto-generated method stub
return null;
}
}
** Entity Class **
package demo.loginapi.main.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "user_login")
public class UserModel {
#Id
#Column(name = "userId", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
#Column(name = "username", nullable = false)
private String username;
#Column(name = "email", nullable = false)
private String email;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "role", nullable = false)
private String role;
public UserModel() {
//default constructor
}
public UserModel(Long userId, String username, String email, String password, String role) {
//super();
this.userId = userId;
this.username = username;
this.email = email;
this.password = password;
this.role = role;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
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 getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
#Override
public String toString() {
return "UserModel [userId=" + userId + ", username=" + username + ", email=" + email + ", password=" + password
+ ", role=" + role + "]";
}
}
** Repository Class **
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import demo.loginapi.main.model.UserModel;
#Repository
public interface UserRepository extends JpaRepository<UserModel, Long>{
List<UserModel> findUserByEmail(String email);
UserModel findByEmail(String email);
//UserModel validate(String email, String password);
UserModel findByEmailAndPaswword(String email, String password);
//UserModel findByEmailPassword(String email, String password);
}
** Service Class **
import demo.loginapi.main.model.UserModel;
public interface UserService {
UserModel validate(String email, String password);
}
** Service Implementation **
package demo.loginapi.main.repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import demo.loginapi.main.model.UserModel;
#Service
public class UserRepoImpl implements UserService{
#Autowired
UserRepository userRepository;
#Override
public UserModel validate(String email, String password) {
if(email != null) email = email.toLowerCase();
return userRepository.findByEmailAndPaswword(email, password);
}
}
In your repository class , is findByEmailAndPassword is available in jparepository, if not use through #query annotation like #query("select usename from userlogin us where us.username =:email") Something like that in your method.
Also if pre defined method is available please check the spelling, seems incorrect. It has double w in it. findByEmailAndPaswword
I'm Trying whenever user logged into the system, that particular username and current time will captured and stored into MySQL database. And my Database Table Names is userName, systemLoginTime, systemLogoffTime. I've tried so many times, but when the user logs into the system it is not effected in Database
This is my code java API:
import java.io.*;
import java.net.*;
public class Test
{
public static void main(String[] args) throws IOException {
String userName = "";
String systemLoginTime = "";
URL url = new URL("http://localhost:8080/insert/{userName}/{systemLoginTime}");
//Insert your JSON query request
String query = "{'userName':USERNAME,'systemLoginTime':'TODAY'}";
//It change the apostrophe char to double colon char, to form a correct JSON string
query=query.replace("'", "\"");
try{
System.getenv().get("USERNAME");
java.util.Date today = new java.util.Date();
return new java.sql.Timestamp(today.getTime());
//com.sun.security.auth.module.NTSystem().getName;
String username = System.getProperty("user.name");
System.out.println("username = " + username);
//make connections
URLConnection urlc = url.openConnection();
//It Content Type is so importan to support JSON call
urlc.setRequestProperty("Content-Type", "application/json");
printMessage("Your URL: " + url.toString());
//use post mode
urlc.setDoOutput(true);
urlc.setAllowUserInteraction(false);
//send query
PrintStream ps = new PrintStream(urlc.getOutputStream());
ps.print(query);
printMessage("Your Query: " + query);
ps.close();
//get result
BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String l = null;
while ((l=br.readLine())!=null) {
printMessage(l);
}
br.close();
} catch (Exception e){
printMessage("Error ocurred");
printMessage(e.toString());
}
}
private static void printMessage(String s){
System.out.println(s);
}
}
=====================================
This is my Spring Boot Repository class
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
#Repository
public class MyCopRepo
{
#Autowired
JdbcTemplate jdbt;
public String add(String userName, String systemLoginTime)
{
String userName1= userName;
String systemLoginTime1=systemLoginTime;
//String systemLogoffTime1= systemLogoffTime;
String query = "insert into mycopinsert(userName, systemLoginTime) values(?,?)";
int i = jdbt.update(query, userName1, systemLoginTime1);
if(i>0)
{
return "Inserted Successfully";
}
return "Not Inserted";
}
}
=============================================
This is my Controller class:
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class MyCopController
{
#Autowired
MyCopRepo ar;
#PostMapping("/insert/{userName}/{systemLoginTime}")
public String myCop(#PathVariable("userName") String userName, #PathVariable("systemLoginTime") String systemLoginTime)
{
return ar.add(userName, systemLoginTime);
}
}
You can try something like this, instead of passing as parameter just get the login time before make the query to the database.
public String add(String userName)
{
String userName1= userName;
String systemLoginTime=java.sql.Timestamp(new Date().getTime());
//String systemLogoffTime1= systemLogoffTime;
String query = "insert into mycopinsert(userName, systemLoginTime) values(?,?)";
int i = jdbt.update(query, userName1, systemLoginTime1);
if(i>0)
{
return "Inserted Successfully";
}
return "Not Inserted";
}
}
You should also encapsulate the code in the main, creating methods to group content (instead of comments before each part), it is more understandable and easy to debug.
Configure your project to use Hibernate & Springboot and your solution becomes:
#postmapping("/login")
public String login(#RequestBody LoginEventRequestBody request) {
LoginEvent event = new LoginEvent();
event.setUsername(request.getUserName);
event.setTimeStamp(new Timestamp(new Date().getTime()));
loginEventService.save(event);
return "successfully logged login event";
}
Essentially, you will want to separate your login logic from your logging logic. After the user successfully logs in log the login event.
you can still use path variables. I personally just find this cleaner
How to Set this up
LoginEventRequestBody
LoginEvent
LoginEventController
LoginEventService
LoginEventRepository
application.properties
LoginEventRequestBody.java
package org.app.loginEvent;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.immutables.value.Value;
#Value.Immutable
#JsonDeserialize(builder = LoginEventRequestBody.Builder.class)
#Value.Style(
visibility = Value.Style.ImplementationVisibility.PACKAGE,
builderVisibility = Value.Style.BuilderVisibility.PUBLIC
)
public interface LoginEventRequestBody {
String getUserName();
class Builder extends ImmutableLoginEventRequestBody.Builder {
}
static LoginEventRequestBody.Builder builder() {
return new LoginEventRequestBody.Builder();
}
}
LoginEvent.java
package org.app.loginEvent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.sql.Timestamp;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "login_event")
public class LoginEvent {
#Id
#GeneratedValue
#JsonProperty("id")
private Long id;
#JsonProperty("userName")
private String userName;
#JsonProperty("timestamp")
private Timestamp timestamp;
public LoginEvent() {
}
public LoginEvent(String userName, Timestamp timestamp) {
this.userName = userName;
this.timestamp = timestamp;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
}
LoginEventController
package org.app.loginEvent;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("events")
public class LoginEventController {
private final LoginEventService loginEventService;
public LoginEventController(LoginEventService loginEventService) {
this.loginEventService = loginEventService;
}
#postmapping("/login")
public String login(#RequestBody LoginRequestBody request) {
LoginEvent event = new LoginEvent();
event.setUsername(request.getUserName);
event.setTimeStamp(new Timestamp(new Date().getTime()));
loginEventService.save(event);
return "successfully logged login event";
}
}
LoginEventService
package org.app.loginEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional
public class LoginEventService {
#Autowired
private LoginEventRepository loginEventRepository;
public void save(LoginEventloginEvent) {
loginEventRepository.save(loginEvent);
}
}
LoginEventRepository
package org.app.loginEvent;
import org.springframework.data.jpa.repository.JpaRepository;
public interface LoginEventRepository extends JpaRepository<LoginEvent, Long> {
}
application.properties
#--------------------------------------------------
#mysql
#--------------------------------------------------
spring.datasource.username =root
spring.datasource.password =root
spring.datasource.url =jdbc:mysql://localhost:3306/mydb
spring.datasource.driverClassName =com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto =update
When your user logsIn,
Make a request to the event tracker
HTTP METHOD
POST
URL Endpoint
http://localhost:8080/events/login
Request body
{
userName:"userNameOfThePersonTryingToLogIn"
}
#now check your database and you will find the event has logged
#repeat this process for your logout event
I want retrieve user email from MySql database table using spring boot.i used findByEmailAndPassword in controller but it retrieve null value for email.
Here is my Code
controller
package com.example.demo.controller;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.demo.JPARepository;
import com.example.demo.pojo.regisbean;
#Controller
public class registerController {
regisbean pp;
#RequestMapping(value = "/")
public String mm() {
System.out.println("I am in m1 method");
return "index";
}
#RequestMapping(value = { "/register", "home" })
public String m1() {
System.out.println("I am in mm method");
return "register";
}
#Autowired
JPARepository jpaRepository;
#PostMapping("/register")
public String regis(#ModelAttribute regisbean rb)
{
System.out.println("I m in regis method");
regisbean b=jpaRepository.save(rb);
if(b!=null)
return "index";
else
return "fail";
}
#RequestMapping(value= {"/login1","login2"})
public String m2() {
System.out.println("i m in m2()");
return "login";
}
#PostMapping("/login")
public String login(#ModelAttribute regisbean rx,Model m) {
System.out.println("I am in Login");
regisbean re=jpaRepository.findByEmailAndPassword(rx.getEmail(), rx.getPassword());
if(re!=null)
{
m.addAttribute("email",rx.getEmail());
m.addAttribute("password",rx.getPassword());
System.out.println("yes");
return "loginsuccess";
}
else
{
System.out.println(rx.getEmail());
System.out.println("failed");
return "register";
}
}
}
pojo class
package com.example.demo.pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "pro")
public class regisbean {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column
private String name;
#Column
private String email;
#Column
private String phonenumber;
#Column
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Repository
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.pojo.regisbean;
public interface JPARepository extends CrudRepository<regisbean, Integer> {
public regisbean findByEmailAndPassword(String email,String password);
}
I was able to get your code to work by inserting a row in the table:
INSERT INTO pro (
id
,email
,name
,password
,phonenumber
)
VALUES (
0
,'user#domain.com'
,'Jim'
,'secret'
,'123-123-1234'
)
Then changing:
public String login(#ModelAttribute regisbean rx,Model m) {
to:
public String login(#RequestBody RegisBean rx,Model m) {
and POSTing the following request body to the /login resource:
{
"email": "user#domain.com",
"password": "secret"
}
I didn't have to make any changes to your Repo. I suspect your attempt was failing because RegisBean was never being initialized with any values and so the repo was asked to find a record with a null email and a null password.
In my project N- number of User is available. Every user can do insert update deleted list of data. every users have different different data. suppose one user have 10 record another user have 20 record and 3rd user have 15 record etc.
I have try to multiple user can register and login to my application with first user in side first user account i have inserted 10 record and display then logout. again i will login with different user then that same data will be display which is inserted by previous user. So my problem is how to maintain every user data with your own account i am beginner in spring-boot with hibernate, jsp.
1.Usercontroller.java
package com.rajesh.controller;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
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.ResponseBody;
import com.rajesh.model.User;
import com.rajesh.service.UserService;
#Controller
public class UserController {
private final Logger logger = LoggerFactory.getLogger(UserController.class);
#Autowired
private UserService userService;
#GetMapping("/")
public String Home(Model model) {
return "home";
}
#PostMapping("/user/register")
public String registerNewUser(ModelMap model, #ModelAttribute("userRegister")#Valid User user, BindingResult bindingResult) {
User userExists = userService.findUserByEmail(user.getEmail());
if (userExists != null) {
bindingResult
.rejectValue("email", "error.user",
"There is already a user registered with the email provided");
model.addAttribute("msgEmail", "your email is already registered");
logger.info("your email Id is already registered");
System.out.println("your email is already registered");
return "home";
} else {
userService.saveUser(user);
model.addAttribute("successMessage", "User has been registered successfully");
logger.info("User has been registered successfully");
System.out.println("User has been registered successfully");
return "home";
}
}
#PostMapping("/user/login")
public String doLogin(ModelMap model, #ModelAttribute("command")User user, HttpSession session) {
if(userService.loginUser(user.getEmail(), user.getPassword()) != null) {
session.setAttribute("email",user.getEmail());
session.setAttribute("user_id", user.getId());
model.addAttribute("sucessLogin", "You are login sucessfully");
logger.info("You are login sucessfully",user.getEmail());
System.out.println("You are login sucessfully "+ user.getEmail());
return "redirect:userdashboard";
}else {
System.out.println("Invalid Email/Password");
logger.error("Invalid Email/Password");
model.put("failed", "Invalid Email/Password");
return "home";
}
}
#PostMapping("/user/checkstatus")
#ResponseBody
public Integer checkUserStatus(String email, ModelMap model, #ModelAttribute("command")User user, HttpSession session) {
int userStatus = userService.isActiveUserStatus(email);
System.out.println(userStatus);
if(userStatus != 0) {
System.out.println(userStatus);
return userStatus;
}else {
System.out.println(userStatus);
return userStatus;
}
}
#GetMapping("/logout")
public String doLogout(ModelMap model, #ModelAttribute("command")User user, HttpSession session) {
session.removeAttribute("email");
logger.info("you are logout successfully");
return "home";
}
}
User.java
package com.rajesh.model;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import org.hibernate.validator.constraints.Length;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* #author Rajesh Bhushan
*/
#Data
#Builder
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "users")
public class User extends BaseEntity{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id")
private int id;
#Column(name="shopname")
#Length(min = 3, message = "*Your shopname must have at least 3 characters")
#NotEmpty(message = "*Please provide an shopname")
private String shopname;
#Column(name="name")
#Length(min = 3, message = "*Your name must have at least 3 characters")
#NotEmpty(message = "*Please provide an name")
private String name;
#Column(name="address")
#Length(min = 3, message = "*Your address must have at least 3 characters")
#NotEmpty(message = "*Please provide an address")
private String address;
#Column(name="mobile")
#NotEmpty(message = "*Please provide an address")
private String mobile;
#Column(name = "email")
#Email(message = "*Please provide a valid Email")
#NotEmpty(message = "*Please provide an email")
private String email;
#Column(name = "password")
#NotEmpty(message = "*Please provide your password")
private String password;
#Column(name="active")
private int active;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "user_role", joinColumns = #JoinColumn(name = "user_id"), inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Role> roles;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getShopname() {
return shopname;
}
public void setShopname(String shopname) {
this.shopname = shopname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
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 int getActive() {
return active;
}
public void setActive(int active) {
this.active = active;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
UserRepository.java
package com.rajesh.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.rajesh.model.User;
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
public User findByEmail(String email);
#Query("from User as u where u.email=:email and u.password=:password")
public User loginUser(String email,String password);
#Query("select active from User as u where u.email=:email")
public Integer isActiveUserStatus(String email);
}
4.UserService.java
package com.rajesh.service;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rajesh.model.Role;
import com.rajesh.model.User;
import com.rajesh.repository.RoleRepository;
import com.rajesh.repository.UserRepository;
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
public User findUserByEmail(String email) {
return userRepository.findByEmail(email);
}
public void saveUser(User user) {
user.setShopname(user.getShopname());
user.setName(user.getName());
user.setEmail(user.getEmail());
user.setPassword(user.getPassword());
user.setMobile(user.getMobile());
user.setAddress(user.getAddress());
user.setActive(0);
user.setCreatedBy(user.getName());
user.setCreatedDate(new Date());
user.setUpdatedBy(user.getName());
user.setUpdatedDate(new Date());
Role userRole = roleRepository.findByRole("USER");
user.setRoles(new HashSet<Role>(Arrays.asList(userRole)));
userRepository.save(user);
}
public User loginUser(String email,String password) {
return userRepository.loginUser(email, password);
}
public Integer isActiveUserStatus(String email) {
Integer activeStatus = userRepository.isActiveUserStatus(email);
return activeStatus;
}
}
Create a userid column on data table. So when listing data get datas according to userid.