javascript 如何使用用户ID以外的变量从数据库中检索用户

wj8zmpe1  于 2023-02-02  发布在  Java
关注(0)|答案(1)|浏览(106)

我有一个Sping Boot 应用程序,其中我有一个模型用户,当我点击前端React应用程序上的提交按钮时,我试图检索具有相同用户名的用户。它说它无法检索,我不知道到底是什么错误。我得到这个错误。
xhr.js:247获取http://localhost:8080/calore_counter/用户/$%7电子邮件%7D网络::错误失败500
我没有麻烦张贴的东西到数据库使用我的前端应用程序。我可以检索用户使用 Postman 与ID。但当我试图使用电子邮件它只是不工作。

后端

用户模型

这是创建用户的位置,也是数据库中的表所基于的位置

@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>

)
}

我希望能够键入一封电子邮件,点击提交按钮,并从数据库中检索用户(多个用户稍后)信息。我搞砸了一些事情,但我无法找出代码有什么问题。我认为这可能是UserRepository中的代码有问题,或ViewUser中的提交按钮。
您可以看到我的存储库中的所有代码
https://github.com/EmmanuelOlofintuyi/FullStackCalorieCounter

cs7cruho

cs7cruho1#

试试这个。
似乎对我有用...

用户模型

这很好,但是最佳实践是使用Lombok的@Data作为getter和setter(这个类级注解将自动为您生成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是好的,不要改变它,它必须工作得很好!

相关问题