JavaNote 4.2 Servlet转换与重定向

一、Servlet

package com.test;

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;

@WebServlet(name = "Servlet_3",urlPatterns = "/login")
public class Servlet_3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String name = "wuxiaowei";
            String pawd ="123456";
            String username = request.getParameter("name");
            String userpwd = request.getParameter("pwd");
            if(!username.equals(name)){
                request.setAttribute("errormessage","账户错误");
                request.getRequestDispatcher("/loginerror.jsp").forward(request,response);//转发
            }
            else if(!userpwd.equals(pawd)){
                request.setAttribute("errormessage","密码错误");
                request.getRequestDispatcher("/loginerror.jsp").forward(request,response);
            }
            else{
                //重定向的两种方式
//                response.setStatus(302);
//                response.setHeader("location","http://www.baidu.com");
                response.sendRedirect(".loginSucess.html");//等于上面两行的结合
            }
    }
}

二、html

login

用户登录

账号:

密码:

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


    Title
    <%----%>
    


error

<%--<%=request.getAttribute("errormessage")%>--%> <%=request.getAttribute("errormessage")%>

sucess


登录成功

你可能感兴趣的:(Java,Note)