美文网首页
spring mvc(1)

spring mvc(1)

作者: 业余的猫 | 来源:发表于2017-03-23 12:57 被阅读0次

1.在web.xml配置dispatcher

<servlet>
    <servlet-name>frontController</servlet-name>
    <servlet-class>
              org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>frontController</servlet-name>
    <!-- '/'-会匹配到/springmvc这样的路径型url,不会匹配到模式为*.jsp这样的后缀型url。-->
    <!-- '/'-会匹配所有的url:路径型的和后缀型的url(包括/springmvc,.jsp,.js和*.html等)。-->
    <url-pattern>/</url-pattern>
</servlet-mapping>

2.在WEB-INF目录下新建frontController-servlet.xml
(备注:名称要和servlet名称相同,后缀为-servlet)

<?xml version="1.0" encoding="UTF-8"?>
<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/context
          http://www.springframework.org/schema/context/spring-context.xsd
          http://www.springframework.org/schema/mvc
          http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 一定要加上controller这个包, 否则有可能会发生HibernateException obtain a transactional-synchronize failed-->
<context:component-scan base-package="com.qfedu.dang.controller" />
<!-- 支持mvc的注解如@RequestMapping -->
<mvc:annotation-driven />
<!-- 用来处理html、css和js的资源 -->
<mvc:default-servlet-handler />
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>
</beans>

3.接着新建Controller(例如:IndexController)

@Controller
public class IndexController {
      @Autowired
      private BookTypeService bookTypeService;
      //request url "index"里面可以不用加'/'
      @RequestMapping("index")
      public String index(Model model) {
          model.addAttribute("allBookTypes", bookTypeService.getAllType());
          //返回的页面全称('index.html / index.jsp'),可以省略后缀
          return "index";
      }
}

4.总结/记录
<b>
需要注意两个地方,一个是配置servlet-mapping的时候,url-pattern一定要是"/"而不是''/*", "/*"有可能会报两个错误,404和jsp页面内容会直接呈现在网页上.但是写了"/*"会导致静态资源不能被访问,所以这时候要在*-servlet.xml文件里添加<mvc:default-servlet-handler />

相关文章

网友评论

      本文标题:spring mvc(1)

      本文链接:https://www.haomeiwen.com/subject/ueyznttx.html