BaseController.java 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package com.fdkankan.manage_jp.controller;
  2. import com.fdkankan.common.util.DateEditor;
  3. import com.fdkankan.common.util.JwtUtil;
  4. import com.fdkankan.manage_jp.common.ResultCode;
  5. import com.fdkankan.manage_jp.entity.User;
  6. import com.fdkankan.manage_jp.exception.BusinessException;
  7. import com.fdkankan.manage_jp.service.IUserService;
  8. import org.apache.commons.lang3.StringUtils;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.beans.propertyeditors.StringTrimmerEditor;
  11. import org.springframework.web.bind.WebDataBinder;
  12. import org.springframework.web.bind.annotation.InitBinder;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15. import java.io.*;
  16. import java.util.Date;
  17. public class BaseController {
  18. @Autowired
  19. protected HttpServletRequest request;
  20. @Autowired
  21. protected HttpServletResponse response;
  22. @Autowired
  23. IUserService userService;
  24. @InitBinder
  25. protected void initBinder(WebDataBinder webDataBinder) {
  26. webDataBinder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
  27. webDataBinder.registerCustomEditor(Date.class, new DateEditor(true));
  28. }
  29. public static void output(HttpServletResponse resp, File file) {
  30. OutputStream os = null;
  31. BufferedInputStream bis = null;
  32. byte[] buff = new byte[1024];
  33. try {
  34. os = resp.getOutputStream();
  35. bis = new BufferedInputStream(new FileInputStream(file));
  36. int i = 0;
  37. while ((i = bis.read(buff)) != -1) {
  38. os.write(buff, 0, i);
  39. os.flush();
  40. }
  41. } catch (IOException e) {
  42. e.printStackTrace();
  43. } finally {
  44. try {
  45. bis.close();
  46. } catch (IOException e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. }
  51. protected String getToken(){
  52. return request.getHeader("token");
  53. }
  54. protected User getUser(){
  55. String username = JwtUtil.getUsername(getToken());
  56. if(StringUtils.isBlank(username)){
  57. throw new BusinessException(ResultCode.USER_NOT_LOGIN);
  58. }
  59. User user = userService.getByUserName(username);
  60. if(user == null){
  61. throw new BusinessException(ResultCode.USER_NOT_LOGIN);
  62. }
  63. return user;
  64. }
  65. }