01_SpringMVC

SpringMVC是什么
Spring web mvc和Struts2都属于表现层的框架,它是Spring框架的一部分,我们可以从Spring的整体结构中看得出来:

Spring整体架构

SpringMVC处理流程

SpringMVC处理流程

入门程序

  • 新建web项目,命名为springmvc01

  • 导入jar包
    参考:springMVC-day01\参考资料\jar包\springmvc独立运行,所有jar包如下:
    spring-jdbc-4.1.3.RELEASE.jar spring-jms-4.1.3.RELEASE.jar spring-messaging-4.1.3.RELEASE.jar spring-tx-4.1.3.RELEASE.jar spring-web-4.1.3.RELEASE.jar spring-webmvc-4.1.3.RELEASE.jar commons-logging-1.1.1.jar jstl-1.2.jar spring-aop-4.1.3.RELEASE.jar spring-aspects-4.1.3.RELEASE.jar spring-beans-4.1.3.RELEASE.jar spring-context-4.1.3.RELEASE.jar spring-context-support-4.1.3.RELEASE.jar spring-core-4.1.3.RELEASE.jar spring-expression-4.1.3.RELEASE.jar

  • 配置前端控制器,在web.xml中添加:

<!-- 配置前端控制器 -->
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 如果没有指定springMvc核心配置文件那么默认会去找/WEB-INF/+<servlet-name>中的内容 +   -servlet.xml配置文件 -->
    <!-- 指定springMvc核心配置文件位置 -->
    
    <!-- tomcat启动的时候就加载这个servlet -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
  • 启动tomcat报错
    Could not open ServletContext resource [/WEB-INF/SpringMVC-servlet.xml]
    SpringMVC就是web.xml中的<servlet-name>

  • 添加SpringMVC核心配置文件

  • web.xml中添加

<init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:SpringMvc.xml</param-value>
    </init-param>
加载自定义的SpringMVC核心文件
  • Java Resources下新建一个Source Folder命名为config
    新建config
  • config新建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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://code.alibabatech.com/schema/dubbo 
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">
        
        <!-- 配置@Controller注解扫描 -->
        <context:component-scan base-package="cn.huachao.controller"/>
        
</beans>
  • Pojo
package cn.huachao.domain;
import java.util.Date;
public class Item {
    private Integer id;
    private String name;
    private Float price;
    private String pic;
    private Date createtime;
    private String detail;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }
    public Float getPrice() {
        return price;
    }
    public void setPrice(Float price) {
        this.price = price;
    }
    public String getPic() {
        return pic;
    }
    public void setPic(String pic) {
        this.pic = pic == null ? null : pic.trim();
    }
    public Date getCreatetime() {
        return createtime;
    }
    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }
    public String getDetail() {
        return detail;
    }
    public void setDetail(String detail) {
        this.detail = detail == null ? null : detail.trim();
    }
}
  • Controller
package cn.huachao.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import cn.huachao.domain.Item;
@Controller
public class ItemController {
    @RequestMapping("/list")
    public ModelAndView  itemsList() throws Exception{
        List<Item> itemList = new ArrayList<>();
        //商品列表
        Item item_1 = new Item();
        item_1.setName("联想笔记本_3");
        item_1.setPrice(6000f);
        item_1.setDetail("ThinkPad T430 联想笔记本电脑!");
        
        Item item_2 = new Item();
        item_2.setName("苹果手机");
        item_2.setPrice(5000f);
        item_2.setDetail("iphone6苹果手机!");
        
        itemList.add(item_1);
        itemList.add(item_2);
        
        //模型和视图
        //model模型: 模型对象中存放了返回给页面的数据
        //view视图: 视图对象中指定了返回的页面的位置
        ModelAndView modelAndView = new ModelAndView();
        //将返回给页面的数据放入模型和视图对象中
        modelAndView.addObject("itemList", itemList);
        //指定返回的页面位置
        modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
        return modelAndView;
    }
    
}

配置JSP视图解析器

  • SpringMvc.xml中添加
        <!-- InternalResourceViewResolver:支持JSP视图解析 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- JstlView表示JSP模板页面需要使用JSTL标签库,所以classpath中必须包含jstl的相关jar 包。
            此属性可以不设置,默认为JstlView。 -->
            <!-- spring-webmvc-4.1.3.RELEASE.jar -->
            <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
  • ItemControllersetViewName改变
//modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
modelAndView.setViewName("itemList");

同时支持json和xml

  • 添加spring-oxm-4.1.3.RELEASE.jar的jar包
  • 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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://code.alibabatech.com/schema/dubbo 
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">
        
        <!-- 配置@Controller注解扫描 -->
        <context:component-scan base-package="cn.huachao.controller" />
        <context:annotation-config />
        
        <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
            <property name="order" value="1" />
            <!-- <property name="defaultContentType" value="text/html"/> -->
            <!-- 是否启用参数支持 ,默认是true-->
            <!-- <property name="favorPathExtension" value="true"/> -->
            
            <!-- 是否启用参数支持 ,默认是true -->
            <property name="favorParameter" value="false"/>
            <!-- 是否忽略掉accept header ,默认是false -->
            <property name="ignoreAcceptHeader" value="true"/>
            
            <property name="mediaTypes">
                <map>
                    <entry key="json" value="application/json"/>
                    <entry key="xml" value="application/xml"/>
                </map>
            </property>
            
            <property name="defaultViews">
                <list>
                    <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"></bean>
                    <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                        <constructor-arg>
                            <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
                                 <property name="classesToBeBound">
                                    <list>
                                       <value>cn.huachao.domain.User</value>
                                       <!-- <value>cn.huachao.domain.Item</value> -->
                                    </list>
                                 </property>
                            </bean>
                        </constructor-arg>
                    </bean>
                </list>
            </property>
        </bean>
        
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="order" value="2" />
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
            <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        </bean>
        
</beans>
  • User实例
package cn.huachao.domain;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class User {
   
    private long userID;
    private String userName;
    private Date birth;
 
    public String getUserName() {
       return userName;
    }
    public void setUserName(String userName) {
       this.userName = userName;
    }
    public Date getBirth() {
       return birth;
    }
    public void setBirth(Date birth) {
       this.birth = birth;
    }
    public long getUserID() {
       return userID;
    }
    public void setUserID(long userID) {
       this.userID = userID;
    }
}
  • Controller
    @RequestMapping(value="/user/{userid}" , method={RequestMethod.GET})
    public String queryUser(@PathVariable("userid")long userID , ModelMap model){
        User u = new User();
        u.setUserID(userID);
        u.setUserName("zhaoyang");
        model.addAttribute("User", u);
        //mv.setViewName("itemList");
        return "User";
    }
  • /WEB-INF/jsp/User.jsp
<body>
    UserName: ${requestScope.User.userID } <br />
    Age: ${requestScope.User.userName }
</body>

SpringMVC架构

参考:
SpringMVC原理教程和搭建实例

下一篇

02-SpringMVC

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,544评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,430评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,764评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,193评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,216评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,182评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,063评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,917评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,329评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,543评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,722评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,425评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,019评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,671评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,825评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,729评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,614评论 2 353

推荐阅读更多精彩内容