写一个spring mvc后台传值到前台的一个小例子。web
分为如下几个步骤:spring
1.建立web项目。express
导入项目包。具体有以下:mvc
2.配置web.xml文件,配置servletapp
<servlet>
<servlet-name>helloSpring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>jsp
<!--<init-param>这个参数是为了加载下一步配置的spring配置文件的 ,默认spring mvc的加载是将spring配置文件放在web-inf下并且名称是web.xml配置的该 servlet名字-servlet.xml 会在启动时自动去改路径寻找该配置文件,咱们这里将它放在了src下去加载-->ui
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:helloSpring-servlet.xml</param-value>
</init-param>url
<!--在项目启动时加载配置文件-->
<load-on-startup>1</load-on-startup>spa
</servlet>component
<servlet-mapping>
<servlet-name>helloSpring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
3.添加spring配置文件并进行配置。
个人spring配置文件叫helloSpring-servlet.xml,放在src下。
在<beans></beans>元素里添加以下内容:
<!-- 配置自动扫描包路径,此处采用注解方式 -->
<context:component-scan base-package="com.demo"></context:component-scan>
<!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 ,会在web-inf/views/下找到你返回的页面名字.jsp-->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
4.编写逻辑代码:在src下建立com.demo.controller包
编写类MySpringController。具体代码以下:
package com.demo;
import org.omg.CORBA.Request;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller//注解,配置扫描到controller
public class MySpringController {
//方法
@RequestMapping(value="/hello",method=RequestMethod.GET)//访问请求的路径,value值是hello
//该方法须要一个ModelMap,它会存储信息,这将hello springMVC字符串放到message里
public String helloWorld(ModelMap map){
map.addAttribute("message","hello springMVC");
//返回一个string hello,会在配置文件中的前缀后缀进行结合,就至关于跳转到web-inf/views/hello.jsp
return "hello";
}
}
----------------------这个方法也能够这么写
@RequestMapping(value="/hello",method=RequestMethod.GET)
public ModelAndView helloWorld()
{
ModelAndView modelAndView=new ModelAndView("hello");//ModelAndView跳转的页面
modelAndView.addObject("message","hello springMVC");//添加到request域存放数据
return modelAndView;
}
5.去web-inf建立views文件夹,在views文件夹下建立hello.jsp
在jsp页面用el表达式就能够取到数值
<body>
${message } <br>
<!--若是没有取到值能够用${requestScope.message}取值,由于它默认存放到request域中-->
</body>
6.访问http://localhost:8080/项目名/hello会跳转到hello.jsp显示数据。
至此一个简单的spring mvc就搭建完成。
我的搭建的,若是有问题欢迎指正。