简单的SpringMVC 实例
写了个简单的SpringMVC 实例,简单的传参
架包导入
我们发现各个spring版本的下载地址: http://repo.spring.io/release/org/springframework/spring可以在这里下载SpringMVC 的架包
首先需要将jar包导入WEB-INF下的lib目录下
解压下载的架包,进入目录spring-framework-4.2.5.RELEASE\libs ,将此目录下的以“.RELEASE.jar”结尾的jar包都导入,除此之外还需要一个commons-logging-1.1.3.jar架包
- web.xml
如果不用
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:com/feizi/config/springmvc-servlet.xml</param-value>
</init-param>
规定SpringMVC xml配置文件的路径则默认是在/WEB-INF/下
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 加载/WEB-INF/[servlet-name]-servlet.xml -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
- springMVC-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 启用spring mvc 注解 -->
<context:annotation-config />
<!-- 设置使用注解的类所在的jar包 -->
<context:component-scan base-package="com.myp.controller"></context:component-scan>
<!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 如:http://127.0.0.1:8080/springmvc/WEB-INF/jsp/****.jsp-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"></bean>
</beans>
- controller
package com.myp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
//name 是入参 在请求 /hello?name=hello 时即可获得参数 ,可不加参数,若参数必须则可以加上注解 @requestParam 默认required=true 必须传参数,否则404错误
//model 出参 是传入给jsp的对象
@RequestMapping(value="/hello")
public String Dohello(String name,Model model){
System.out.println("running...");
model.addAttribute("hello","hello");
return "hello";//WEB-INF/jsp/hello.jsp
}
}
- hello.jsp
This is my JSP page ${hello }
- 效果