Senior relearn SpringMVC--

30. SpringMVC_RESTRUL_CRUD_ display all the employee information
31. SpringMVC_RESTRUL_CRUD_ Add Action & form tag
32. SpringMVC_RESTRUL_CRUD_ deletion & treatment of static resources
33. SpringMVC_RESTRUL_CRUD_ modification operations
34. SpringMVC_ data binding process analysis
35. SpringMVC_ custom type conversion is
36. SpringMVC_annotation-driven configuration
37. SpringMVC_InitBinder annotation
38. SpringMVC_ formatted data
39. SpringMVC_JSR303 data check
display an error message and 40. SpringMVC_ international
41. SpringMVC_ return the JSON
42. a SpringMVC_HttpMessageConverter principles
43. SpringMVC_ use HttpMessageConverter
44. the SpringMVC_ international _ Overview
45. SpringMVC_ international _ the first two questions
46. SpringMVC_ international switching _ hyperlink Locale
upload files 47. SpringMVC_
48. SpringMVC_ first custom interceptor is
49. SpringMVC_ interceptor arranged
execution order of the plurality 50. a method for intercepting SpringMVC_
51. SpringMVC_ exception handling annotations _ExceptionHandler
52. SpringMVC_ exception handling _ResponseStatusExceptionResolver
53. SpringMVC_ exception handling _DefaultHandlerExceptionResolver
54. SpringMVC_ exception handling _SimpleMappingExceptionResolver
55. SpringMVC_ operational flow diagram

 springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/mvc " > 

    <-! configured to automatically scan packages -> 
    < context : Scan-Component Base-Package = "com.atguigu.springmvc" > </ context: Component-Scan > 

    ! <- configuration view resolver -> 
    < the bean class = "org.springframework.web.servlet.view. the InternalResourceViewResolver " > 
        < Property name =" prefix " value =" / the WEB-INF / views / " > </ Property > 
        <property name="suffix" value=".jsp"></property>
    </bean>
    
    <!-   
        default-the servlet-Handler SpringMVC defined in the context of a DefaultServletHttpRequestHandler,
        It will enter the request DispatcherServlet of screening, if the request has not been found to be mapped to the request referred WEB application server default 
        Servlet process. If it is not static resource requests before continuing to process the DispatcherServlet 

        general WEB application server Servlet default name is default. 
        the default name is not the default WEB Servlet server if used, by the need to explicitly specify the default-servlet-name attribute 
        
    -> 
    < MVC: the servlet-default-Handler /> 

    < MVC: Driven-Annotation Conversion-Service- = "ConversionService" > </ MVC: Annotation-Driven >     
    
    <-! configuration ConversionService -> 
    < the bean ID = "ConversionService" 
        class = "org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <ref bean="employeeConverter"/>
            </set>
        </property>    
    </bean>
    
    <!-- 配置国际化资源文件 -->
    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value= "the i18n" > </ Property > 
    </ the bean > 
    
    <-!Configuration SessionLocalResolver -> 
    < the bean ID = "LocaleResolver" 
        class = "org.springframework.web.servlet.i18n.SessionLocaleResolver" > </ the bean > 
    
    < MVC: interceptors > 
        ! <- configure custom interceptor defined -> 
        < the bean class = "com.atguigu.springmvc.interceptors.FirstInterceptor" > </ the bean > 
        
        <-! arranged interceptor (no) path effects -> 
        < MVC: interceptor > 
            < MVC: Mapping path = "/ the emps " /> 
            <bean class="com.atguigu.springmvc.interceptors.SecondInterceptor"></bean>
        </mvc:interceptor>
        
        <!-- 配置 LocaleChanceInterceptor -->
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
    </mvc:interceptors>
    
    <!--  
    <mvc:view-controller path="/i18n" view-name="i18n"/>
    -->
    <mvc:view-controller path="/i18n2" view-name="i18n2"/>
    
    <!-- 配置 MultipartResolver -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="maxUploadSize" value="1024000"></property>    
    </bean>    
    
    <!-- 配置使用 SimpleMappingExceptionResolver 来映射异常 -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionAttribute" value="ex"></property>
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
            </props>
        </property>
    </bean>    
        
</beans>

EmployeeHandler.Java

@Controller
public class EmployeeHandler {

    @Autowired
    private EmployeeDao employeeDao;
    
    @Autowired
    private DepartmentDao departmentDao;

    @ModelAttribute
    public void getEmployee(@RequestParam(value="id",required=false) Integer id,
            Map<String, Object> map){
        if(id != null){
            map.put("employee", employeeDao.get(id));
        }
    }
    
    @RequestMapping(value="/emp", method=RequestMethod.PUT)
    public String update(Employee employee){
        employeeDao.save(employee);
        
        return "redirect:/emps";
    }
    
    @RequestMapping(value="/emp/{id}", method=RequestMethod.GET)
    public String input(@PathVariable("id") Integer id, Map<String, Object> map){
        map.put("employee", employeeDao.get(id));
        map.put("departments", departmentDao.getDepartments());
        return "input";
    }
    
    @RequestMapping(value="/emp/{id}", method=RequestMethod.DELETE)
    public String delete(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }
    
    @RequestMapping(value="/emp", method=RequestMethod.POST)
    public String save(@Valid Employee employee, Errors result, 
            Map<String, Object> map){
        System.out.println("save: " + employee);
        
        if(result.getErrorCount() > 0){
            System.out.println("出错了!");
            
            for(FieldError error:result.getFieldErrors()){
                System.out.println(error.getField() + ":" + error.getDefaultMessage());
            }
            
            //若验证出错, 则转向定制的页面
            map.put("departments", departmentDao.getDepartments());
            return "input";
        }
        
        employeeDao.save(employee);
        return "redirect:/emps";
    }
    
    @RequestMapping(value="/emp", method=RequestMethod.GET)
    public String input(Map<String, Object> map){
        map.put("departments", departmentDao.getDepartments());
        map.put("employee", new Employee());
        return "input";
    }
    
    @RequestMapping("/emps")
    public String list(Map<String, Object> map){
        map.put("employees", employeeDao.getAll());
        return "list";
    }
    
//    @InitBinder
//    public void initBinder(WebDataBinder binder){
//        binder.setDisallowedFields("lastName");
//    }
    
}

SpringMVCTest.java

@Controller
public class SpringMVCTest {

    @Autowired
    private EmployeeDao employeeDao;
    
    @Autowired
    private ResourceBundleMessageSource messageSource;
    
    @RequestMapping("/testSimpleMappingExceptionResolver")
    public String testSimpleMappingExceptionResolver(@RequestParam("i") int i){
        String [] vals = new String[10];
        System.out.println(vals[i]);
        return "success";
    }
    
    @RequestMapping(value="/testDefaultHandlerExceptionResolver",method=RequestMethod.POST)
    public String testDefaultHandlerExceptionResolver(){
        System.out.println("testDefaultHandlerExceptionResolver...");
        return "success";
    }
    
    @ResponseStatus(reason="测试",value=HttpStatus.NOT_FOUND)
    @RequestMapping("/testResponseStatusExceptionResolver")
    public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
        if(i == 13){
            throw new UserNameNotMatchPasswordException();
        }
        System.out.println("testResponseStatusExceptionResolver ..." ); 
        
        return "Success" ; 
    } 
    
//     @ExceptionHandler (RuntimeException.class {})
 //     public ModelAndView handleArithmeticException2 (Exception EX) {
 //         System.out.println ( "[the abnormality]: "+ EX);
 //         ModelAndView Music Videos new new ModelAndView = (" error ");
 //         mv.addObject (" Exception ", EX);
 //         return Music Videos;
 //     } 
    
    / ** 
     * 1. in a method @ExceptionHandler exception may be added into the reference types of parameters, i.e. the parameter corresponding to the occurrence of the exception object 
     * 2. @ExceptionHandler the reference method can not pass Map. If you want to conduction abnormality information on the page, as the return value required ModelAndView
     * 3. @ExceptionHandler method labeled abnormality has priority issue. 
     * 4. @ControllerAdvice: If you can not find @ExceptionHandler method in the current Handler to come out in the current method appears abnormal, 
     * marked class will go in @ControllerAdvice @ExceptionHandler tag lookup method to handle exceptions. 
     * / 
//     @ExceptionHandler (ArithmeticException.class {})
 //     public ModelAndView handleArithmeticException (exception EX) {
 //         System.out.println ( "the abnormality:" + ex) ;
 //         ModelAndView Music Videos new new ModelAndView = ( "error");
 //         mv.addObject ( "Exception", EX);
 //         return Music Videos;
 //     } 
    
    @RequestMapping ( "/ testExceptionHandlerExceptionResolver" )
     public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i){
        System.out.println("result: " + (10 / i));
        return "success";
    }
    
    @RequestMapping("/testFileUpload")
    public String testFileUpload(@RequestParam("desc") String desc, 
            @RequestParam("file") MultipartFile file) throws IOException{
        System.out.println("desc: " + desc);
        System.out.println("OriginalFilename: " + file.getOriginalFilename());
        System.out.println("InputStream: " + file.getInputStream());
        return "success";
    }
    
    @RequestMapping("/i18n")
    public String testI18n(Locale locale){
        String val = messageSource.getMessage("i18n.user", null, locale);
        System.out.println(val); 
        return "i18n";
    }
    
    @RequestMapping("/testResponseEntity")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{
        byte [] body = null;
        ServletContext servletContext = session.getServletContext();
        InputStream in = servletContext.getResourceAsStream("/files/abc.txt");
        body = new byte[in.available()];
        in.read(body);
        
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=abc.txt");
        
        HttpStatus statusCode = HttpStatus.OK;
        
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
        return response;
    }
    
    @ResponseBody
    @RequestMapping("/testHttpMessageConverter")
    public String testHttpMessageConverter(@RequestBody String body){
        System.out.println(body);
        return "helloworld! " + new Date();
    }
    
    @ResponseBody
    @RequestMapping("/testJson")
    public Collection<Employee> testJson(){
        return employeeDao.getAll();
    }
    
    @RequestMapping("/testConversionServiceConverer")
    public String testConverter(@RequestParam("employee") Employee employee){
        System.out.println("save: " + employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }
    
}

 

Guess you like

Origin www.cnblogs.com/gzhcsu/p/11699723.html