为java_web项目添加spring_MVC框架(JSTL表达式)

阅读更多
为java web项目添加spring MVC框架
今天花了点时间将之前整理的spring MVC项目的搭建做了下笔记,也把之前的做的个Demo一起放上来,给学习spring MVC框架的朋友一个引导吧!接下来我们就开始吧:

1. 添加spring类库(如下图所示):


在这里我们添加了Spring 2.5 Core Libraries、Spring 2.5 AOP Libraries和Spring 2.5 Web Libraries 三个类库。

2. 在WEB-INF下创建applicationContext.xml文件,内容大致如下:

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">




3. 在WEB-INF下创建springMVCTemplet-servlet.xml文件(其中springMVCTemplet为你项目的名称),内容大致如下:

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">


class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/" p:suffix=".jsp"
p:viewClass="org.springframework.web.servlet.view.JstlView" />








4. 接下来需要在web.xml中进行相应的配置,配置如下:

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">


contextConfigLocation

/WEB-INF/applicationContext.xml





springMVCTemplet

org.springframework.web.servlet.DispatcherServlet

0


springMVCTemplet
*.htm




org.springframework.web.context.ContextLoaderListener



 
    index.jsp
 



在web.xml中,我们告诉容器需要加载applicationContext.xml配置文件;对spring MVC 也进行了相应的配置,其中URL以.htm为后缀的请求将交由DispatcherServlet 进行处理,DispatcherServlet会将请求分发给相应的控制器进行处理;同时增加spring的监听器。


到这里spring MVC项目已经搭建完成,接下来我们进行一个简单的测试。

在src目录下创建包:com.lym.control
创建类IndexController,代码如下:
package com.lym.control;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {

@RequestMapping("/index.htm")
public ModelMap index(HttpServletRequest request,
HttpServletResponse response)throws Exception{
ModelMap model = new ModelMap();
model.addAttribute("hello", "hello Word!");
return model;
}
}

当我们通过浏览器访问/index.htm时,IndexController类的index方法将接受处理请求,这里我们只是简单的往request属性中添加hello属性,让对应的jsp页面可以获取到该属性。

在index.jsp上引入jstl,然后使用${hello}将hello属性值显示出来。

例子参见:springMVCTemplet.rar (导入MyEclipse部署到tomcat运行)

  • 为java_web项目添加spring_MVC框架_JSTL表达式_.rar (55.4 KB)
  • 下载次数: 161

你可能感兴趣的:(spring,mvc,框架,web,java)