前面做了那么多铺垫,现在我们开始着手处理后台管理系统。
首先,大家需要下载淘淘商城的静态资源文件,大家可以到:http://download.csdn.net/detail/u012453843/9794517这个地址进行下载,下载后解压,解压后可以看到有css、js、jsp三个文件夹。我们把这三个文件夹分别放到taotao-manager-web工程的src/main/webapp下及src/main/webapp/WEB-INF下,如下图所示。
为什么我们把jsp放到WEB-INF下面呢?这是因为我们在taotao-mamager-web工程的springmvc.xml文件中配置了关于jsp的视图解析器,把jsp放到了WEB-INF下,所以为了保持一致,我们把jsp放到了WEB-INF下。当然,也可以修改视图解析器配置,只要两者路径一致即可。
为了访问index.jsp页面,我们需要写一个Controller类,通过访问Controller来间接访问index.jsp。我们定义的Controller类是PageController。如下图所示。
我们重新启动taotao-manager-web工程,启动后,我们访问http://localhost:8081/会看到如下图所示信息,这明显不是我们的后台页面。为什么会出现这种情况呢?这是因为在src/main/webapp下本来就有个index.jsp,因此首先去访问它了,这样就不能访问位于src/main/webapp/WEB-INF下面的index.jsp了。
为了解决上面的那个问题,我们需要把位于src/main/webapp下的index.jsp删掉(下图蓝色圈住的index.jsp文件需要删掉)。
删除掉src/main/webapp下的index.jsp之后我们再访问http://localhost:8081/,我们会看到如下图所示页面,很明显,css样式没有出来,出现这种情况的原因是资源被拦截了,我们需要配置一下资源映射。
我们打开springmvc.xml文件,在其中添加资源配置映射,如下图所示。
方便大家复制,现把整个springmvc.mxl文件粘贴如下:
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!-- 配置注解驱动 -->
<mvc:annotation-driven />
<!-- 视图解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置包扫描器,扫描@Controller注解的类 -->
<context:component-scan base-package="com.taotao.controller"/>
<!-- 配置资源映射 -->
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<!-- 引用dubbo服务 -->
<dubbo:application name="taotao-manager-web"/>
<dubbo:registry protocol="zookeeper" address="192.168.156.40:2181"/>
<dubbo:reference interface="com.taotao.service.ItemService" id="itemService" />
</beans>
配置完资源映射,我们再重新启动taotao-manager-web工程。然后再访问http://localhost:8081/,可以看到如下图所示界面,我们点击"新增商品"发现控制台会报错,提示找不到item-add页面。
既然是index.jsp页面访问别的页面的时候报的错,我们便看看index.jsp的请求页面及我们的静态页面的关系,如下图所示。发现index.jsp访问的页面就是我们的静态页面,名字一样。因此我们现在需要做的就是在Controller中通过拦截器把访问路径中的item-add这个串得到然后经过自动补充后缀.jsp从而返回一个同名的item-add.jsp回去,这样就可以访问了,其它页面的访问情况一样。
我们在PageController类中添加如下代码。
下面我们重新启动taotao-manager-web工程,如下图所示,我们可以正常访问到新增商品界面了。我们再点击下其它页面,发现都可以正常访问了。