servlet应用

1.建立用户表

  在这里,我们使用mysql建立登录用户表,如下图所示:

 

 2.编写一个servlet进行用户名和密码校验,获取登录页面的用户名密码,并显示出来

首先,我们需要新建一个web application项目:

 

 点击下一步按钮弹出新的窗口,在窗口中设置项目的名称和位置:

 

 创建完项目后,我们需要配置tomcat服务器,点击图中的编辑结构按钮:

 

 然后弹出运行/调试配置窗口,在左侧栏中找到tomcat,并点击其中的Local按钮:

 

 但是,由于之前的idea中打了汉化包的原因,导致这里的Local无法点击,查阅资料需要卸载汉化包,但是在这里卸载汉化包之后打开idea就报错,所以只能更换另一个未汉化的版本重新进行Tomcat配置:

 

 

 

 

 

 

 

 然后,进行资源热部署:

 

 部署结束后,在项目中新建servlet,然后编写servlet的代码,如下:

package servlet;

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

/**
 * Servlet implementation class MyServlet
 */
@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // 判断是否拥有cookie
        Cookie[] cookies = request.getCookies();
        //String value = "";
        if (cookies != null) {
            for (int i=0;i<cookies.length;i++) {
                if (cookies[i].getName().equals("remember")) {
                    response.sendRedirect("After.html");
                    return;
                }
            }
        }
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");
        // 判断账号密码是否正确,默认账号密码为:tom  123
        if (username != null && password != null) {
            if (!username.isEmpty() && !password.isEmpty() ) {
                if (username.equals("tom") && password.equals("123")&&remember!=null) {
                    Cookie newCookie = new Cookie("remember", "1");
                    newCookie.setMaxAge(30*24*60*60);
                    response.addCookie(newCookie);
                    response.sendRedirect("After.html");
                    return;
                } else if(username.equals("tom") && password.equals("123")){
                    response.sendRedirect("After.html");
                    return;
                }
            }
        }
        response.sendRedirect("Login.html");
    }
}

 

 

3.使用cookie,如果用户在登录时选择保存登录信息,30天内,用户无需登录

  在上面的代码中的doPost方法中,已经写了关于cookie的代码,这里不再阐述。 

前两步的效果图如下:

获取登录的用户名与密码:

自动填充密码:

 

 4.使用session,显示计科院网站当前在线人数

    public void sessionCreated(HttpSessionEvent arg0) {

        System.out.println("createSession.....");

        Map<String,Object> application=ActionContext.getContext().getApplication();

        //从web配置文件中得到属性的值,如果创建一个session就加一,销毁减一

        int onlineNumber=Integer.parseInt(application.get("onlineNumber").toString())+1;

        application.put("onlineNumber", onlineNumber);

    }



    public void sessionDestroyed(HttpSessionEvent arg0) {

        System.out.println("deleteSession.....");

        Map<String,Object> application=ActionContext.getContext().getApplication();

        int onlineNumber=Integer.parseInt(application.get("onlineNumber").toString())-1;

        application.put("onlineNumber", onlineNumber);

    }

5.使用过滤器解决乱码问题,登录时用户名为中文可能不能正常识别,解决该问题

  要解决这一问题,我们必须建立Filter,代码如下:

public class MyFilter implements Filter {

    /**
     * Default constructor. 
     */
    public MyFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        // place your code here

        // pass the request along the filter chain
        
        
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        chain.doFilter(request, response);
    }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}

码云地址:https://gitee.com/tianhaoqi/servlet

 

posted @ 2020-06-05 08:45  玉米yumi  阅读(189)  评论(0编辑  收藏  举报