Spring集成Web环境与SpringMVC组件的扩展使用详解
1. Spring集成Web环境
Spring是一种用于构建企业级Java应用程序的开源框架。在创建Spring应用程序时,您需要在您的应用程序中集成Web环境,以便能够与Web浏览器进行交互。以下是在Spring中集成Web环境的步骤:
- 在项目的pom.xml中添加以下依赖项:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.9</version>
</dependency>
- 在Spring配置文件中,开启Spring MVC:
<mvc:annotation-driven />
- 配置DispatcherServlet和Servlet mapping:
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
2. SpringMVC组件的扩展使用
Spring MVC是Spring框架的一个子框架,用于构建Web应用程序。以下是两个常用的SpringMVC组件及其扩展使用方法:
2.1. Handler Interceptor
Handler Interceptor用于在请求被处理前和处理后执行一些操作,例如记录日志、加密等等。以下是在Spring MVC中配置Handler Interceptor的步骤:
- 实现HandlerInterceptor接口:
public class LoggingInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 在请求被处理前执行
Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);
logger.info("Request URL::" + request.getRequestURL().toString() + ":: Start Time=" + System.currentTimeMillis());
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 在请求被处理后执行
Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);
logger.info("Request URL::" + request.getRequestURL().toString() + ":: End Time=" + System.currentTimeMillis());
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 在请求完成后执行
}
}
- 在Spring配置文件中,注册Handler Interceptor:
<mvc:interceptors>
<bean class="com.example.LoggingInterceptor" />
</mvc:interceptors>
2.2. Controller Advice
Controller Advice用于处理全局异常或数据绑定错误等问题。以下是在Spring MVC中配置Controller Advice的步骤:
- 实现ControllerAdvice接口:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
public ModelAndView handleException(HttpServletRequest request, Exception ex) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("errorMessage", ex.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
- 在Spring配置文件中,开启@ControllerAdvice的支持:
<mvc:annotation-driven/>
同时,需要把ExceptionHandler类所在的包注册到Spring Context中。例如,如果ExceptionHandler类在com.example包中,则在Spring配置文件中添加以下内容:
<context:component-scan base-package="com.example"/>
示例
示例1:Handler Interceptor的使用
以下是一个示例,演示如何在Spring MVC中使用Handler Interceptor来记录日志:
@Controller
@RequestMapping("/helloWorld")
public class HelloWorldController {
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello World!");
return "helloWorld";
}
}
<mvc:interceptors>
<bean class="com.example.LoggingInterceptor" />
</mvc:interceptors>
在访问http://localhost:8080/helloWorld时,日志输出如下:
Request URL::http://localhost:8080/helloWorld:: Start Time=1629640048801
Request URL::http://localhost:8080/helloWorld:: End Time=1629640048901
示例2:Controller Advice的使用
以下是一个示例,演示如何在Spring MVC中使用Controller Advice来处理全局异常:
@Controller
public class HelloWorldController {
@RequestMapping(value = "/throwException", method = RequestMethod.GET)
public String throwError() {
throw new RuntimeException("This is a runtime exception!");
}
@RequestMapping(value = "/catchException", method = RequestMethod.GET)
public String handleError(Model model) {
return "error";
}
}
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
public ModelAndView handleException(HttpServletRequest request, Exception ex) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("errorMessage", ex.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
<mvc:annotation-driven/>
<context:component-scan base-package="com.example"/>
在访问http://localhost:8080/throwException时,应用程序会抛出RuntimeException。然后,Controller Advice会捕获该异常并将其重定向到http://localhost:8080/catchException。最终,将渲染error.jsp页面,页面中显示:
This is a runtime exception!
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Spring集成Web环境与SpringMVC组件的扩展使用详解 - Python技术站