• 吴裕雄--天生自然轻量级JAVA EE企业应用开发Struts2Sping4Hibernate整合开发学习笔记:Servlet介绍


    drop database if exists liuyan;
    create database liuyan;
    
    use liuyan;
    
    create table user_inf
    (
        id int auto_increment primary key,
        name varchar(255),
        pass varchar(255)
    );
    
    insert into user_inf
    values(null,'crazyit','123');
    insert into user_inf
    values(null,'tiger','123');
    <%--
    网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
    author  yeeku.H.lee kongyeeku@163.com
    version  1.0
    Copyright (C), 2001-2016, yeeku.H.Lee
    This program is protected by copyright laws.
    Program Name:
    Date: 
    --%>
    
    <%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
    <!DOCtype html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title> 收集参数的表单页 </title>
        <meta name="website" content="http://www.crazyit.org" />
    </head>
    <body>
    <form id="form1" method="post" action="aa">
    用户名:<br/>
    <input type="text" name="name"><hr/>
    性别:<br/>
    男:<input type="radio" name="gender" value="男">
    女:<input type="radio" name="gender" value="女"><hr/>
    喜欢的颜色:<br/>
    红:<input type="checkbox" name="color" value="红">
    绿:<input type="checkbox" name="color" value="绿">
    蓝:<input type="checkbox" name="color" value="蓝"><hr/>
    来自的国家:<br/>
    <select name="country">
        <option value="中国">中国</option>
        <option value="美国">美国</option>
        <option value="俄罗斯">俄罗斯</option>
    </select><hr/>
    <input type="submit" value="提交">
    <input type="reset" value="重置">
    </form>
    </body>
    </html>
    <%--
    网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
    author  yeeku.H.lee kongyeeku@163.com
    version  1.0
    Copyright (C), 2001-2016, yeeku.H.Lee
    This program is protected by copyright laws.
    Program Name:
    Date: 
    --%>
    
    <%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title> 用户登录 </title>
        <meta name="website" content="http://www.crazyit.org" />
    </head>
    <body>
    <!-- 输出出错提示 -->
    <span style="color:red;font-weight:bold">
    <%
    if (request.getAttribute("err") != null)
    {
        out.println(request.getAttribute("err") + "<br/>");
    }
    %>
    </span>
    请输入用户名和密码:
    <!-- 登录表单,该表单提交到一个Servlet -->
    <form id="login" method="post" action="login">
    用户名:<input type="text" name="username"/><br/>&nbsp;&nbsp码:<input type="password" name="pass"/><br/>
    <input type="submit" value="登录"/><br/>
    </form>
    </body>
    </html>
    <%--
    网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
    author  yeeku.H.lee kongyeeku@163.com
    version  1.0
    Copyright (C), 2001-2016, yeeku.H.Lee
    This program is protected by copyright laws.
    Program Name:
    Date: 
    --%>
    
    <%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title> 欢迎页面 </title>
        <meta name="website" content="http://www.crazyit.org" />
    </head>
    <body>
    <h3>欢迎登录</h3>
    <%=session.getAttribute("name")%>,欢迎登录!
    </body>
    </html>
    <?xml version="1.0" encoding="GBK"?>
    <!-- 定义生成文件的project根元素,默认的target为空 -->
    <project name="web" basedir="." default="">
        <!-- 定义三个简单属性 -->
        <property name="src" value="src"/>
        <property name="classes" value="classes"/>
        <!-- 定义一组文件和目录集 -->
        <path id="classpath">
            <fileset dir="lib">
                <include name="*.jar"/>
            </fileset>
            <pathelement path="${classes}"/>
        </path>
        <!-- 定义compile target,用于编译Java源文件 -->
        <target name="compile" description="编译Java源文件">
            <!-- 先删除classes属性所代表的文件夹 -->
            <delete dir="${classes}"/>
            <!-- 创建classes属性所代表的文件夹 -->
            <mkdir dir="${classes}"/>
            <!-- 编译Java文件,编译后的class文件放到classes属性所代表的文件夹内 -->
            <javac destdir="${classes}" debug="true" includeantruntime="yes"
                deprecation="false" optimize="false" failonerror="true">
                <!-- 指定需要编译的Java文件所在的位置 -->
                <src path="${src}"/>
                <!-- 指定编译Java文件所需要第三方类库所在的位置 -->
                <classpath refid="classpath"/>
            </javac>
        </target>
    </project>
    <?xml version="1.0" encoding="GBK"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
        http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
        version="3.1">
    
        <!-- 配置Servlet的名字 -->
        <servlet>
            <!-- 指定Servlet的名字,
                相当于指定@WebServlet的name属性 -->
            <servlet-name>firstServlet</servlet-name>
            <!-- 指定Servlet的实现类 -->
            <servlet-class>lee.FirstServlet</servlet-class>
        </servlet>
        <!-- 配置Servlet的URL -->
        <servlet-mapping>
            <!-- 指定Servlet的名字 -->
            <servlet-name>firstServlet</servlet-name>
            <!-- 指定Servlet映射的URL地址,
                相当于指定@WebServlet的urlPatterns属性-->
            <url-pattern>/aa</url-pattern>
        </servlet-mapping>
    
        <servlet>
            <!-- Servlet名 -->
            <servlet-name>timerServlet</servlet-name>
            <!-- Servlet的实现类 -->
            <servlet-class>lee.TimerServlet</servlet-class>
            <!-- 配置应用启动时,创建Servlet实例
                ,相当于指定@WebServlet的loadOnStartup属性-->
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <servlet>
            <!-- 配置Servlet名 -->
            <servlet-name>testServlet</servlet-name>
            <!-- 指定Servlet的实现类 -->
            <servlet-class>lee.TestServlet</servlet-class>
            <!-- 配置Servlet的初始化参数:driver -->
            <init-param>
                <param-name>driver</param-name>
                <param-value>com.mysql.jdbc.Driver</param-value>
            </init-param>
            <!-- 配置Servlet的初始化参数:url -->
            <init-param>
                <param-name>url</param-name>
                <param-value>jdbc:mysql://localhost:3306/javaee</param-value>
            </init-param>
            <!-- 配置Servlet的初始化参数:user -->
            <init-param>
                <param-name>user</param-name>
                <param-value>root</param-value>
            </init-param>
            <!-- 配置Servlet的初始化参数:pass -->
            <init-param>
                <param-name>pass</param-name>
                <param-value>32147</param-value>
            </init-param>
        </servlet>
        <servlet-mapping>
            <!-- 确定Servlet名 -->
            <servlet-name>testServlet</servlet-name>
            <!-- 配置Servlet映射的URL -->
            <url-pattern>/testServlet</url-pattern>
        </servlet-mapping>
    
    </web-app>
    package lee;
    
    import java.sql.*;
    
    /**
     * Description:
     * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
     * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
     * <br/>This program is protected by copyright laws.
     * <br/>Program Name:
     * <br/>Date:
     * @author  Yeeku.H.Lee kongyeeku@163.com
     * @version  1.0
     */
    public class DbDao
    {
        private Connection conn;
        private String driver;
        private String url;
        private String username;
        private String pass;
        public DbDao()
        {
        }
        public DbDao(String driver , String url
            , String username , String pass)
        {
            this.driver = driver;
            this.url = url;
            this.username = username;
            this.pass = pass;
        }
        // 下面是各个成员属性的setter和getter方法
        public void setDriver(String driver) {
            this.driver = driver;
        }
        public void setUrl(String url) {
            this.url = url;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public void setPass(String pass) {
            this.pass = pass;
        }
        public String getDriver() {
            return (this.driver);
        }
        public String getUrl() {
            return (this.url);
        }
        public String getUsername() {
            return (this.username);
        }
        public String getPass() {
            return (this.pass);
        }
        // 获取数据库连接
        public Connection getConnection() throws Exception
        {
            if (conn == null)
            {
                Class.forName(this.driver);
                conn = DriverManager.getConnection(url,username,
                    this. pass);
            }
            return conn;
        }
        // 插入记录
        public boolean insert(String sql , Object... args)
            throws Exception
        {
            PreparedStatement pstmt = getConnection().prepareStatement(sql);
            for (int i = 0; i < args.length ; i++ )
            {
                pstmt.setObject( i + 1 , args[i]);
            }
            if (pstmt.executeUpdate() != 1)
            {
                return false;
            }
            pstmt.close();
            return true;
        }
        // 执行查询
        public ResultSet query(String sql , Object... args)
            throws Exception
        {
            PreparedStatement pstmt = getConnection().prepareStatement(sql);
            for (int i = 0; i < args.length ; i++ )
            {
                pstmt.setObject( i + 1 , args[i]);
            }
            return pstmt.executeQuery();
        }
        // 执行修改
        public void modify(String sql , Object... args)
            throws Exception
        {
            PreparedStatement pstmt = getConnection().prepareStatement(sql);
            for (int i = 0; i < args.length ; i++ )
            {
                pstmt.setObject( i + 1 , args[i]);
            }
            pstmt.executeUpdate();
            pstmt.close();
        }
        // 关闭数据库连接的方法
        public void closeConn()
            throws Exception
        {
            if (conn != null && !conn.isClosed())
            {
                conn.close();
            }
        }
    }
    package lee;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    
    import java.io.*;
    
    /**
     * Description:
     * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
     * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
     * <br/>This program is protected by copyright laws.
     * <br/>Program Name:
     * <br/>Date:
     * @author  Yeeku.H.Lee kongyeeku@163.com
     * @version  1.0
     */
    // Servlet必须继承HttpServlet类
    @WebServlet(name="firstServlet"
        , urlPatterns={"/firstServlet"})
    public class FirstServlet extends HttpServlet
    {
        // 客户端的响应方法,使用该方法可以响应客户端所有类型的请求
        public void service(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException,java.io.IOException
        {
            // 设置解码方式
            request.setCharacterEncoding("GBK");
            response.setContentType("text/html;charSet=GBK");
            // 获取name的请求参数值
            String name = request.getParameter("name");
            // 获取gender的请求参数值
            String gender = request.getParameter("gender");
            // 获取color的请求参数值
            String[] color = request.getParameterValues("color");
            // 获取country的请求参数值
            String national = request.getParameter("country");
            // 获取页面输出流
            PrintStream out = new PrintStream(response.getOutputStream());
            //输出HTML页面标签
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet测试</title>");
            out.println("</head>");
            out.println("<body>");
            // 输出请求参数的值:name
            out.println("您的名字:" + name + "<hr/>");
            // 输出请求参数的值:gender
            out.println("您的性别:" + gender + "<hr/>");
            // 输出请求参数的值:color
            out.println("您喜欢的颜色:");
            for(String c : color)
            {
                out.println(c + " ");
            }
            out.println("<hr/>");
            out.println("您喜欢的颜色:");
            // 输出请求参数的值:national
            out.println("您来自的国家:" + national + "<hr/>");
            out.println("</body>");
            out.println("</html>");
        }
    }
    package lee;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    
    import java.io.PrintWriter;
    import java.io.IOException;
    
    import java.sql.*;
    
    /**
     * Description:
     * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
     * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
     * <br/>This program is protected by copyright laws.
     * <br/>Program Name:
     * <br/>Date:
     * @author  Yeeku.H.Lee kongyeeku@163.com
     * @version  1.0
     */
    @WebServlet(name="login"
        , urlPatterns={"/login"})
    public class LoginServlet extends HttpServlet
    {
        // 响应客户端请求的方法
        public void service(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException,java.io.IOException
        {
            String errMsg = "";
            // Servlet本身并不输出响应到客户端,因此必须将请求转发到视图页面
            RequestDispatcher rd;
            // 获取请求参数
            String username = request.getParameter("username");
            String pass = request.getParameter("pass");
            try
            {
                // Servlet本身并不执行任何的业务逻辑处理,它调用JavaBean处理用户请求
                DbDao dd = new DbDao("com.mysql.jdbc.Driver",
                    "jdbc:mysql://localhost:3306/liuyan","root","32147");
                // 查询结果集
                ResultSet rs = dd.query("select pass from user_inf"
                    + " where name = ?", username);
                if (rs.next())
                {
                    // 用户名和密码匹配
                    if (rs.getString("pass").equals(pass))
                    {
                        // 获取session对象
                        HttpSession session = request.getSession(true);
                        // 设置session属性,跟踪用户会话状态
                        session.setAttribute("name" , username);
                        // 获取转发对象
                        rd = request.getRequestDispatcher("/welcome.jsp");
                        // 转发请求
                        rd.forward(request,response);
                    }
                    else
                    {
                        // 用户名和密码不匹配时
                        errMsg += "您的用户名密码不符合,请重新输入";
                    }
                }
                else
                {
                    // 用户名不存在时
                    errMsg += "您的用户名不存在,请先注册";
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            // 如果出错,转发到重新登录
            if (errMsg != null && !errMsg.equals(""))
            {
                rd = request.getRequestDispatcher("/login.jsp");
                request.setAttribute("err" , errMsg);
                rd.forward(request,response);
            }
        }
    }
    package lee;
    
    import java.sql.*;
    
    import javax.servlet.http.*;
    import javax.servlet.*;
    import javax.servlet.annotation.*;
    import java.io.*;
    
    /**
     * Description:
     * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
     * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
     * <br/>This program is protected by copyright laws.
     * <br/>Program Name:
     * <br/>Date:
     * @author  Yeeku.H.Lee kongyeeku@163.com
     * @version  1.0
     */
    @WebServlet(name="testServlet"
        , urlPatterns={"/testServlet"}
        , initParams={
            @WebInitParam(name="driver", value="com.mysql.jdbc.Driver"),
            @WebInitParam(name="url", value="jdbc:mysql://localhost:3306/javaee"),
            @WebInitParam(name="user", value="root"),
            @WebInitParam(name="pass", value="32147")})
    public class TestServlet extends HttpServlet
    {
        // 重写init方法
        public void init(ServletConfig config)
            throws ServletException
        {
            // 重写该方法,应该首先调用父类的init()方法
            super.init(config);
        }
        // 响应客户端请求的方法
        public void service(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException,java.io.IOException
        {
            try
            {
                // 获取ServletConfig对象
                ServletConfig config = getServletConfig();
                // 通过ServletConfig对象获取配置参数:dirver
                String driver = config.getInitParameter("driver");
                // 通过ServletConfig对象获取配置参数:url
                String url = config.getInitParameter("url");
                // 通过ServletConfig对象获取配置参数:user
                String user = config.getInitParameter("user");
                // 通过ServletConfig对象获取配置参数:pass
                String pass = config.getInitParameter("pass");
                // 注册驱动
                Class.forName(driver);
                // 获取数据库连接
                Connection conn = DriverManager.getConnection(url,user,pass);
                // 创建Statement对象
                Statement stmt = conn.createStatement();
                // 执行查询,获取ResuletSet对象
                ResultSet rs = stmt.executeQuery("select * from news_inf");
                response.setContentType("text/html;charSet=gbk");
                // 获取页面输出流
                PrintStream out = new PrintStream(response.getOutputStream());
                // 输出HTML标签
                out.println("<html>");
                out.println("<head>");
                out.println("<title>访问Servlet初始化参数测试</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<table bgcolor="#9999dd" border="1"" +
                    "width="480">");
                // 遍历结果集
                while(rs.next())
                {
                    // 输出结果集内容
                    out.println("<tr>");
                    out.println("<td>" + rs.getString(1) + "</td>");
                    out.println("<td>" + rs.getString(2) + "</td>");
                    out.println("</tr>");
                }
                out.println("</table>");
                out.println("</body>");
                out.println("</html>");
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    package lee;
    
    import javax.servlet.http.*;
    import javax.servlet.*;
    import javax.servlet.annotation.*;
    
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.Date;
    
    /**
     * Description:
     * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
     * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
     * <br/>This program is protected by copyright laws.
     * <br/>Program Name:
     * <br/>Date:
     * @author  Yeeku.H.Lee kongyeeku@163.com
     * @version  1.0
     */
    
    @WebServlet(loadOnStartup=1)
    public class TimerServlet extends HttpServlet
    {
        public void init(ServletConfig config)throws ServletException
        {
            super.init(config);
            Timer t = new Timer(1000,new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    System.out.println(new Date());
                }
            });
            t.start();
        }
    }
  • 相关阅读:
    希腊字母写法
    The ASP.NET MVC request processing line
    lambda aggregation
    UVA 10763 Foreign Exchange
    UVA 10624 Super Number
    UVA 10041 Vito's Family
    UVA 10340 All in All
    UVA 10026 Shoemaker's Problem
    HDU 3683 Gomoku
    UVA 11210 Chinese Mahjong
  • 原文地址:https://www.cnblogs.com/tszr/p/12363963.html
Copyright © 2020-2023  润新知