Servlet入门案例

Posted miantiao312

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Servlet入门案例相关的知识,希望对你有一定的参考价值。

一、需求:登陆页面,查询数据库是否有此人,并统计登陆的次数、显示成功登陆与否信息

1、登陆页面和登陆成功页面

login.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>
    <h1>登录页面</h1>
    <%
        /**
        * 判断request域中是否有错误信息:(第一次进入登录页面的时候,没有错误信息)
        * * 如果有错误信息:显示错误信息
        */
        String msg = "";
        if(request.getAttribute("msg") != null){
            // 有错误信息:显示错误信息:
            msg = (String)request.getAttribute("msg");
        }
    %>
    <h3><font color="red"><%= msg %></font></h3>
    <form action="/web_login/LoginServlet" method="post">
        <table border="1" width="400">
            <tr>
                <td>用户名</td>
                <td><input type="text" name="username"/></td>
            </tr>
            <tr>
                <td>密码</td>
                <td><input type="password" name="password"/></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="登录"/></td>
            </tr>
        </table>
    </form>
    </body>
    </html>

success.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>
    <h1>登录成功的页面!</h1>
    <%
        Integer count = 0;
        // 判断,如果ServletContext中有值,获取并显示:
        if(this.getServletContext().getAttribute("count")!=null){
            count = (Integer)this.getServletContext().getAttribute("count");
        }
    %>
    <h3>登录成功的总人数:<%= count %></h3>
    </body>
    </html>

2、web.xml配置

      <servlet>
        <description></description>
        <display-name>LoginServlet</display-name>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.kid.controller.LoginServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
      </servlet-mapping>

      <servlet>
        <description></description>
        <display-name>InitServlet</display-name>
        <servlet-name>InitServlet</servlet-name>
        <servlet-class>com.kid.controller.InitServlet</servlet-class>
         <!-- 配置启动时加载 -->
        <load-on-startup>2</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>InitServlet</servlet-name>
        <url-pattern>/InitServlet</url-pattern>
      </servlet-mapping>

3、代码逻辑

    A、//登陆的Servlet
    public class LoginServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            try {
                //1、接受页面请求数据
                request.setCharacterEncoding("UTF-8");
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                
                //2、封装数据
                User user=new User();
                user.setUsername(username);
                user.setPassword(password);
                
                //3、查询数据库处理数据
                UserModel userModel=new UserModel();
                User existUser=userModel.login(user);
                
                //4、判断用户
                if(existUser == null) {
                    request.setAttribute("msg", "用户名或密码错误");
                    request.getRequestDispatcher("/login.jsp").forward(request, response);
                }else {
                    int count = (Integer) this.getServletContext().getAttribute("count");
                    count++;
                    this.getServletContext().setAttribute("count", count);
                    response.sendRedirect("/web_login/success.jsp");
                }
                
            } catch (SQLException e) {
                
                e.printStackTrace();
            }
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }

    B、//初始化的servlet
    public class InitServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        /**
         * 初始化方法
         */
        @Override
        public void init() throws ServletException {
            int count=0;
            this.getServletContext().setAttribute("count", count);
        }
        
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }
    
    C、实体类
        public class User {

            private Integer uid;
            private String username;
            private String password;
            private String nickname;
            
            //getter、setter方法
        }

    D、连接数据库查询,并且处理数据
        public class UserModel {
            /**
             * 查询数据库,处理用户的登陆的方法
             * @param user
             * @return
             * @throws SQLException 
             */
            public User login(User user) throws SQLException {
                QueryRunner queryRunner=new QueryRunner(JDBCUtils.getDataSource());
                User existUser = queryRunner.query("select * from user where username = ? and password = ?",
                        new BeanHandler<User>(User.class), user.getUsername(), user.getPassword());
                return existUser;
            }
        }

    E、工具类
        public class JDBCUtils {
            private static final ComboPooledDataSource dataSource = new ComboPooledDataSource();
            
            public static Connection getConnection() throws SQLException{
                return dataSource.getConnection();
            }
        
            public static DataSource getDataSource(){
                return dataSource;
            }
        }

    F、c3p0连接池配置
        c3p0-config
        <?xml version="1.0" encoding="UTF-8"?>
        <c3p0-config>
            <default-config>
                <property name="driverClass">com.mysql.jdbc.Driver</property>
                <property name="jdbcUrl">jdbc:mysql:///web_login</property>
                <property name="user">root</property>
                <property name="password">root</property>
                
                <property name="initialPoolSize">5</property>
                <property name="minPoolSize">5</property>
                <property name="maxPoolSize">20</property>
            </default-config> 
        </c3p0-config>

4、登陆成功人数统计分析:

技术分享图片

以上是关于Servlet入门案例的主要内容,如果未能解决你的问题,请参考以下文章

Servlet简要介绍及入门案例。

Servlet入门案例

首个springmvc入门案例报错

javaweb 基于java Servlet登入 简单入门案例

完成SpringMVC的入门案例

Struts1的框架的原理,开发流程,配置与入门案例