SpringMVC简单的开始
利用Spring模板配置写一个web项目。
1.核心配置文件(模板代码)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 关联一个springmvc的配置文件--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!-- 启动级别--> <load-on-startup>1</load-on-startup> </servlet> <!-- / 匹配所有请求,不包括.jsp--> <!-- /* 匹配所有请求,包括.jsp --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
2.spring配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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"> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> <!-- 视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver"> <!-- 前缀--> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <bean id="/h1" class="com.lian.HelloServlet"/> </beans>
3.写Servlet类HelloController
public class HelloController implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { // ModelAndView模型和视图 ModelAndView mv=new ModelAndView(); //封装对象,放在 ModelAndView中 mv.addObject("msg","HelloSpringMVC!!"); //封装要跳转的视图,放在 ModelAndView中 mv.setViewName("hello");///WEB-INF/jsp/hello.jsp return mv; } }
写这个例子的时候要跳转到 /h1 页面时候报404错误
查看了project Structure发现是项目的lib包没进来
要保证项目需要的包都导入了
标签:SpringMVC,开始,跳转,视图,springmvc,mv,简单,ModelAndView From: https://www.cnblogs.com/MyBlogs-joyiyii/p/17342703.html