5.web支持
5-1 POM配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!-- J2EE 环境依赖 begin --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- J2EE 环境依赖 end --> |
5-2 tomcat插件
1 2 3 4 5 6 7 8 9 10 11 | <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <!-- 配置应用名,在Maven开发中,一般配置空就行 --> <path>/</path> <!-- 配置端口号 --> <port>8080</port> </configuration> </plugin> |
5-3 配置监听器
配置Application创建销毁事件的一个监听器
用于在服务器启动的时候解析Spring容器
该监听器由Spring提供,我们需要对其进行配置即可
Spring提供的监听器为:
ContenxtLoaderListener
1 2 3 | <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> |
但是,由于Spring的容器是由开发者定义的
Spring无法预先知道我们的配置文件放在哪
因此,提供了一个全局初始化参数,用于指定容器的位置
该参数的key为
contextConfigLocation 通过全局初始化对该参数值可以配置
1 2 3 4 5 6 7 | <!-- 配置全局初始化参数,用于指定Spring配置文件的位置 --> <context-param> <param-name>contextConfigLocation</param-name> <!-- 初始化参数的值支持通配符 --> <!--<param-value>classpath:applicationContext.xml</param-value>--> <param-value>classpath:applicationContext*.xml</param-value> </context-param> |
5-4 UserServlet
1 2 3 4 5 6 7 8 9 10 11 12 13 | WebApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); UserService userService = (UserService) ac.getBean("userServiceImpl"); String username = request.getParameter("username"); String password = request.getParameter("password"); try { User user = userService.login(username, password); request.getSession().setAttribute("user", user); response.sendRedirect(request.getContextPath() + "/regist.jsp"); } catch (UserNotExistException e) { request.setAttribute("loginMsg", e.getMessage()); request.getRequestDispatcher("/login.jsp").forward(request, response); } |