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

2024-09-06 18:44

本文主要是介绍木舟0基础学习Java的第二十六天(JavaWeb),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

设置响应头

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;}@Overridepublic 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;@Overridepublic 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();}@Overrideprotected 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,valuereq.getRequestDispatcher("HanderServlet").forward(req, resp);
@WebServlet("/HanderServlet")
public class HanderServlet extends HttpServlet {@Overrideprotected 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();}@Overrideprotected 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 {@Overrideprotected 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对象的数据//获取cookieCookie[] 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();}@Overrideprotected 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){//创建sessionHttpSession 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 {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");resp.setContentType("text/html;charset=UTF-8");//创建sessionHttpSession 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 {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");resp.setContentType("text/html;charset=UTF-8");HttpSession session = req.getSession();//关闭sessionsession.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();//删除bsc.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);

这篇关于木舟0基础学习Java的第二十六天(JavaWeb)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1142816

相关文章

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

Mac系统下卸载JAVA和JDK的步骤

《Mac系统下卸载JAVA和JDK的步骤》JDK是Java语言的软件开发工具包,它提供了开发和运行Java应用程序所需的工具、库和资源,:本文主要介绍Mac系统下卸载JAVA和JDK的相关资料,需... 目录1. 卸载系统自带的 Java 版本检查当前 Java 版本通过命令卸载系统 Java2. 卸载自定

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja

javax.net.ssl.SSLHandshakeException:异常原因及解决方案

《javax.net.ssl.SSLHandshakeException:异常原因及解决方案》javax.net.ssl.SSLHandshakeException是一个SSL握手异常,通常在建立SS... 目录报错原因在程序中绕过服务器的安全验证注意点最后多说一句报错原因一般出现这种问题是因为目标服务器

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项