2021SC@SDUSC-SDUDOC-blog16

2021SC@SDUSC-SDUDOC-blog16,第1张

2021SC@SDUSC-SDUDOC-blog16


本项目结构中,多个controller类进行后端事务的控制。
服务器和编辑器的通讯目前已经改成类protobuf接口,云端打开
有加入云端协作编辑的功能,暂时不表。

@RestController
@RequestMapping("/article")
public class DmsArticleController {

    @Resource
    private DmsArticleService dmsArticleService;

    @RequestMapping("/findAll")
    @ResponseBody
    List findAll() {
        return dmsArticleService.findAll();
    }

}

使用@RestController:
是Spring4之后新加入的注解,原来返回json需要@ResponseBody和@Controller配合。

即@RestController是@ResponseBody和@Controller的组合注解。


@RestController
public class HelloController {

    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(){
        return "hello";
    }
}

与下面的代码作用一样

@Controller
@ResponseBody
public class HelloController {

    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(){
        return "hello";
    }
}

@RequestMapping 配置url映射

@RequestMapping此注解即可以作用在控制器的某个方法上,也可以作用在此控制器类上。

当控制器在类级别上添加@RequestMapping注解时,这个注解会应用到控制器的所有处理器方法上。处理器方法上的@RequestMapping注解会对类级别上的@RequestMapping的声明进行补充。

本项目中article和character的控制类都比较简单,基本采用原生的注解结构即可。

简单提一下DmsArticle

它包含文章基本信息,也就是:

唯一标识 String
文章作者 String
书名 String
内容 String
图片链接 String
页码 List>
xml文档 String
文章注解 String
朝代 String
详细注解 JSonArray

DmsArticleService实现DmsArticleRepository的接口:

@Resource
private DmsArticleRepository dmsArticleRepository;

@Override
public DmsArticle save(DmsArticle dmsArticle) {
    return dmsArticleRepository.save(dmsArticle);
}

而DmsArticleRepository继承MongoRepository:

@Repository(value = "ds1DmsArticleRepository")
public interface DmsArticleRepository extends MongoRepository {
}

查看源码:

@NoRepositoryBean
public interface MongoRepository extends PagingAndSortingRepository, QueryByExampleExecutor 
@NoRepositoryBean
public interface CrudRepository extends Repository {
    ...
    
    // ...
    Optional findById(ID id);
}

发现一直在层层继承。

@NoRepositoryBean
public interface CrudRepository extends Repository {
    ...
    
    // ...
    Optional findById(ID id);
}

追溯到最高层,果然有ID作为文章唯一标识。

登陆控制需要的点稍微多一些。下一篇拆开来分析。

@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    UmsUserRepository service;
    @Autowired
    TokenService tokenService;

    @PostMapping("/login")
    public JSONObject login(String username, String password) {
        JSONObject jsonObject = new JSONObject();
        UmsUser user = new UmsUser();
        user.setUsername(username);
        user.setPassword(password);

        Optional userForbase = service.findOne(Example.of(user));

        if (userForbase.isPresent()) {
            if (!userForbase.get().getPassword().equals(user.getPassword())) {
                jsonObject.put("message", "登录失败,密码错误");
            } else {
                String token = tokenService.getToken(userForbase.get());
                jsonObject.put("token", token);
                jsonObject.put("user", userForbase);
            }
        }else{
            jsonObject.put("message", "登录失败,用户不存在或密码错误");
        }

        return jsonObject;
    }

    @PostMapping("/register")
    public Object register(String username, String password, String nickname) {
        JSONObject jsonObject = new JSONObject();
        UmsUser fuser = new UmsUser();
        fuser.setUsername(username);
        Optional one = service.findOne(Example.of(fuser));

        if (one.isPresent()) {
            jsonObject.put("message", "用户已存在");
        } else {
            fuser.setPassword(password);
            fuser.setNickname(nickname);
            fuser.setStatus(1);
            fuser.setCount(1);

            service.save(fuser);
            jsonObject = login(username, password);
        }

        return jsonObject;
    }

    @UserLoginToken
    @GetMapping("/get_message")
    public String getMessage() {
        return "通过验证";
    }

    @PostMapping("/set_password")
    public String setPassword(String username, String password, String /confirm/iPassword) {
        if (password == null || password.equals("") || confirmPassword == null || /confirm/iPassword.equals("")) {
            return "密码不能为空";
        }
        if (!password.equals(/confirm/iPassword)) {
            return "两次输入密码不同";
        }
        UmsUser user = new UmsUser();
        user.setUsername(username);
        Optional one = service.findOne(Example.of(user));
        if (one.isPresent()) {
            if (one.get().getPassword().equals(password)) {
                return "密码重复";
            } else {
                user = one.get();
                user.setPassword(password);
                service.save(user);
                return password;
            }
        } else {
            return "用户不存在";
        }
    }

    @PostMapping("/set_nickname")
    public String setNickname(String username, String nickname) {
        if (nickname == null || nickname.equals("")) {
            return "昵称不能为空";
        }
        UmsUser user = new UmsUser();
        user.setUsername(username);
        Optional one = service.findOne(Example.of(user));
        if (one.isPresent()) {
            user = one.get();
            user.setNickname(nickname);
            service.save(user);
            return nickname;
        } else {
            return "用户不存在";
        }
    }

    @PostMapping("/set_email")
    public String setEmail(String username, String email) {
        if (email == null || email.equals("")) {
            return "邮箱不能为空";
        }
        if (email.indexOf('@') == -1) {
            return "邮箱地址格式错误";
        }
        UmsUser user = new UmsUser();
        user.setUsername(username);
        Optional one = service.findOne(Example.of(user));
        if (one.isPresent()) {
            user = one.get();
            user.setEmail(email);
            service.save(user);
            return email;
        } else {
            return "用户不存在";
        }
    }

    @PostMapping("/set_phone")
    public String setPhone(String username, String phone) {
        if (phone == null || phone.equals("")) {
            return "手机号码不能为空";
        }
        if (phone.trim().length() != 11) {
            return "号码格式不正确";
        }
        if (phone.charAt(0) != '1' || (phone.charAt(0) == '1' && "358".indexOf(phone.charAt(1)) == -1)) {
            return "号码格式不正确";
        }
        UmsUser user = new UmsUser();
        user.setUsername(username);
        Optional one = service.findOne(Example.of(user));
        if (one.isPresent()) {
            user = one.get();
            user.setPhone(new BigInteger(phone));
            service.save(user);
            return phone;
        } else {
            return "用户不存在";
        }
    }

    @PostMapping("/set_sex")
    public Integer setSex(String username, Integer sex) {
        if (sex == null) {
            return -1;  // 参数为空
        }
        if (sex != 0 && sex != 1) {
            return -2;  // 参数不合法
        }
        UmsUser user = new UmsUser();
        user.setUsername(username);
        Optional one = service.findOne(Example.of(user));
        if (one.isPresent()) {
            user = one.get();
            user.setSex(sex);
            service.save(user);
            return sex;
        } else {
            return -3;  // 用户不存在
        }
    }

    @PostMapping("/set_birthday")
    public String setBirthday(String username, String birthday) {
        if (birthday == null || birthday.equals("")) {
            return "生日不能为空";
        }
        if (birthday.length() != 10
                || birthday.indexOf('-') == -1
                || !birthday.substring(0, 4).matches("[0-9]*")
                || !birthday.substring(5, 7).matches("[0-9]*")
                || !birthday.substring(8).matches("[0-9]*")) {
            return "生日格式应为 yyyy-MM-dd";
        }
        UmsUser user = new UmsUser();
        user.setUsername(username);
        Optional one = service.findOne(Example.of(user));
        if (one.isPresent()) {
            user = one.get();
            user.setBirthday(birthday);
            service.save(user);
            return birthday;
        } else {
            return "用户不存在";
        }
    }

    @PostMapping(value = "/set_avatar", produces = "application/json")
    public String setAvatar(@RequestBody JSONObject data) {
        String username = data.getString("username");
        String img = data.getString("img").replaceAll(" ", "+");

        String[] d = img.split("base64,");

        if (d.length == 2) {
            String b = d[1];

            byte[] bs = base64Util.base64Decode2Bytes(b);
            for(int i = 0 ; i < bs.length; ++i) {
                if(bs[i] < 0) {
                    //调整异常数据
                    bs[i] += 256;
                }
            }

            try {
                String imgFilePath = System.getProperty("user.dir");
                File dir = new File(imgFilePath + "/userimg/picture/");
                if (!dir.exists() && !dir.mkdirs()) {
                    return "生成图片存储路径失败";
                }

                UmsUser user = new UmsUser();
                user.setUsername(username);
                Optional one = service.findOne(Example.of(user));
                if (!one.isPresent()) {
                    return "用户不存在";
                } else {
                    user = one.get();
                    imgFilePath += "/userimg/picture/" + one.get().getUsername() + ".jpg";
                    user.setImgurl(imgFilePath);

                    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imgFilePath));
                    out.write(bs);
                    out.flush();
                    out.close();

                    service.save(user);

                    return "图片写入成功";
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "图片写入失败";
            }
        }
        return "base64格式错误";
    }

    @GetMapping("/get_avatar")
    public void getAvatar(HttpServletResponse response, String username) {
        UmsUser user = new UmsUser();
        user.setUsername(username);
        Optional one = service.findOne(Example.of(user));

        if (one.isPresent()) {
            try {
                ServletOutputStream out = response.getOutputStream();

                InputStream in = new FileInputStream(System.getProperty("user.dir") + "/userimg/picture/" + username + ".jpg");
                byte[] data = new byte[in.available()];

                while (in.read(data) == -1) break;

                in.close();

                out.write(data);
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5683968.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存