优化SpringMVC配置1的配置文件路径问题,以及访问controller的路径问题
1.引入jar包
2.配置web.xml文件
<?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">
<!-- SpringMVC 前端控制器,入口 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 设置 springmvc.xml 的路径在src下-->
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 自启动-在启动tomcat时立即加载对应的Servlet -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- 只能放行jsp,这个地方很容易出错 不要配成/* ,否则jsp文件无法解析-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.配置springmvc.xml
<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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 告诉SpringMVC的注解在哪里 -->
<context:component-scan base-package="com.sixfly.controller"></context:component-scan>
<!-- 配置标签让SPringMVC注解生效,创建注解解析器. -->
<mvc:annotation-driven />
<!-- 如果碰见请求中/js/xx格式请求,去location配置的/js中去寻找,配置放行静态资源 -->
<!-- 如果没有配置mvc:resources去寻找@requestmappingg -->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/" mapping="/**"></mvc:resources>
</beans>
4.测试代码
package com.sixfly.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class SixController {
@RequestMapping("show")
public String show(){
System.out.println("配置方式2 show");
return "index.jsp";
}
}
5.jsp页面
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>welcome</title>
</head>
<body>
<img src="images/fun.jpg" />
<br />
<font size="20"> sixfly</font>
</body>
</html>
6.输出效果
6.1控制台输出
6.2页面效果