hooyantsing's Blog

第71次课程_Servlet基础

字数统计: 1.4k阅读时长: 7 min
2019/10/26

源辰76班

第71次课程

2019.10.26

内容

Servlet基础[廖彦]

1.创建servlet文件

ce7b38a03c82d6cc5a4cafa6d0c83b63.png

标准servlet模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.yc.damai.servlet;

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;

//servlet文件地址路径
@WebServlet("/Demo.s")
public class Demo extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    //服务器应对Get请求
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //=== more code ===
    }

    //服务器应对Post请求
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

2.两种配置方式

旧:

通过web.xml配置

在web.xml中加入如下代码

1
2
3
4
5
6
7
8
<servlet>
    <servlet-name>hello world  servlet</servlet-name>
     <servlet-class>com.yc.damai.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>hello world  servlet</servlet-name>
    <url-pattern>/hello.s</url-pattern>
</servlet-mapping>

新:

直接在servlet文件中配置

1
2
@WebServlet("/Demo.s")
public class ...

3.将后端jsp执行的代码放入servlet

例如:dologin.jsp -> dologin.s

dologin.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<%@ page import="java.util.*"%>
<%@ page  import="com.yc.damai.util.DBHelper"%>
<%@ page language="java"  contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%
    // 设置请求对象的字符集编码,可以兼容中文参数,避免乱码问题
    request.setCharacterEncoding("utf-8");
    // 接收 用户名 和 密码
    String username =  request.getParameter("username");
    String password =  request.getParameter("password");
    String sql = "select * from user where  username=? and password=?";
    Map<String, Object> user =  DBHelper.selectOne(sql, username, password);
    if (user != null) {
       session.setAttribute("loginedUser",  user);
       response.sendRedirect("index.jsp");
    } else {
       request.setAttribute("msg", "用户名或密码错误!");
       request.getRequestDispatcher("login.jsp").forward(request, response);
    }
%>

dologin.s

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.yc.damai.servlet;

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;

//servlet文件地址路径
@WebServlet("/dologin.s")
public class Demo extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    //服务器应对Get请求
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求对象的字符集编码,可以兼容中文参数,避免乱码问题
        request.setCharacterEncoding("utf-8");
        // 接收 用户名 和 密码
        String username =  request.getParameter("username");
        String password =  request.getParameter("password");
        String sql = "select * from user where  username=? and password=?";
        Map<String, Object> user =  DBHelper.selectOne(sql, username, password);
        if (user != null) {
           session.setAttribute("loginedUser",  user);
           response.sendRedirect("index.jsp");
        } else {
           request.setAttribute("msg", "用户名或密码错误!");
           request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    //服务器应对Post请求
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

4.案例

为大麦(damai)项目的登录页面(login.jsp)加入分时限制登陆的功能。

web.xml

提前设置好参数,servlet可以通过(路径).etInitParameter(“参数名”)方法直接获取。

加入如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<servlet>
    <servlet-name>登录的servlet</servlet-name>
     <servlet-class>com.yc.damai.servlet.LoginServlet</servlet-class>
    <init-param>
      <param-name>begin-time</param-name>
      <param-value>8</param-value>
    </init-param>
    <init-param>
      <param-name>end-time</param-name>
      <param-value>22</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>登录的servlet</servlet-name>
     <url-pattern>/LoginServlet.s</url-pattern>
</servlet-mapping>

LoginServlet.s

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.yc.damai.servlet;

import java.io.IOException;
import java.util.Map;

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

import com.yc.damai.util.DBHelper;

/**
* Servlet 的参数配置
*
*
*    Servlet 提供的 getInitParameter() 获取配置参数方法
*
*    用户只能在  8 ~ 22 点之间登录系统   企业项目   12306
*
*    设置一个时间 参数,限制用户的登录
*
*
*    The servlets named [登录的servlet] and
*    [com.yc.damai.servlet.LoginServlet] are both mapped to
*    the url-pattern [/dologin.s] which is not permitted
*
*    1、以注解方式定义的Servlet 名字默认为类路径
*    2、注解配置单的 Servlet 和 web.xml配置的Servlet 可以共存
*    3、所有的servlet 的路径必须 全局唯一
*
*/

// @WebServlet("/dologin1.s") // 替换成 web.xml配置
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        String beginTimeParam = this.getInitParameter("begin-time");
        String endTimeParam = this.getInitParameter("end-time");
        
        int beginTime = Integer.parseInt(beginTimeParam);
        int endTime = Integer.parseInt(endTimeParam);
        
        // 获取当前时间 小时
        java.util.Calendar c = java.util.Calendar.getInstance();
        int hour = c.get(java.util.Calendar.HOUR_OF_DAY);
        
        if(hour < beginTime || hour > endTime){
            request.setAttribute("msg", "没上班!");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }
        
        // 设置请求对象的字符集编码,可以兼容中文参数,避免乱码问题
        request.setCharacterEncoding("utf-8");
        // 接收 用户名 和 密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        String sql = "select * from user where username=? and password=?";
        Map<String, Object> user = DBHelper.selectOne(sql, username, password);

        if (user != null) {
            HttpSession session = request.getSession();
            session.setAttribute("loginedUser", user);
            response.sendRedirect("index.jsp");
        } else {
            request.setAttribute("msg", "用户名或密码错误!");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 绝大多数请求下, get 请求和 post 执行的业务逻辑是一致的
        doGet(request, response);  // 必须有
        
        //doXXX 方法中的 super。。。 必须删除
        // 父类 的 doPost 只有一行代码   throw new ServletException(405,"HTTP method POST is not supported by this URL");
        //super.doPost(request, response);
        
    }
}

servlet实现登出功能

原理:销毁会话对象(invalidate方法)

LogoutServlet.s

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.yc.damai.servlet;

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;

@WebServlet("/logout.s")
public class LogoutServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 销毁会话对象
        request.getSession().invalidate();
        // 跳转主页
        response.sendRedirect("index.jsp");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
CATALOG