快速搭建
首先是web项目,还需要web.xml去配置一个springMVC核心接受参数spring用的是servlet开发的
1.创建web maven项目
2.导包 spring的所有包 spring-web包 spring-MVC包
3.书写配置文件
springmvc.xml
开启注解
<context:component-scan base-package="com.hd.controlter"></context:component-scan>
4.写一个类
@Controller
public class helloController {
@RequestMapping("/hello")
public void hello(){
System.out.println("hello spring");
} <version>3.4.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
}
5.在web.xml里面输入springmvc核心类
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<!--
/* 拦截所有 包括静态济源
/目录匹配
*.action后缀名匹配
-->
<url-pattern>*.action</url-pattern>
</servlet-mapping>
6.测试打开网页,输入地址
注意:如果使用的是maven项目,打开的方式要更改为war,默认的jar,改为war配置tomcat,选用xxx:war
打开网页可能出现404错误,在控制台打印了代码,说明我们写的方法已经执行了
调用setViewName方法可以实现页面转发
public ModelAndView hello(){
System.out.println("hello spring");
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("/index.jsp");
return modelAndView;
}