首先配置前端控制器(也就是Servlet),在webxml中
<servlet>
<servlet-name>Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
在resources文件下配置springmvc.xml
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 开启注解扫描-->
<context:component-scan base-package="cn.xf"></context:component-scan>
<!-- 配置视图解析器-->
<bean id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置查询文件的目录-->
<property name="prefix" value="WEB-INF/pages/"></property>
<!-- 配置查询文件的类型-->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
这时我们就可以写servlet了
ackage cn.xf;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.sql.SQLOutput;
@Controller
public class HelloController {
@RequestMapping(path = "/hello")
public String getPages()
{
System.out.println("hello");
return "success";
}
}
这里在类上加注解@Controller,此类就变成了一个servlet, @RequestMapping(path = “/hello”)指定了访问该文件的路径
return “success”`;是返回一个页面,通过视图解析器跳转到这个页面
要让springmvc.xml被加载,别忘了在web.xml文件里加上
<init-param>
<!-- 加载配置文件-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:SpringMVC.xml</param-value>
</init-param>
<!-- 启动服务器时创建-->
<load-on-startup>1</load-on-startup>
最后在WEB-INF包下创建包pages,在里面放入success.jsp文件,整个入门程序就大功告成了!