代码:
package com.itheima.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* @author 往
*/
@Controller
public class TargetController {
@RequestMapping("/target")
public ModelAndView show(){
System.out.println("目标资源执行");
//创建modelAndView对象
ModelAndView modelAndView = new ModelAndView();
//添加数据
modelAndView.addObject("name","itcast");
//设置显示数据页面名
modelAndView.setViewName("username");
//返回
return modelAndView;
}
}
spring配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<!--1.mvc注解驱动-->
<mvc:annotation-driven/>
<!--2.配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"/><!--资源路径目录-->
<property name="suffix" value=".jsp"/><!--后缀名-->
</bean>
<!--3.开放静态资源权限-->
<mvc:default-servlet-handler/>
<!--4.组件扫描-->
<context:component-scan base-package="com.itheima.controller"/>
</bea
分析:代码和配置文件都没有错,但实现页面跳转是显示404错误,检查路径也没错。之后查看xml配置文件时发现没有配置springMVC前端控制器。
<!--配置springMVC的前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
配置完后重新部署一下就可以正常跳转了