xdxxdx
www.xdxxdxxdx.com

 

spirng mvc是一个mvc框架,与struts2类似,都是基于Servlet封装而成的框架,所以要了解spring mvc或者struts2比需先了解Servlet,本篇我们先把spring mvc集成进来,做一个简单的demo。

1.在com.m_gecko.controller包下新建一个java类,命名为GeckoController。

既然是Servlet,我们首先关心的一个问题是,如何传参,即如何取到从浏览器端发送过来的参数。先看如下代码:

package com.m_gecko.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class GeckoController {
    @RequestMapping("/getReq")
    public ModelAndView getReq(HttpServletRequest req){
        String gecko=req.getParameter("gecko");
        System.out.println(gecko);
        return null;
    }

}

运行之后在浏览器端输入:http://192.168.1.185:8080/m_gecko/getReq?gecko=豹纹守宫

关于annotation注解的相关知识这里就不做讲解,可以看到我们直接在这个方法的参数列表中填入了HttpServletRequest参数,在方法中就可以直接使用,可以猜测这个参数的实参是由框架传递过来的。

运行结果如下

第二个问题我们需要关心的是,如何把响应到浏览器端,作如下验证。

@RequestMapping("/setRes")
    public ModelAndView setRes(HttpServletResponse res){
        String str="这是一个响应,我要将它打印在浏览器上";
        PrintWriter writer=null;
        try {
            writer=res.getWriter();
            writer.print(str);
            writer.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if (writer != null)
                writer.close();
        }
        return null;
    }

我的本意是将"这是一个响应,我要将它打印在浏览器上"当成浏览器响应,展示在网页上。但是运行的结果是:

 加入一行代码    res.setHeader("Content-type", "text/html;charset=UTF-8");得到我们想要的效果。

2.新建一个jsp页面,在web-inf下新建一个名为jsp的文件夹,在jsp文件夹下再建一个gecko的文件夹,然后新建一个goPage.jsp页面,页面代码如下。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    这是第一个jsp页面
    <br>
    <h1>${geckoName}</h1>
</body>
</html>

再编写一个新的controller方法,如下。

    @RequestMapping("/goPage")
    public ModelAndView goPage(String geckoName){
        ModelAndView mv=new ModelAndView();
        mv.getModel().put("geckoName", geckoName);
        mv.setViewName("gecko/GoPage");
        return mv;
    }

这里注意 mv.getModel().put("geckoName", geckoName);这句代码,它相当于Servlet中的request.setAttribute("geckoName", geckoName);在一个request中传递共享参数。而该方法的形参直接传递了一个String类型的参数,相当于Servlet中request.getParameter("geckoName")。可以发现spring mvc为我们封装得很好。而且因为一个方法对应一个请求,而请求中的数据都通过形参传递过来,不像struts2的有些数据是当成类的成员变量存在的,不同请求如果共用一个action对象,则有可能会出现线程安全的问题,所以struts2采用每一个请求实例化一个新的action对象来解决这个问题。这也势必对内存回收造成影响。

spring mvc只会产生一个controller类的实例对象,每次请求对应于该对象的一个方法,因为方法中的变量属于局部变量,所以不会出现共享的问题。

在浏览器输入http://192.168.1.185:8080/m_gecko/goPage?geckoName=恶魔白酒

显示结果如下:

 

 3.以上只是spring mvc的一些最基本的操作,接下来我们做一个功能,就是显示t_gecko表中的数据。

  1)首先我们需要引入service类,加入如下代码:

 

    @Resource(name="geckoService")
    private GeckoService geckoService;

 

2)创建geckoList方法

代码如下:

 

@RequestMapping("geckoList")
    public ModelAndView geckoList() throws Exception{
        ModelAndView mv=new ModelAndView();
        List<TGecko>geckoList=geckoService.getGeckoList();
        mv.getModel().put("geckoList", geckoList);
        mv.setViewName("gecko/GeckoList");
        return mv;
    }

 

编写jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>守宫列表</title>
</head>
<body>
    <table>
        <tr>
            <td>编号</td>
            <td>名称</td>
            <td>创建时间</td>
        </tr>
        <c:choose>
            <c:when test="${not empty geckoList }">
                <c:forEach items="${geckoList }" var="gecko" varStatus="vs">
                    <tr>
                        <td>${gecko.geckoId}</td>
                        <td>${gecko.geckoName}</td>
                        <td><fmt:formatDate type="both" dateStyle="medium"
                                timeStyle="medium" value="${gecko.createTime}" /></td>
                    </tr>
                </c:forEach>
            </c:when>
            <c:otherwise>
            没有相关数据
            </c:otherwise>
        </c:choose>

    </table>

</body>
</html>

此处用到了jstl的相关知识,需要在maven配置文件中引入以下包。

    <!-- jsp标签 -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.servlet</groupId>
                    <artifactId>servlet-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.servlet.jsp</groupId>
                    <artifactId>jsp-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>jstl-impl</artifactId>
            <version>1.2</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.servlet</groupId>
                    <artifactId>servlet-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.servlet.jsp</groupId>
                    <artifactId>jsp-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.servlet.jsp.jstl</groupId>
                    <artifactId>jstl-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

在这边我被坑了很久,起因是引入包之后一直提示The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application这个错误,网上找了半天,用尽各种方法也没有奏效。

最后把build path中的server改成tomcat7,才解决问题。

于是猜测可能是tomcat8中的某些jar包版本太高,导致无法适配jstl的包,然后我又重新更改成tomcat8运行,神奇的发现可以运行了。这里我至今没搞懂。

结果如下:

 

 下一篇文章我们做一下提交表单,修改数据,结合spring mvc完成一个简单的增删改查demo.

 

posted on 2017-05-27 16:44  xdxxdx  阅读(437)  评论(0编辑  收藏  举报