技术文章分类(180)

技术随笔(11)

servlet跟JSP交互数据

代码运行环境在jdk1.7以上,servlet3.0,所以不用配置web.xml

一下有简单的三种交互数据的方式

servlet:

package com.test;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServletDemo2
 */
@WebServlet("/ServletDemo2")
public class ServletDemo2 extends HttpServlet {       

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        
        String data = "数据";
        this.getServletContext().setAttribute("data", data);
        RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/Demo2.jsp");
        rd.forward(request, response);
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

 

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>
    
    <article style="color:red;">
        <%
            String data1 = (String)this.getServletContext().getAttribute("data");
            out.write(data1);
        %>
    </article>
    <div style="color:blue;">
        <%
            String data2 = (String)application.getAttribute("data");
            out.write(data2);
        %>
    </div>
    <div style="color:green;">${data}</div>
</body>
</html>

 

posted @ 2014-06-02 14:21  坤哥MartinLi  阅读(231)  评论(0编辑  收藏  举报