木舟0基础学习Java的第二十六天(JavaWeb)

news2024/9/25 11:13:35

设置响应头

resp.setHeader("key","nihao");//推荐使用英文 中文会乱码

案例:模拟登录

 jdbc.properties

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?verifyServerCertificate=false&useSSL=false
name=root
password=123456

JDBCUtil

public class JDBCUtil {
    static String driverClass=null;
    static String url=null;
    static String name=null;
    static String password=null;
    static{
        Properties properties=new Properties();
        InputStream is=null;
        try {
            is=JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
            properties.load(is);
            driverClass=properties.getProperty("driverClass");
            url=properties.getProperty("url");
            name=properties.getProperty("name");
            password=properties.getProperty("password");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static Connection getConn(){
        Connection conn=null;
        try {
            Class.forName(driverClass);
            conn= DriverManager.getConnection(url,name,password);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return conn;
    }
    private static void closeConn(Connection conn){
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally{
                conn=null;
            }
        }
    }
    private static void closePs(PreparedStatement ps){
        if(ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally{
                ps=null;
            }
        }
    }
    private static void closeRs(ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally{
                rs=null;
            }
        }
    }
   public static void release(Connection conn,PreparedStatement ps,ResultSet rs){
       closeRs(rs);
       closePs(ps);
       closeConn(conn);
   }
    public static void release(Connection conn,PreparedStatement ps){
        closePs(ps);
        closeConn(conn);
    }
}

T_user

需要实现序列化 Serializable接口

public class T_user implements Serializable{
    private int id;
    private String name;
    private String pwd;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "T_user{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

UserDao

public interface UserDao {
    public T_user login(String uname, String pwd);
}

UserDaoImpl

public class UserDaoImpl implements UserDao {
    //处理数据连接数据库
    Connection conn=null;
    PreparedStatement ps=null;
    ResultSet rs=null;
    T_user user=null;
    @Override
    public T_user login(String uname, String pwd) {
        try {
            conn= JDBCUtil.getConn();
            String sql="select * from t_user where uname=? and pwd=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,uname);
            ps.setString(2,pwd);
            rs=ps.executeQuery();
            while(rs.next()){
                String uname1 = rs.getString("uname");
                String pwd1 = rs.getString("pwd");
                user=new T_user();
                user.setName(uname1);
                user.setPwd(pwd1);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            JDBCUtil.release(conn,ps,rs);
        }
        return user;
    }
}

LoginService

@WebServlet("/LoginService")
public class LoginService extends HttpServlet {
    private UserDao UserDao;
    public LoginService() {
        UserDao=new UserDaoImpl();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String uname = req.getParameter("uname");
        String pwd = req.getParameter("pwd");
        System.out.println("uname:" + uname + "\tpwd:" + pwd);
        T_user user=UserDao.login(uname,pwd);
        if(user!=null){
            resp.getWriter().write("<font color='red' size=30>登录成功,欢迎"+user.getName()+"回来!</font>");
        }else{
            resp.getWriter().write("<font color='red' size=30>登录失败,账号或密码错误!</font>");
        }
    }
}

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="LoginService" method="post">
  用户名:<input type="text" name="uname">
  密码:<input type="password" name="pwd">
    爱好:<input type="checkbox" name="hobby" value="抽烟">抽烟
    <input type="checkbox" name="hobby" value="喝酒">喝酒
    <input type="checkbox" name="hobby" value="烫头">烫头
    <input type="checkbox" name="hobby" value="蹦迪">蹦迪
  <input type="submit" value="提交">
</form>
</body>
</html>

请求转发重定向

请求转发

特点:路径不会发生改变

缺点:每次刷新页面 就相当于重新提交

请求转发 在登录场景 和 转账场景不能使用
req.getRequestDispatcher("success.html").forward(req,resp);

重定向

缺点:不能携带数据

 resp.sendRedirect("success.html");

servlet跳转servlet

//将数据以键值对的方式存入
            req.setAttribute("user", user);//key,value
            req.getRequestDispatcher("HanderServlet").forward(req, resp);
@WebServlet("/HanderServlet")
public class HanderServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       T_user user = (T_user)req.getAttribute("user");//利用getAttribute获取值
       resp.getWriter().write("<h1>系统提示</h1>");
       resp.getWriter().write("<hr/>");
       resp.getWriter().write("<font color='red'>欢迎,"+user.getUname()+"登录成功!</font>");
    }
}

Cookie

cookie技术是浏览器端的数据存储技术 解决了同一个工程下不同请求需要使用相同数据的问题 我们把请求需要共享的请求数据 存储在浏览器端 避免用户进行重复书写请求数据 

特点:适合少量数据 键值对 不安全

注意:一个cookie对象存储一条数据 多条数据 可以创建多个cookie对象进行存储

作用:Cookie技术解决不同请求发送之间的数据共享问题

Cookie的使用

@WebServlet("/LoginSerlet")
public class LoginUser extends HttpServlet {
    private com.dao.UserDao UserDao;

    public LoginUser() {
        UserDao = new UserDaoImpl();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String uname = req.getParameter("uname");
        String pwd = req.getParameter("pwd");
        System.out.println("uname:" + uname + "\tpwd:" + pwd);
        T_user user=UserDao.login(uname,pwd);
        if(user!=null){
            //将数据存储到Cookie当中
            Cookie c1=new Cookie("name",user.getUname());
            Cookie c2=new Cookie("pwd",user.getPwd());
            //设置三天免登录 默认不设置时间 关闭浏览器立即失效
            c1.setMaxAge(24*3600*3);
            //把存储了登录信息的Cookie 通过响应resp 响应到浏览器中
            resp.addCookie(c1);
            resp.addCookie(c2);
            resp.sendRedirect("success");
        }else{
            req.getRequestDispatcher("login.html").forward(req, resp);
        }
    }
}
@WebServlet("/success")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //通过浏览器携带的cookie name=admin pwd=123456 找tomcat中cookie对象的数据
        //获取cookie
        Cookie[] cookies = req.getCookies();//键值对
        String value=null;
        //遍历所有cookie 找cookie的key是user的cookie对象
        for (Cookie c : cookies) {
            if("name".equals(c.getName())) {
                value = c.getValue();
                System.out.println("name:"+value);
            }
            if("pwd".equals(c.getName())) {
                value = c.getValue();
                System.out.println("pwd:"+value);
            }
        }
        resp.getWriter().write("<h1>系统提示</h1>");
        resp.getWriter().write("<hr/>");
        resp.getWriter().write("<font color='red'>欢迎,"+value+"登录成功!</font>");

    }
}

中央仓库(jar包下载)

Maven Repository: Central (mvnrepository.com)icon-default.png?t=O83Ahttps://mvnrepository.com/repos/central

 Session

首先创建Session Session在tomcat容器中 有且只有一个

Session默认时间30分钟 在开发中一般都使用Session存储用户登录信息

@WebServlet("/SessionLogin")
public class SessionLogin extends HttpServlet {
    UserService service;

    public SessionLogin() {
        service = new UserServiceImpl();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String uname = req.getParameter("uname");
        String pwd = req.getParameter("pwd");
        T_stu stu = service.login(uname, pwd);
        if(stu!=null){
            //创建session
            HttpSession session = req.getSession();
            //将数据以键值对的方式存入
            session.setAttribute("stu", stu);
            resp.sendRedirect("SessionUser");
        }else{
            req.getRequestDispatcher("login.html").forward(req, resp);
        }

    }
}
@WebServlet("/SessionUser")
public class SessionUser extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //创建session
        HttpSession session = req.getSession();
        //获取数据
        T_stu stu =(T_stu)session.getAttribute("stu");
            resp.getWriter().write("<h1>系统提示</h1>");
            resp.getWriter().write("<hr/>");
            resp.getWriter().write("<h1>登录成功,欢迎"+stu.getUname()+"登录!</h1>");
            resp.getWriter().write("<a href='exit'>退出</a>");
    }
}
@WebServlet("/exit")
public class SessionExit extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        HttpSession session = req.getSession();
        //关闭session
        session.invalidate();
        resp.sendRedirect("login.html");
    }
}

ServletContext(上下文对象携带数据)

生命周期 程序启动到结束

作用域 在项目内

创建

        //第一种创建方式 有就创建 没有就获取
        ServletContext sc1= this.getServletContext();
        //第二种
        ServletContext sc2=req.getSession().getServletContext();
        //第三种
        ServletContext c3=this.getServletConfig().getServletContext();

得到

 ServletContext sc = this.getServletContext();
        String a =(String) sc.getAttribute("a");
        String b =(String) sc.getAttribute("b");
        String c =(String) sc.getAttribute("c");
        resp.getWriter().write("a:"+a+"b:"+b+"c:"+c);

删除

ServletContext sc = this.getServletContext();
        //删除b
        sc.removeAttribute("b");

读取配置文件的配置信息

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <context-param>
        <param-name>name</param-name>
        <param-value>木舟</param-value>
    </context-param>
</web-app>
String city = sc.getInitParameter("city");
        System.out.println(city);

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2110203.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Qt:玩转QPainter后转之太极图(步骤详细、包含源码)

前言 简单了解了QPainter之后还是要做两个小例子练一练&#xff0c;不实际去做&#xff0c;只看看函数是没啥太大提升的&#xff0c;这里就简单画一个太极图。 正文 我们都知道太极分为阴阳鱼两部分&#xff0c;阴鱼(黑色)有个白色鱼眼&#xff0c;阳鱼(白色)有个黑色鱼眼&am…

Notes,无代码应用开发王者归来!

大家好&#xff0c;才是真的好。 连续一个星期都在讲HCL Notes Domino 14.5 EAP1&#xff0c;大家是不是已经感到疲惫了&#xff1f;和大家一样&#xff0c;我并没有。 因此&#xff0c;看了一下9月4号晚上的HCL Notes Domino 14.5 EAP1在线广播回顾&#xff0c;发现了几个大…

模拟RabbitMQ实现消息队列【项目】

文章目录 1. 项目介绍什么是RabbitMQ&#xff1f; 2. 开发环境3. 技术选型3.1ProtoBuf使用介绍&#xff1a;3.2 Muduo库3.3 SQLite3什么是SQLIte&#xff1f;为什么要用SQLite&#xff1f; 3.4 Gtest什么是Gtest 4. 需求分析4.1 核心概念4.2 核心API4.3 交换机类型4.4 持久化4.…

UVa1389/LA3709 Hard Life

UVa1389/LA3709 Hard Life 题目链接题意输入格式输出格式 分析AC 代码 题目链接 本题是2006年icpc欧洲区域赛东北欧赛区的H题 题意 约翰是一家公司的CEO。公司的股东决定让他的儿子斯科特成为公司的经理。约翰十分担心&#xff0c;儿子会因为在经理岗位上表现优异而威胁到他CE…

IPv4地址学习

今天学习了IPv4&#xff0c;做下学习笔记&#xff1a; 什么是IPv4&#xff1f; IPv4地址是网络层地址&#xff0c;用于标识网络中的每个节点。 什么是子网&#xff1f;什么是主类子网划分&#xff1f; 我们将IP地址划分为网络位和主机位 一个地址为192.168.1.2/24&#xff…

【HTML】置换元素(替换元素)

● 它的内容不是由元素的标签内的内容决定的,而是由元素的属性决定的 ● 可以通过CSS设置宽度和高度。 常见的置换元素主要包括以下几种: <img> 元素:用于嵌入图像,通过 src 属性指定图像的路径。例如:<img src="example.jpg" alt="示例图片&quo…

场景感知技术带您重塑未来生活的新篇章

在科技日新月异的今天&#xff0c;场景感知技术正以前所未有的速度渗透到我们生活的方方面面&#xff0c;成为连接物理世界与数字世界的桥梁&#xff0c;重塑着人类的认知方式与生活体验。这项技术通过综合运用传感器、大数据分析、人工智能等前沿科技&#xff0c;实现对周围环…

C++多态 学习笔记(上)

本文涉及的指针都是 4bytes 。 如果要其他平台下&#xff0c;部分代码需要改动。比如&#xff1a;如果是 x64 程序&#xff0c;则需要考虑指针是 8bytes 问题 等等。 什么是多态&#xff1f; 举个例子&#xff1a;比如 买票这个行为 &#xff0c;当 普通人 买票时&#xff0c;…

短剧APP系统搭建,短剧市场的发展机遇

短剧作为近几年内发展快速的行业&#xff0c;一直深受大众的欢迎&#xff0c;各种让观众上头的短剧层出不穷&#xff0c;深深吸引着大众。短剧的巨大发展前景也吸引了大量资本涌入市场&#xff0c;目前&#xff0c;短剧入局者也都获得了不菲的经济收益&#xff01; 随着短剧行…

C++下标+【】、迭代器、范围for、迭代器对于其他容器都是通用的、迭代器可以更好的跟算法配合、rbegin和rend函数、const修饰的迭代器等的介绍

文章目录 前言一、 下标 【】二、 迭代器1.begin2. end3. 使用迭代器遍历string类对象 三、范围for(语法糖)五、迭代器对于其他容器都是通用的六、迭代器可以更好地跟算法配合七、 rbegin 和 rend函数八、 const 修饰的迭代器总结 前言 C下标【】、迭代器、范围for、迭代器对…

JavaEE---Spring MVC(5)

MVC学习小案例3 留言板案例 后端代码 测试 点击刷新的时候页面的这些记录仍在 一个小tips 我们在日常中写的时候会经常写到get和set方法,这会使整个代码看起来非常多不好看,这里我们引入一个新的依赖解决这个问题 引入LomBok依赖 那要是个别情况下我们不想获取他的ge…

高集成度双通道差分式电容型传感芯片-MC11

工采电子代理的MC11S、MC11T是一款高集成度双通道电容型传感芯片&#xff0c;芯片直接与被测物附近的差分电容极板相连&#xff0c;通过谐振激励并解算测量微小电容的变化。激励频率在0.1~20MHz范围内可配置&#xff0c;其频率测量输出为16bit数字信号&#xff0c;对应的电容感…

Ventoy启动盘制作

然后直接将系统的ISO镜像直接拷贝进去&#xff0c;就能直接使用

69页PPT全面预算管理体系的框架与落地

一、明确企业战略目标企业战略目标是预算指标体系确立的根本出发点。它为预算指标的设定提供了方向和指导。 深入分析企业长期发展规划 企业需要对自身的长期发展规划进行全面、深入的分析。这包括对市场趋势、行业竞争态势、技术发展方向等外部环境因素的研究&#xff0c;以…

AI技术颠覆游戏开发:谷歌DeepMind GameNGen实时生成《DOOM》探秘

引言 近年来&#xff0c;生成式人工智能&#xff08;AIGC&#xff09;在图像和视频生成领域取得了巨大突破。然而&#xff0c;谁能想到&#xff0c;这项技术正逐渐渗透进游戏开发领域&#xff0c;且潜力巨大。2023年8月29日&#xff0c;谷歌DeepMind发布了名为《扩散模型是实时…

【舍入,取整,取小数,取余数丨Excel 函数】

数学函数 1、Round函数 Roundup函数 Rounddown函数 取整&#xff1a;(Int /Trunc)其他舍入函数&#xff1a; 2、Mod函数用Mod函数提取小数用Mod函数 分奇偶通过身份证号码判断性别 1、Round函数 Roundup函数 Rounddown函数 Round(数字&#xff0c;保留几位小数)&#xff08;四…

解除网站禁用右键 解除禁用选择方法 并允许复制

限制我复制&#xff0c;太恶心了&#xff0c;别用技术作恶&#xff01;&#xff01;&#xff01; 一般HTML网站禁止右键选择的方法 <body ondragstart"return false" oncontextmenu"return false" onselectstart"return false">解除网站…

遇到“msvcp120.dll丢失”的错误提示?来看看msvcp120.dll丢失的解决方法都有哪些?

遇到“msvcp120.dll丢失”的错误提示可能会让人感到焦虑&#xff0c;尤其是当你尝试运行某个应用程序或游戏时突然接收到这样的消息。​msvcp120.dll​是Microsoft Visual C 2013 Redistributable Package 中的一个文件&#xff0c;主要负责C标准库中的功能&#xff0c;比如输入…

C++第四十六弹---解锁多线程编程的奥秘:<thread>库深入探索

✨个人主页&#xff1a; 熬夜学编程的小林 &#x1f497;系列专栏&#xff1a; 【C语言详解】 【数据结构详解】【C详解】 目录 1 线程库 1.1 thread类的简单介绍 1.2 线程函数参数 1.3 原子性操作库(atomic) 1.4 lock_guard与unique_lock 1.4.1 mutex的种类 1.4.2 loc…

python-小理的三角形

题目描述 小理有一个数组长度大小为 n &#xff0c;数组中有 n 个正整数。 现在小理请你从其中选出三个元素&#xff08;注意选择元素的下标不能相同&#xff0c;但是其值可以相同&#xff09;组成一个三角形。 无法做到&#xff0c;请输出一行一个字符串"No solution&quo…