寫一個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就搭建完成。
我的搭建的,若是有問題歡迎指正。