URL未与Spring MVC映射

时间:2015-01-31 16:02:49

标签: java spring spring-mvc

我正在配置一个基本的Spring MVC项目,但我不明白为什么URL不会被我的控制器捕获。

这是在web.xml

<servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

这是servlet上下文:

<annotation-driven />

<resources mapping="/resources/**" location="/resources/" />

<beans:bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.lh.mvcex" />

这是HomeController

@Controller
public class HomeController {

    @RequestMapping(value = { "/", "home", "/home.jsp" }, method = RequestMethod.GET)
    public String home_jsp(Locale locale, Model model) {
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
                DateFormat.LONG, locale);

        String formattedDate = dateFormat.format(date);

        model.addAttribute("serverTime", formattedDate);

        return "home";
    }
}

URL /和/ home正确映射到我的home.jsp资源,但不是第三个(home.jsp),它给了我404.

问题1:为什么?

此外,我想映射一个不利用视图解析器返回页面的请求(让我们说/ customhome),而是希望它返回普通的html。 问题2:我怎样才能返回普通的HTML?

最后,我想在资源文件夹中映射一个返回资源home.html的请求(让我们说/ statichome)。 问题3:如何返回静态页面?

1 个答案:

答案 0 :(得分:1)

此servlet映射模式

<url-pattern>/</url-pattern>

是默认的网址格式。它将匹配任何其他url-pattern未匹配的请求。据推测,您的Servlet容器的servlet-mapping

<url-pattern>*.jsp</url-pattern>

用于其JSP处理servlet。如果请求的网址具有DispatcherServlet扩展名,则优先于.jsp

您可以使用@ResponseBody并返回包含HTML的String我不建议这样做。将Java与HTML分开。

再次使用@ResponseBody,您可以返回一个Resource对象,用于标识要序列化到响应正文的资源。