【Java】【JSP】jsp入门-实现登陆

  1. login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Login


  1. resutl.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


<%
    out.print(request.getAttribute("msg"));
    if (request.getAttribute("res").equals("1")) {
        out.print("退出登录");
    }
%>


  1. LoginServlet
package com.stu.demo;

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 java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html; charset=utf-8");
    PrintWriter out = response.getWriter();

    request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
  1. DoLoginServlet
package com.stu.demo;

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 java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "DoLoginServlet")
public class DoLoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html; charset=utf-8");
    PrintWriter out = response.getWriter();

    String uid = request.getParameter("uid");
    String pwd = request.getParameter("pwd");
    if (uid.equals("123") && pwd.equals("321")) {
        request.setAttribute("msg", "登陆成功:" + uid);
        request.setAttribute("res", "1");
    } else {
        request.setAttribute("msg", "登陆失败");
        request.setAttribute("res", "0");
    }
    request.getRequestDispatcher("/result.jsp").forward(request, response);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}

你可能感兴趣的:(【Java】【JSP】jsp入门-实现登陆)