Response & web登录操作 -2024/10/17

响应行设置响应状态码:

void setStatus(int sc);

设置响应头键值对:

void setHeader(String name,String value);

response实现重定向

   resp.setStatus(302);
   resp.setHeader("location","https://www.4399.com");

前端a.html登录,将结果传给后端,用request接收,用Mybatis框架连接数据库,获取用户名和密码,
并与前端接收到的用户名,密码匹配,如果匹配成功,通过response输出到网站,显示登录成功

package com.stdu.web;

import com.stdu.mapper.UserMapper;
import com.stdu.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

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.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;

@WebServlet(urlPatterns = "/test3")
public class a03Request_Test extends HttpServlet {

    Set<String> set = new HashSet<>();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        ArrayList<User> users = userMapper.selectAllUser();

        //请求方式POST,解决request中文乱码
        //req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username + " "+ password);
        resp.setHeader("content-type","text/html;charset=utf-8");
        boolean flag = false;
        for (User u : users) {
            if(u.getPassword().equals(password) && u.getUsername().equals(username)){
                resp.getWriter().write(username + "登录成功");
                flag = true;
                return;
            }
        }
        if(!flag) resp.getWriter().write("用户名或密码错误");
    }



    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}

posted @ 2024-10-17 22:11  XYu1230  阅读(5)  评论(0编辑  收藏  举报