SpringMVC 고급 개발 기능 실현 과정 분석

전역 이상 프로세서

1.사용자 정의 이상 클래스 를 작성 하여 어떤 이상 이 시스템 이상 인지,어떤 이상 이 사용자 의 부당 한 조작 이상 인지 구분 합 니 다.

//  Exception
public class UserException extends Exception{

  private static final long serialVersionUID = -8469276157483476569L;

  public UserException() {
    super();
  }

  public UserException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
    super(message, cause, enableSuppression, writableStackTrace);
  }

  public UserException(String message, Throwable cause) {
    super(message, cause);
  }

  public UserException(String message) {
    super(message);
  }

  public UserException(Throwable cause) {
    super(cause);
  }
2.전역 이상 처리 장 치 를 만 듭 니 다.이 처리 장 치 는 Handler ExceptionResolver 를 실현 해 야 합 니 다.

//        spring    
@Component
public class MyExceptionHandler implements HandlerExceptionResolver {
  @Override
  public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
      Exception ex) {
    // ex           
    //     ,      ,          
    //     ,    :     ,       
    ModelAndView modelAndView = new ModelAndView();if (ex instanceof UserException) {//    
      modelAndView.addObject("error", ex.getMessage());
    } else {//    
      modelAndView.addObject("error", "    ,     !!!");
    }
    modelAndView.setViewName("error");
    return modelAndView;
  }
3.springMVC 설정 파일 에 전역 이상 프로 세 서 를 설정 합 니 다.
① Component ② 를 사용 하여 springmvc 설정 파일 에을 수 동 으로 추가 합 니 다.
4.이 exception 가방 의 주 해 를 스 캔 합 니 다.
2.json 지원 에 응답

AJAX:배경 응답 을 요구 하 는 것 은 데이터 입 니 다.배경 방향 을 바 꾸 고 한 페이지 로 전송 합 니 다.이 페이지 를 하나의 데이터 로 생각 하고 ajax 에 응답 합 니 다.
배경:자바 대상
프론트:ajax->js 대상,json 을 사용 하려 면 배경 에서 자바 대상 을 json 형식의 문자열 로 변환 해 야 합 니 다.
Servlet:json-lib 를 사용 하여 JSONobject 를 수 동 으로 호출 합 니 다.
SpringMVC 변환 json,사용:1)jackson**2)fastjson
1.jackson 가 져 오기 의존:bundle을 삭제 하고 필요 한 jar 를 가 져 옵 니 다.

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.10.0</version>
</dependency>
Controller 방법의 반환 값 자바 대상 은@ResponseBody 에 맞 춰 방법의 반환 값 을 데이터 로 전단 에 응답 해 야 합 니 다.****
자바 대상 이 고 json 에 대한 의존 도(jaskson/fastJSon)를 가 져 오 면 컨버터 를 호출 하여 자바 대상 을 json 형식 문자열 로 전단 에 응답 합 니 다.
날 짜 를 지정 한 형식의 문자열 로 변환 합 니 다.
@DateTimeFormat(pattern="yyy-MM-dd")//SpringMVC 의 주석 으로 전단 의 문자열 을 Date 로 변환 합 니 다.
@JSonFormat(pattern="yyy-MM-dd")//jackson 의 주석,Date 를 json 이 지정 한 형식의 문자열 로 변환 합 니 다.
@JsonFormat(pattern = "yyyy-MM-dd")
private Date brithday;[/code]
어떤 속성 을 json 으로 변환 하 는 것 을 무시 합 니 다.
@JsonIgnoreprivate String password;
@RequestBody:백 엔 드 에 전 달 된 json 문자열 의 데 이 터 를 수신 하 는 데 주로 사 용 됩 니 다(요청 체 의 데이터).post 만 제출 할 수 있 고 get 은 요청 체 가 없습니다.
주 해 는 http 에서 요청 한 내용(문자열)을 읽 는 데 사 용 됩 니 다.springmvc 에서 제공 하 는 HttpMessageConverter 인 터 페 이 스 를 통 해 읽 은 내용 을 json,xml 등 형식의 데이터 로 변환 하고 controller 방법의 매개 변수 에 연결 합 니 다.

//    json,   json
@RequestMapping("/queryUserByCondition.action")
@ResponseBody
public User  queryUserByCondition( @RequestBody User user) throws Exception{
  return user;
}
전단 코드

//    json
    function requestJson(){
      //     json
      //      , data json,   js  ,   key/value
      //contentType:"application/json;charset=utf-8",   json      
      $.ajax({
      url:"${pageContext.request.contextPath }/user/queryUserByCondition.action",
      type:"post",
      //data:"id=2&username=  &sex= &brithday=1999-12-21",
      contentType:"application/json;charset=utf-8", 
      data:'{"id":3,"username":"  ","sex":" ","brithday":"2012-12-12"}',
      success:function(rs){
        alert(rs.username+"-->"+rs.sex); // json       js  
      },
      dataType:"json"
        });
    }
파일 업로드
1.페이지 에 대한 요구:
form 의 method:postform 의 enctype:기본 값:application/x-www-form-urlencoded 는 반드시 multipart/form-data 사용파일 선택
2.페이지 에 대한 요구:
파일 업로드 의존 도 가 져 오기:comons-fileupload comons-io

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.4</version>
</dependency>
3.springMVC 프로필 에 올 린 해상도

<!--      -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
 <!--             :10M-->
<property name="maxUploadSize" value="10485760"></property>
</bean>
메모:bean 의 id 는 반드시 multipart Resolver 입 니 다.그렇지 않 으 면 데 이 터 를 얻 을 수 없습니다.
4.파일 코드

@PostMapping("/addUser.action")
  public String addUser(User user, MultipartFile photo,Model model) throws Exception{
    if(photo == null) {
      throw new UserException("     ");
    }else {
      //    
      String savePath = "D:\\upload";
      //File 
      File pathFile = new File(savePath);
      if(!pathFile.exists()) {
        //     
        pathFile.mkdirs();
      }
      //     :       UUID 
      //          
      String uploadFileName = photo.getOriginalFilename();
      String suffix = uploadFileName.substring(uploadFileName.lastIndexOf("."));
      String saveFilename = UUID.randomUUID().toString().replace("-", "").toUpperCase()+suffix;
      //  
      photo.transferTo(new File(savePath,saveFilename));
      // user   photoPath    
      user.setPhotoPath(saveFilename);
      
      //     ,    
      userService.saveUser(user);
      model.addAttribute("msg", "    ");
    }
    return "msg";
  }
  
tomcat 에 맵 경 로 를 설정 해 야 합 니 다.

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기