Simple exception handler that comes with springmvc (1)

Springmvc comes with an exception handler called SimpleMappingExceptionResolver, which implements the HandlerExceptionResolver interface, and all global exception handlers need to implement this interface. We want to use this built-in exception handler,

Step 1: Configure the processor in the springmvc.xml file

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value ="/jsp/"></property>
        <property name="suffix" value =".jsp"></property>
    </bean>
    <!-- Simple exception handler provided by springmvc-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
         <!-- Define the default exception handling page-->
        <property name="defaultErrorView" value="error"/>
        <!-- Define the variable name used by the exception handling page to obtain exception information, or not define, the default name is exception -->
        <property name="exceptionAttribute" value="ex"/>
        <!-- Define exceptions that require special handling, this is the important point-->
        <property name="exceptionMappings">
            <props>
                <prop key="com.test.validator.entity.GyException">custom_error</prop>
            </props>
            <!-- You can also define other custom exceptions -->
        </property>
    </bean>

Step 2: Create the exception class

public class GyException extends Exception {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private String exception;
	public GyException() {}
	public GyException(String exception) {
		super(exception);
		this.exception =exception;
	}

Step 3: Throw Exception

@RequestMapping(value="exception")
	public String ecxeption(HttpServletRequest httpServletRequest , HttpServletResponse httpServletResponse ,User user) throws Exception {
	    if(user.getUserName()==null) {
	    	System.out.println("Username cannot be empty");
				 throw new GyException();
	    	
	    }
	      return "custom_error";
    }

Step 4: Page Acquisition

${ex}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325894316&siteId=291194637