file-type

Spring MVC实现servlet3.0无web.xml配置详解

ZIP文件

下载需积分: 50 | 23KB | 更新于2024-11-22 | 147 浏览量 | 4 评论 | 2 下载量 举报 收藏
download 立即下载
随着Web开发技术的不断进步,Java开发社区中的Spring MVC框架也经历了快速的更新。在Servlet 3.0规范发布之后,开发者可以在不使用传统的web.xml文件的情况下配置Spring MVC。本文将详细探讨如何利用Servlet 3.0+特性在Spring MVC中实现无web.xml配置,并介绍相关的知识点。 首先,Servlet 3.0规范引入了注解驱动的配置方式,这使得开发者无需再依赖web.xml文件来配置Servlet、Filter等Web组件。这种做法简化了Web应用的配置过程,并提高了配置的灵活性。 在Spring MVC中,利用Servlet 3.0+特性进行无web.xml配置,主要是通过以下几个步骤实现的: 1. **使用注解配置DispatcherServlet**: 在Spring 3.1及更高版本中,可以通过注解的方式来配置DispatcherServlet。开发者可以在Spring配置类上添加@EnableWebMvc注解,这会启用Spring MVC的配置。此外,需要将Servlet容器中的DispatcherServlet映射到应用上下文路径上,这通常可以通过在Servlet初始化参数中设置"contextConfigLocation"实现。 2. **Servlet初始化参数配置**: 在使用Servlet 3.0+时,如果需要设置初始化参数,可以通过注解的方式来完成。例如,可以在Spring的Servlet监听器中通过@ServletInitParam注解来添加初始化参数,这样就可以避免在web.xml中配置。 3. **使用Spring Boot简化配置**: 虽然Servlet 3.0+已经提供了在Java配置中省略web.xml的能力,但Spring Boot进一步简化了Spring MVC应用的配置工作。Spring Boot提供了一个自动配置机制,可以自动配置DispatcherServlet和其他Spring MVC组件,使得开发者甚至不需要手动编写@EnableWebMvc注解来启用Spring MVC。Spring Boot还支持内嵌的Servlet容器,比如Tomcat、Jetty或Undertow,这样可以更进一步简化部署过程。 4. **Java配置与XML配置的兼容**: 尽管重点是介绍无web.xml配置,但在某些情况下,项目可能需要同时支持Java配置和XML配置。在Spring MVC中,可以使用@ImportResource注解来导入XML配置文件。这种方式提供了灵活性,允许开发者逐步迁移现有的XML配置到Java配置。 5. **编程式配置**: 对于更高级的用例,Spring MVC还允许通过编程式的方式配置Web组件。这意味着开发者可以使用Java代码来直接配置Servlet、Filter等组件,并将它们注册到Servlet容器中。这通常涉及到实现WebApplicationInitializer接口,然后在实现的方法中添加自定义的Web配置。 6. **兼容性和可扩展性**: 虽然无web.xml配置方式带来了便利,但是它需要确保所使用的Servlet容器支持Servlet 3.0+规范。同时,开发者在迁移旧项目到无web.xml配置时需要考虑到兼容性问题,确保新旧配置方式不会产生冲突。 7. **资源文件管理**: 在无web.xml配置中,静态资源文件(如JavaScript、CSS、图片等)的映射可以通过配置Spring MVC的静态资源处理器来完成。这可以通过实现WebMvcConfigurer接口并重写addResourceHandlers方法来实现,从而指定静态资源的存放位置和访问路径。 8. **安全性配置**: 安全是Web应用开发中不可忽视的一部分。在无web.xml配置的情况下,可以利用Spring Security等安全框架,并通过Java配置类来设置安全策略,包括用户认证、授权等。 通过以上步骤和知识点的介绍,可以看出,使用Servlet 3.0+进行无web.xml配置的Spring MVC应用,不仅可以使配置更加简洁,还能提高开发效率和应用的灵活性。然而,开发者在使用这种配置方式时需要充分理解Java配置背后的工作原理,以确保应用的正确部署和运行。随着Spring Boot的广泛使用,这种无web.xml配置方式已经成为了许多Java Web开发者的首选。

相关推荐

filetype

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>ssm</display-name> <filter> <filter-name>charset</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>charset</filter-name> <servlet-name>springmvc</servlet-name> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> classpath填什么?

filetype

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://JAVA.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>springMVC</display-name> <welcome-file-list> <welcome-file>/WEB-INF/jsp/login.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext-mybatis.xml</param-value> </context-param> <filter> <filter-name>encodingFilter</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <param-name>webAppRootKey</param-name> <param-value>keshe_C12_09.root</param-value> </context-param> <listener> <listener-class> org.springframework.web.util.Log4jConfigListener </listener-class> </listener> </web-app>

filetype

<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>spring</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring.xml</param-value> </context-param> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <description>Spring监听器</description> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <description>SpringMVC</description> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> <url-pattern>*.css</url-pattern> <url-pattern>*.html</url-pattern> <url-pattern>/upload/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>

filetype

6月 21, 2025 4:40:31 上午 org.apache.coyote.AbstractProtocol init 信息: Initializing ProtocolHandler ["http-bio-8080"] 6月 21, 2025 4:40:31 上午 org.apache.catalina.core.StandardService startInternal 信息: Starting service Tomcat 6月 21, 2025 4:40:31 上午 org.apache.catalina.core.StandardEngine startInternal 信息: Starting Servlet Engine: Apache Tomcat/7.0.47 6月 21, 2025 4:40:32 上午 org.apache.catalina.startup.ContextConfig processAnnotationsJar 严重: Unable to process Jar entry [META-INF/versions/11/module-info.class] from Jar [jar:file:/C:/Users/26945/.m2/repository/com/zaxxer/HikariCP/5.0.1/HikariCP-5.0.1.jar!/] for annotations org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19 at org.apache.tomcat.util.bcel.classfile.Constant.readConstant(Constant.java:133) at org.apache.tomcat.util.bcel.classfile.ConstantPool.<init>(ConstantPool.java:60) at org.apache.tomcat.util.bcel.classfile.ClassParser.readConstantPool(ClassParser.java:209) at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:119) at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2134) at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:2010) at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1976) at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1961) at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1319) at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878) at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:376) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119) at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) at java.base/java.lang.Thread.run(Thread.java:840) 6月 21, 2025 4:40:33 上午 org.apache.catalina.core.ApplicationContext log 信息: No Spring WebApplicationInitializer types detected on classpath 6月 21, 2025 4:40:33 上午 org.apache.coyote.AbstractProtocol start 信息: Starting ProtocolHandler ["http-bio-8080"]

filetype

<?xml version="1.0" encoding="UTF-8" standalone="no"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.1" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"> <context-param> <param-name>metadata-complete</param-name> <param-value>true</param-value> </context-param> <servlet> <servlet-name>exampleServlet</servlet-name> <servlet-class>com.example.ExampleServlet</servlet-class> </servlet> <servlet> <description>generated-servlet</description> <servlet-name>KuCun2 Servlet</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:KuCun2-web-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet> <description>generated-resources-servlet</description> <servlet-name>Resource Servlet</servlet-name> <servlet-class> org.springframework.js.resource.ResourceServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>exampleServlet</servlet-name> <url-pattern>/example</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Resource Servlet</servlet-name> <url-pattern>/resources/*</url-pattern> </servlet-mapping> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> </web-app>

filetype

(一)项目构建 使用 Maven 构建项目,在pom.xml中引入 Spring MVC 相关依赖,如spring - webmvc,配置 Servlet、JSP 等相关依赖,确保项目具备 Spring MVC 运行环境 。示例关键依赖配置: <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring - webmvc</artifactId> <version>5.3.18</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet - api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp - api</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> </dependencies> (二)Spring MVC 配置 DispatcherServlet 配置:在 Web.xml(或 Servlet 3.0 + 环境下用 Java 配置)中配置 DispatcherServlet,指定 Spring MVC 配置文件位置,使其能拦截处理请求 。示例 Web.xml 配置: <servlet> <servlet - name>springmvc</servlet - name> <servlet - class>org.springframework.web.servlet.DispatcherServlet</servlet - class> <init - param> <param - name>contextConfigLocation</param - name> <param - value>classpath:springmvc - servlet.xml</param - value> </init - param> <load - on - startup>1</load - on - startup> </servlet> <servlet - mapping> <servlet - name>springmvc</servlet - name> <url - pattern>/</url - pattern> </servlet - mapping> Spring MVC 配置文件(springmvc - servlet.xml):开启组件扫描(扫描控制器等组件)、视图解析器(配置前缀后缀,解析 JSP 视图)、开启注解驱动等 。示例: <context:component - scan base - package="com.example.controller"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB - INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <mvc:annotation - driven/> 三)功能模块实现 1. 用户登录验证 o 控制器(Controller):创建LoginController,编写方法处理/login请求(对应login.jsp表单提交),接收用户名、密码参数(可通过@RequestParam注解),进行简单验证(如硬编码用户名 “admin”、密码 “123” 模拟,实际可连数据库查询),验证成功用return "redirect:/main";重定向到主页控制器方法,失败则带错误信息(通过model.addAttribute)返回login视图(即login.jsp )。示例代码: package com.example.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class LoginController { @RequestMapping("/login") public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model) { if ("admin".equals(username) && "123".equals(password)) { return "redirect:/main"; } else { model.addAttribute("error", "用户名或密码错误"); return "login"; } } 2. 登录页面(login.jsp):使用 Spring 表单标签库(需引入相关标签库)或普通 HTML 表单,提交到/login,显示错误信息(通过 EL 表达式${error} )。示例关键代码: <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <html> <body> <form:form action="/https/wenku.csdn.net/login" method="post"> 用户名:<form:input path="username"/>
密码:<form:password path="password"/>
<input type="submit" value="登录"> </form:form> <c:if test="${not empty error}">

${error}

</c:if> </body> </html> 3. 访问控制(拦截器实现) o 创建拦截器类:实现HandlerInterceptor接口,在preHandle方法中检查会话是否有用户登录标识(如session.getAttribute("user") ,假设登录成功时在会话存user对象),无则redirect到/login并返回false拦截,有则返回true放行 。示例: package com.example.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Object user = request.getSession().getAttribute("user"); if (user == null) { response.sendRedirect(request.getContextPath() + "/login"); return false; } return true; } } 4. 配置拦截器:在 Spring MVC 配置文件(springmvc - servlet.xml)中注册拦截器,指定拦截路径(如/main )。示例: <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/main"/> <bean class="com.example.interceptor.LoginInterceptor"/> </mvc:interceptor> </mvc:interceptors> 5. 会话管理(登出功能) o 控制器方法:在MainController中编写处理登出的方法,调用session.invalidate()销毁会话,然后redirect到登录页 。示例: package com.example.controller; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MainController { @RequestMapping("/main") public String main() { return "main"; } @RequestMapping("/logout") public String logout(HttpSession session) { session.invalidate(); return "redirect:/login"; } } 6. 主页(main.jsp):添加 “退出” 链接, href 指向/logout 。示例: <html> <body>

欢迎访问主页

退出 </body> </html>
资源评论
用户头像
东方捕
2025.07.25
该文档是Java Web开发者的福音,省去了web.xml的繁琐配置,提高了开发效率。
用户头像
扈涧盛
2025.05.04
对于希望了解最新Spring技术的开发者,这篇文章提供了有价值的实践知识。
用户头像
人亲卓玛
2025.04.26
文章详细介绍了Spring MVC和Servlet 3.0的结合使用,对减少部署描述符的依赖具有指导意义。
用户头像
文润观书
2025.03.17
这篇文章深入探讨了如何在Spring MVC中使用Servlet 3.0标准来实现无web.xml配置,对Java开发者非常实用。
迷荆
  • 粉丝: 77
上传资源 快速赚钱