the5fire

关注Python、Django、Vim、Linux、Web开发、团队管理和互联网--Life is short, we need Python.


JSP Servlet简单实现

作者:the5fire | 标签:     | 发布:2010-12-29 11:13 a.m. | 阅读量: 9023, 8797

Jsp和Servlet个人感觉使用起来没有太大区别的,查了一下,说是jsp是Servlet的简化。这说明其本质是一样的,这里简单实现一下jsp和Servlet交互,比较简单,就不多说了,看代码吧。

在src中添加Servlet:

.. code:: java

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class TestServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String strRequest = request.getParameter("test");

        if (strRequest != null) {
            if ("T".equals(strRequest.trim())) {
                request.setAttribute("result11", "你输入的是T,代表正确");

            } else if ("F".equals(strRequest.trim())) {
                request.setAttribute("result11", "你输入的是F,代表错误");
            }
        }

        //转发
        request.getRequestDispatcher("/test.jsp").forward(request, response);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        this.doGet(req, resp);
    }

}

在WebContent下添加jsp页面test.jsp:

.. code:: html

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%
    String strResult = (String)request.getAttribute("result11");
    if (strResult != null) {
        out.println(strResult);
    }
%>
<!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=GB18030">
<title>Insert title here</title>
</head>
<body>
    <form action="TestServlet">
        <input type="text" id="test" name="test">
        <input type="submit" value="提交">
    </form>
</body>
</html>

在WEB-INF下配置web.xml文件:

::

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <servlet>
        <servlet-name>TestServlet</servlet-name>
        <servlet-class>TestServlet</servlet-class>
        <load-on-startup>5</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>/TestServlet</url-pattern>
    </servlet-mapping>

</web-app>
- from the5fire.com
----EOF-----

微信公众号:Python程序员杂谈


其他分类: