学习13

老年人评估系统
后端使用了spring boot
mapper层

package com.example.elserevaluate.mapper;

import com.example.elserevaluate.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Insert;

@Mapper
public interface userMapper {
    @Select("SELECT * FROM user WHERE username = #{username}")
    User findByUsername(String username);

    @Insert("INSERT INTO user(username, password) VALUES(#{username}, #{password})")
    int insert(User user);

    @Select("SELECT * FROM user WHERE username = #{username} AND password = #{password}")
    User findByUsernameAndPassword(String username, String password);
}

package com.example.elserevaluate.mapper;

import com.example.elserevaluate.entity.Customer;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface CustomerMapper {
    @Insert("INSERT INTO customer (name, gender, birth_date, id_card, social_security_card, " +
            "ethnicity, education, religion, marital_status, living_condition, create_time, update_time) " +
            "VALUES (#{name}, #{gender}, #{birthDate}, #{idCard}, #{socialSecurityCard}, " +
            "#{ethnicity}, #{education}, #{religion}, #{maritalStatus}, #{livingCondition}, " +
            "NOW(), NOW())")
    int insert(Customer customer);

    @Select("SELECT * FROM customer WHERE id_card = #{idCard}")
    Customer findByIdCard(String idCard);
}
package com.example.elserevaluate.mapper;


import com.example.elserevaluate.entity.Questionnaire;
import com.example.elserevaluate.entity.Questionnaire;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface QuestionnaireMapper {
    @Insert("INSERT INTO questionnaire (eating, bathing, grooming, dressing, bowel_control, " +
            "urine_control, toileting, bed_transfer, walking, stairs, " +
            "cognitive_memory, cognitive_clock, aggression_physical, aggression_verbal, " +
            "depression_mood, depression_suicide, consciousness, vision, hearing, " +
            "communication, life_skills, work_skills, time_space_orientation, " +
            "create_time, update_time) " +
            "VALUES (#{eating}, #{bathing}, #{grooming}, #{dressing}, #{bowelControl}, " +
            "#{urineControl}, #{toileting}, #{bedTransfer}, #{walking}, #{stairs}, " +
            "#{cognitiveMemory}, #{cognitiveClock}, #{aggressionPhysical}, #{aggressionVerbal}, " +
            "#{depressionMood}, #{depressionSuicide}, #{consciousness}, #{vision}, #{hearing}, " +
            "#{communication}, #{lifeSkills}, #{workSkills}, #{timeSpaceOrientation}, " +
            "NOW(), NOW())")
    int insert(Questionnaire questionnaire);

    @Select("SELECT * FROM questionnaire WHERE id = #{id}")
    Questionnaire findById(Long id);
}

实体类

package com.example.elserevaluate.entity;

import lombok.Data;

@Data
public class User {
    private Long id;
    private String username;
    private String password;
}
package com.example.elserevaluate.entity;

import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.util.Date;

@Data
public class Questionnaire {
    private Long id;

    @NotBlank(message = "进食能力不能为空")
    private String eating;

    @NotBlank(message = "洗澡能力不能为空")
    private String bathing;

    @NotBlank(message = "修饰能力不能为空")
    private String grooming;

    @NotBlank(message = "穿衣能力不能为空")
    private String dressing;

    @NotBlank(message = "大便控制不能为空")
    private String bowelControl;

    @NotBlank(message = "小便控制不能为空")
    private String urineControl;

    @NotBlank(message = "如厕能力不能为空")
    private String toileting;

    @NotBlank(message = "床椅转移能力不能为空")
    private String bedTransfer;

    @NotBlank(message = "平地行走能力不能为空")
    private String walking;

    @NotBlank(message = "上下楼梯能力不能为空")
    private String stairs;

    private Boolean cognitiveMemory;
    private Boolean cognitiveClock;
    private Boolean aggressionPhysical;
    private Boolean aggressionVerbal;
    private Boolean depressionMood;
    private Boolean depressionSuicide;

    @NotBlank(message = "意识水平不能为空")
    private String consciousness;

    @NotBlank(message = "视力状况不能为空")
    private String vision;

    @NotBlank(message = "听力状况不能为空")
    private String hearing;

    @NotBlank(message = "沟通交流能力不能为空")
    private String communication;

    @NotBlank(message = "生活能力不能为空")
    private String lifeSkills;

    @NotBlank(message = "工作能力不能为空")
    private String workSkills;

    @NotBlank(message = "时间空间定向能力不能为空")
    private String timeSpaceOrientation;

    private Date createTime;
    private Date updateTime;
}

package com.example.elserevaluate.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;

@Data
public class Customer {
    private Long id;
    private String name;
    private String gender;

    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss", timezone = "GMT+8")
    private Date birthDate;

    private String idCard;
    private String socialSecurityCard;
    private String ethnicity;
    private String education;
    private String religion;
    private String maritalStatus;
    private String livingCondition;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date createTime;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date updateTime;
}

service层

package com.example.elserevaluate.mapper;


import com.example.elserevaluate.entity.Questionnaire;
import com.example.elserevaluate.entity.Questionnaire;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface QuestionnaireMapper {
    @Insert("INSERT INTO questionnaire (eating, bathing, grooming, dressing, bowel_control, " +
            "urine_control, toileting, bed_transfer, walking, stairs, " +
            "cognitive_memory, cognitive_clock, aggression_physical, aggression_verbal, " +
            "depression_mood, depression_suicide, consciousness, vision, hearing, " +
            "communication, life_skills, work_skills, time_space_orientation, " +
            "create_time, update_time) " +
            "VALUES (#{eating}, #{bathing}, #{grooming}, #{dressing}, #{bowelControl}, " +
            "#{urineControl}, #{toileting}, #{bedTransfer}, #{walking}, #{stairs}, " +
            "#{cognitiveMemory}, #{cognitiveClock}, #{aggressionPhysical}, #{aggressionVerbal}, " +
            "#{depressionMood}, #{depressionSuicide}, #{consciousness}, #{vision}, #{hearing}, " +
            "#{communication}, #{lifeSkills}, #{workSkills}, #{timeSpaceOrientation}, " +
            "NOW(), NOW())")
    int insert(Questionnaire questionnaire);

    @Select("SELECT * FROM questionnaire WHERE id = #{id}")
    Questionnaire findById(Long id);
}

package com.example.elserevaluate.service;

import com.example.elserevaluate.entity.Customer;
import com.example.elserevaluate.mapper.CustomerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
public class CustomerService {

    @Autowired
    private CustomerMapper customerMapper;

    public Customer getCustomerByIdCard(String idCard) {
        if (!StringUtils.hasText(idCard)) {
            return null;
        }
        return customerMapper.findByIdCard(idCard);
    }

    @Transactional
    public boolean saveCustomer(Customer customer) {
        if (customer == null || !StringUtils.hasText(customer.getIdCard())) {
            return false;
        }

        // 检查是否已存在相同身份证号的记录
        Customer existingCustomer = customerMapper.findByIdCard(customer.getIdCard());
        if (existingCustomer != null) {
            return false;
        }

        return customerMapper.insert(customer) > 0;
    }
}
package com.example.elserevaluate.service;


import com.example.elserevaluate.entity.Questionnaire;
import com.example.elserevaluate.mapper.QuestionnaireMapper;
import com.example.elserevaluate.mapper.QuestionnaireMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class QuestionnaireService {

    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Transactional
    public boolean saveQuestionnaire(Questionnaire questionnaire) {
        if (questionnaire == null) {
            return false;
        }
        return questionnaireMapper.insert(questionnaire) > 0;
    }

    public Questionnaire getQuestionnaireById(Long id) {
        return questionnaireMapper.findById(id);
    }
}

controller层

package com.example.elserevaluate.controller;

import com.example.elserevaluate.entity.Customer;
import com.example.elserevaluate.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "http://127.0.0.1:5500", allowCredentials = "true")
public class AddController {

    @Autowired
    private CustomerService customerService;

    // 保存用户信息
    @PostMapping("/info")
    public ResponseEntity<Map<String, Object>> saveUserInfo(@RequestBody Customer customer) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean result = customerService.saveCustomer(customer);
            if (result) {
                response.put("code", "1");
                response.put("msg", "保存成功");
            } else {
                response.put("code", "0");
                response.put("msg", "该身份证号已存在");
            }
        } catch (Exception e) {
            response.put("code", "0");
            response.put("msg", "保存失败:" + e.getMessage());
        }

        return ResponseEntity.ok(response);
    }

    // 通过身份证号查询用户信息
    @GetMapping("/info/{idCard}")
    public ResponseEntity<Map<String, Object>> getUserInfo(@PathVariable String idCard) {
        Map<String, Object> response = new HashMap<>();

        try {
            Customer customer = customerService.getCustomerByIdCard(idCard);
            if (customer != null) {
                response.put("code", "1");
                response.put("msg", "查询成功");
                response.put("data", customer);
            } else {
                response.put("code", "0");
                response.put("msg", "未找到该身份证号的客户");
            }
        } catch (Exception e) {
            response.put("code", "0");
            response.put("msg", "查询失败:" + e.getMessage());
        }

        return ResponseEntity.ok(response);
    }
}

package com.example.elserevaluate.controller;

import com.example.elserevaluate.entity.User;
import com.example.elserevaluate.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://127.0.0.1:5500", allowCredentials = "true")
public class LoginController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody LoginRequest request) {
        Map<String, Object> response = new HashMap<>();

        try {
            User user = userService.login(
                    request.getUsername(),
                    request.getPassword(),
                    request.getImageCaptchaCode()
            );

            if (user != null) {
                // 移除密码等敏感信息
                user.setPassword(null);

                response.put("code", "1");
                response.put("msg", "登录成功");
                response.put("data", user);
                return ResponseEntity.ok(response);
            } else {
                response.put("code", "0");
                response.put("msg", "用户名或密码错误");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (RuntimeException e) {
            response.put("code", "0");
            response.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}

class LoginRequest {
    private String username;
    private String password;
    private String imageCaptchaCode;

    // Getters and Setters
    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 String getImageCaptchaCode() {
        return imageCaptchaCode;
    }

    public void setImageCaptchaCode(String imageCaptchaCode) {
        this.imageCaptchaCode = imageCaptchaCode;
    }
}

package com.example.elserevaluate.controller;

import com.example.elserevaluate.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://127.0.0.1:5500", allowCredentials = "true")
public class RegisterController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody RegisterRequest request) {
        Map<String, Object> response = new HashMap<>();

        try {
            boolean success = userService.register(
                    request.getUsername(),
                    request.getPassword(),
                    request.getImageCaptchaCode()
            );

            if (success) {
                response.put("code", "1");
                response.put("msg", "注册成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("code", "0");
                response.put("msg", "注册失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (RuntimeException e) {
            response.put("code", "0");
            response.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}

// 添加请求体对象
class RegisterRequest {
    private String username;
    private String password;
    private String imageCaptchaCode;

    // Getters and Setters
    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 String getImageCaptchaCode() {
        return imageCaptchaCode;
    }

    public void setImageCaptchaCode(String imageCaptchaCode) {
        this.imageCaptchaCode = imageCaptchaCode;
    }
}
package com.example.elserevaluate.controller;


import com.example.elserevaluate.entity.Questionnaire;
import com.example.elserevaluate.service.QuestionnaireService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/questionnaire")
@CrossOrigin(origins = "http://127.0.0.1:5500", allowCredentials = "true")
public class QuestionnaireController {

    @Autowired
    private QuestionnaireService questionnaireService;

    @PostMapping("/submit")
    public ResponseEntity<Map<String, Object>> submitQuestionnaire(
            @Valid @RequestBody Questionnaire questionnaire,
            BindingResult bindingResult) {

        Map<String, Object> response = new HashMap<>();

        // 验证数据
        if (bindingResult.hasErrors()) {
            response.put("code", "0");
            response.put("msg", "数据验证失败:" +
                    bindingResult.getAllErrors().get(0).getDefaultMessage());
            return ResponseEntity.ok(response);
        }

        try {
            boolean result = questionnaireService.saveQuestionnaire(questionnaire);
            if (result) {
                response.put("code", "1");
                response.put("msg", "问卷提交成功");
            } else {
                response.put("code", "0");
                response.put("msg", "问卷提交失败");
            }
        } catch (Exception e) {
            response.put("code", "0");
            response.put("msg", "提交失败:" + e.getMessage());
        }

        return ResponseEntity.ok(response);
    }
}

后端代码只是实现了较为简单的功能,后面还要进行修改和完善。

posted @ 2025-02-11 22:04  haoyinuo  阅读(20)  评论(0)    收藏  举报