簡體   English   中英

如何使用用戶 ID 以外的變量從數據庫中檢索用戶

[英]How to retrieve a Users from a database using a variable other than User Id

我有一個 Spring Boot 應用程序,其中有一個 model 用戶,當我點擊前端 React 應用程序上的提交按鈕時,我試圖檢索具有相同用戶名的用戶。 它說它無法檢索,我不知道到底出了什么問題。 我收到此錯誤。

xhr.js:247 GET http://localhost:8080/calorie_counter/user/$%7Bemail%7D.net::ERR_FAILED 500

使用我的前端應用程序將內容發布到數據庫中沒有問題。 我可以使用帶有 Id 的 Postman 檢索用戶。 但是當我嘗試使用 Email 時,它就不起作用了。

后端

用戶模型

這是創建用戶的地方以及數據庫中的表所基於的



@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private LocalDate dob;
@Transient
private Integer age;
@Transient
private Integer suggestedCalories;
private Integer lifestyle;
private String goal;
private Double weight;

public User() {
}

public User(String name, String email, LocalDate dob, String goal, Integer lifestyle, Double weight) {
this.name = name;
this.email = email;
this.dob = dob;
this.lifestyle = lifestyle;
this.goal = goal;
this.weight = weight;
}

public User(String name, String email, LocalDate dob) {
this.name = name;
this.email = email;
this.dob = dob;
}

public Long getId() {
return id;
}

public void setId(Long 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 LocalDate getDob() {
return dob;
}

public void setDob(LocalDate dob) {
this.dob = dob;
}

public Integer getAge() {
return Period.between(this.dob, LocalDate.now()).getYears();
}

public void setAge(Integer age) {
this.age = age;
}

public Integer getSuggestedCalories() {
return calculateCalories();
}

public void setSuggestedCalories(Integer suggestedCalories) {
this.suggestedCalories = suggestedCalories;
}

public Integer getLifestyle() {
return lifestyle;
}

public void setLifestyle(Integer lifestyle) {
this.lifestyle = lifestyle;
}

public Double getWeight() {
return weight;
}

public void setWeight(Double weight) {
this.weight = weight;
}
public String getGoal() {
return goal;
}

public void setGoal(String goal) {
this.goal = goal;
}

public Integer calculateCalories(){
Double calories = 0.0;

    String goal = getGoal();
    Integer lifeStyleValue = getLifestyle();
    if(goal.equals("LOSE")) {
        calories = (weight\*10);
        if (lifeStyleValue \<= 1) {
            calories -= 500;
        } else if (lifeStyleValue == 2) {
            calories  -= 250;
        } else if (lifeStyleValue == 4) {
            calories += 250;
        } else if (lifeStyleValue \>= 5) {
            calories += 500;
        } else {
            calories +=0;
        }
    } else if (goal.equals("GAIN") ){
        calories = ((weight\*15)+500);
        if (lifeStyleValue \<= 1) {
            calories -= 500;
        } else if (lifeStyleValue == 2) {
            calories -= 250;
        } else if (lifeStyleValue == 4) {
            calories += 250;
        } else if (lifeStyleValue \>= 5) {
            calories += 500;
        } else {
            calories+=0;
        }
    }
    else {
        calories = (weight\*15);
        if (lifeStyleValue \<= 1) {
            calories -= 500;
        } else if (lifeStyleValue == 2) {
            calories -= 250;
        } else if (lifeStyleValue == 4) {
            calories += 250;
        } else if (lifeStyleValue \>= 5) {
            calories += 500;
        } else {
            calories +=0;
        }
    
    }
    Integer cv = calories.intValue();
    return cv;

}

}

用戶資料庫



@Repository
public interface UserRepository extends JpaRepository\<User, Long\> {
@Query("SELECT u FROM User u WHERE u.email = ?1")
User findUserByEmail(String email);

}

用戶服務



@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserRepository userRepository;

    @Override
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
    
    @Override
    public User saveUser(User user) {
        return userRepository.save(user);
    }
    
    @Override
    public User getUserById(Long id) {
        return userRepository.findById(id)
                .orElseThrow(()->new UserNotFoundException(id));
    }
    
    @Override
    public User getUserByEmail(String email) {
        User user = userRepository.findUserByEmail(email);
        if (email != null &&
                email.length() > 0 &&
                !Objects.equals(user.getEmail(), email)) {
            User userOptional = userRepository
                    .findUserByEmail(email);
            if (userOptional == null) {
                throw new IllegalStateException("email does not exist");
            }
            return user;
        }
        return null;
    }
    
    @Override
    public User updateUser(User newUser, Long id) {
        return userRepository.findById(id)
                .map(user -> {
                    user.setName(newUser.getName());
                    user.setEmail(newUser.getEmail());
                    user.setDob(newUser.getDob());
                    user.setWeight(newUser.getWeight());
                    user.setLifestyle(newUser.getLifestyle());
                    user.setGoal(newUser.getGoal());
                    return userRepository.save(user);
                }).orElseThrow(()->new UserNotFoundException(id));
    }
    
    @Override
    public String deleteUser(Long id) {
        if(!userRepository.existsById(id)){
            throw new UserNotFoundException(id);
        }
        userRepository.deleteById(id);
        return "User with id"+id+"has been deleted, success";
    }

}

用戶控制器


@RestController
@CrossOrigin("http://localhost:3000")

@RequestMapping("/calorie_counter")
public class UserController {
@Autowired
private UserService userService;

    @PostMapping("/addUser")
    public String add(@RequestBody User user){
        userService.saveUser(user);
        return "New user added to the database";
    }
    
    @GetMapping("/users")
    public List<User> getAllUsers(){
        return userService.getAllUsers();
    }
    
    @GetMapping("/user/{id}")
    public User getUserById(@PathVariable Long id){
        return userService.getUserById(id);
    }
    
    @GetMapping("/user/{email}")
    public User getUserByEmail(@PathVariable String email){return userService.getUserByEmail(email);}
    
    @PutMapping("/user/{id}")
    public User updatUser(@RequestBody User newUser, @PathVariable Long id){
        return userService.updateUser(newUser, id);
    }
    
    @DeleteMapping("/user/{id}")
    public String deleteUser(@PathVariable Long id){
        return userService.deleteUser(id);
    }

}

前端

查看用戶

import axios from 'axios';
import React, { useState, useEffect } from 'react'

import {useParams, useNavigate} from 'react-router-dom'

export default function ViewUser() {

    const [user, setUser] = useState({
        name:"",
        email: "",
        dob: "",
        age: "",
        suggestedCalories: "",
        goal:"",
        lifestyle:"",
        weight:""
    });
    
    const onInputChange = (e) => {
        setUser({ ...user, [e.target.name]: e.target.value });
      };
    
    const {email}=useParams();
    
    useEffect(()=>{
        fetch("http://localhost:8080/calorie_counter/user/${email}")
        .then(res=>res.json)
        .then((result)=>{
            setUser(result)
        })
    }, [])
    
    const onSubmit= async (e)=>{
        e.preventDefault()
        const result = await axios.get("http://localhost:8080/calorie_counter/user/${email}",user)
        setUser(result.data)
      }
    return (
    <div className='col-md-6 offset-md-3 border rounded p-4 mt-2 shadow'>
        <form onSubmit={(e) => onSubmit(e)}>
        <div className='mb-3'>
            <label htmlFor='Email' className='form-label'>
            E-mail
            </label>
            <input
            type={'text'}
            className='form-control'
            placeholder='Enter E-mail'
            onChange={(e)=>onInputChange(e)}
            value={email}
            name='email'
            />
            <button type="submit" className='btn btn-outline-success'>Submit</button>
            <button type="submit" className='btn btn-outline-danger mx-2'>Cancel</button>
        </div>
        </form>
    <div className='card'>
        <div className='card-header'>
            Details of user id : 
            <ul className='list-group list-group-flush'>
                <li className='list-group-item'>
                    <b>Name: </b>
                    {user.name}
                </li>
                <li className='list-group-item'>
                    <b>Email: </b>
                    {user.email}
                </li>
                <li className='list-group-item'>
                    <b>Date of Brith: </b>
                    {user.dob}
                </li>
                <li className='list-group-item'>
                    <b>Age: </b>
                    {user.age}
    
                </li>
                <li className='list-group-item'>
                    <b>Suggested Calories: </b>
                    {user.suggestedCalories}
    
                </li>
                <li className='list-group-item'>
                    <b>Goal: </b>
                    {user.goal}
    
                </li>
                <li className='list-group-item'>
                    <b>LifeStyle: </b>
                    {user.lifestyle}
    
                </li>
            </ul>
        </div>
    
    </div>

)
}

我希望能夠輸入 email,單擊提交按鈕並從數據庫中檢索用戶(稍后為多個用戶)信息。 我搞砸了一些事情,但我無法弄清楚代碼有什么問題。 我認為 UserRepository 中的代碼或 ViewUser 中的提交按鈕可能有問題。

您可以在我的存儲庫中看到所有代碼

https://github.com/EmmanuelOlofintuyi/FullStackCalorieCounter

試試這個。
似乎在為我工作...

用戶模型

沒關系,最好的做法是將來自 Lombok 的@Data用於 getter 和 setter(此 class 級別注釋將為您自動生成 getter 和 setter)。
同樣,這只是一個建議:)

用戶資料庫

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    Optional<User> findUserByEmail(String email);

}

內聯查詢容易受到 SQL_Injection 攻擊,因此不建議這樣做!
雖然 Jpa 和 Hibernate 對於有才華的攻擊者來說也不例外,但最好還是使用它們,因為它們通過使用正則表達式等提供了良好的安全層。

用戶服務

...


@Override
public User getUserByEmail(String email) {

    if(email == null || email.length() == 0) return null;

    Optional<User> dbUser = this.userRepository.findUserByEmail(email);
    if (!dbUser.isPresent()) throw new IllegalStateException("email does not exist");
    return dbUser.get();
}


...

用戶控制器

實際上UserController很好,不要更改它,它一定可以正常工作!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM