javaweb学习笔记之实验一

实验内容:

longin.jsp 登陆(包含用户名和密码)--->
ControlServlet:
1-负责接收登陆信息,
2.判断用户名、密码是否正确
3.正确  转发到到文件上传页面---》完成上传功能
4.不正确,重定向到longin.jsp

一.Content-Type

  一般在Servlet中,习惯性的会首先设置请求以及响应的内容类型以及编码方式:
  response.setContentType(“text/html;charset=UTF-8”);
  request.setCharacterEncoding(“UTF-8”);

Content-Type(内容类型),一般是指网页中存在的 Content-Type,用于定义网络文件的类型和网页的编码,决定浏览器将以什么形式、什么编码读取这个文件,这就是经常看到一些 PHP 网页点击的结果却是下载一个文件或一张图片的原因。

Content-Type 标头告诉客户端实际返回的内容的内容类型。
实例:
在这里插入图片描述
HTTP content-type 对照表

二.request.getParameter

request.getParameter获取通过http协议提交过来的数据.     
通过容器的实现来取得通过get或者post方式提交过来的数据

三.JSP 页面重定向

  最简单的重定向方式就是使用response对象的sendRedirect()方法:
  public void response.sendRedirect(String location)
  request.getContextPath()是解决相对路径的问题,可返回站点的根路径。

四.代码

servelet.java

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" ,urlPatterns="/ser1")
public class Servlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        String  name=request.getParameter("name");
        String  password=request.getParameter("password");
        if("111".equals(name)&&"123".equals(password)){
    
    
//
            //请求重定向回success.jsp
          //  response.sendRedirect(request.getContextPath()+"/success.jsp");
            response.sendRedirect("success.jsp");
        }else
            //请求重定向回longin.jsp
            response.sendRedirect(request.getContextPath()+"/longin.jsp");
            response.sendRedirect("longin.jsp");
    }



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

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: wcy
  Date: 2021/3/12
  Time: 10:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <form action="ser1" method="post">

  用户名:<input type="text" name="name" ><br>
  密码:<input type="password" name="password"><br>
  <button type="submit" name="submit">提交</button>

  </form>

  </body>
</html>

success.jsp

<%--
  Created by IntelliJ IDEA.
  User: wcy
  Date: 2021/3/12
  Time: 11:23
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>success</title>
</head>
<body>
success<br>
<input type="file">

</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_47917118/article/details/114944367