JavaWeb(Servlet预习)

案例1:基于jsp+Servlet实现用户登录验证

1.input.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body><form action="loginCheck" method="post">用户名:<input type="text" name="username" /><br> 密码:<inputtype="password" name="userpwd" /><br> <input type="submit"value="提交"> <input type="reset"></form>
</body>
</html>

2.loginCheckServlet.java

package servlets;import java.io.IOException;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;@WebServlet("/loginCheck")
public class LoginCheckServlet extends HttpServlet {public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{String userName = request.getParameter("username");String userPwd = request.getParameter("userpwd");String info = "";if("abc".equals(userName)&&"123".equals(userPwd)) {info="欢迎你"+userName;}else {info="用户名或密码错误";}request.setAttribute("outputMessage", info);request.getRequestDispatcher("/info.jsp").forward(request, response);}}

3.info.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%=request.getAttribute("outputMessage") %>
</body>
</html>

案例2:基于jsp+Servlet+JavaBean实现用户注册

1.数据库连接类

package db;import java.sql.*;public class JdbcUtil {public static Connection getConnection() throws Exception{String driverName = "com.mysql.jdbc.Driver";String dbName = "students";String userName = "root";String userPwd = "1234";String url1 = "jdbc:mysql://localhost:3306/"+dbName;String url2 = "?user="+userName+"&password="+userPwd;String url3 = "&useUnicode=true&characterEncoding=UTF-8";String url = url1+url2+url3;Class.forName(driverName);Connection conn = DriverManager.getConnection(url);return conn;}public static void free(ResultSet rs,PreparedStatement pstmt,Connection conn) throws SQLException {if(rs!=null) {rs.close();}if(pstmt!=null) {pstmt.close();}if(conn!=null) {conn.close();}}
}

2.javabean实体类

package beans;public class User {private String userName;private String userPwd;public User(String userName,String userPwd) {this.userName = userName;this.userPwd = userPwd;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getUserPwd() {return userPwd;}public void setUserPwd(String userPwd) {this.userPwd = userPwd;}public User() {}}

3.数据库访问类dao

package dao;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;import javax.swing.plaf.basic.BasicInternalFrameTitlePane.RestoreAction;import beans.User;
import db.JdbcUtil;public class UserDao {//添加public void add(User user) throws Exception{Connection conn = null;PreparedStatement pstmt = null;conn = JdbcUtil.getConnection();String sql = "insert into user_b(username,userpassword) values(?,?)";pstmt = conn.prepareStatement(sql);pstmt.setString(1, user.getUserName());pstmt.setString(2, user.getUserPwd());pstmt.executeUpdate();JdbcUtil.free(null, pstmt, conn);}//查询全部public List<User> QueryAll() throws Exception{Connection conn = null;PreparedStatement pstmt = null;ResultSet rs = null;List<User> UserList = new ArrayList<User>();conn = JdbcUtil.getConnection();String sql = "select * from user_b";pstmt = conn.prepareStatement(sql);rs = pstmt.executeQuery();while(rs.next()) {String xm = rs.getString("username");String mm = rs.getString("password");User user = new User(xm,mm);UserList.add(user);}JdbcUtil.free(rs, pstmt, conn);return UserList;}//修改public int update(User user) throws Exception{Connection conn = null;PreparedStatement pstmt = null;int result = 0;conn = JdbcUtil.getConnection();String sql = "update user_b set userpassword=? where username=?";pstmt.setString(1, user.getUserName());pstmt.setString(2, user.getUserPwd());result = pstmt.executeUpdate();JdbcUtil.free(null, pstmt, conn);return result;}//删除public int delete(int username) throws Exception{Connection conn = null;PreparedStatement pstmt = null;int result = 0;conn = JdbcUtil.getConnection();String sql = "delete from user_b where username=?";pstmt = conn.prepareStatement(sql);pstmt.setInt(1, username);result = pstmt.executeUpdate();JdbcUtil.free(null, pstmt, conn);return result;}}

4.注册页面a.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body><form>用户名:<input type="text" name="xm"><br><br> 密码:<input type="password" name="mm"><br><br> <input type="submit" value="提交"></form>
</body>
</html>

5.处理登录的servlet

6.结果页面b.jsp

例3:学生体质信息管理

student.java

package beans;public class Student {private int id;private String name;private String sex;private int age;private float weight;private float height;public Student() {}public Student(int id,String name,String sex,int age,float weight,float height) {this.id = id;this.name = name;this.sex = sex;this.age = age;this.weight = weight;this.height = height;}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 getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public float getWeight() {return weight;}public void setWeight(float weight) {this.weight = weight;}public float getHeight() {return height;}public void setHeight(float height) {this.height = height;}}

studentDao.java

package Dao;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;import org.apache.tomcat.dbcp.dbcp2.PStmtKey;import com.sun.org.apache.xerces.internal.util.EntityResolver2Wrapper;import Util.JdbcUtil;
import beans.Student;public class StudentDao {public Student create(Student stu) throws Exception{Connection conn = JdbcUtil.getConnection();String sql = "insert into stu_info (id,name,sex,age,weight,height) values(?,?,?,?,?,?)";PreparedStatement pstmt = conn.prepareStatement(sql);pstmt.setInt(1, stu.getId());pstmt.setString(2, stu.getName());pstmt.setString(3, stu.getSex());pstmt.setInt(4, stu.getAge());pstmt.setFloat(5, stu.getWeight());pstmt.setFloat(6, stu.getHeight());pstmt.executeUpdate();JdbcUtil.free(null, conn, pstmt);return stu;}public List<Student> findAll() throws Exception{Connection conn = JdbcUtil.getConnection();String sql = "select * from stu_info";PreparedStatement pstmt = conn.prepareStatement(sql);ResultSet rs = null;List<Student> students = new ArrayList<Student>();rs = pstmt.executeQuery();while(rs.next()) {Student stu2 = new Student();stu2.setId(rs.getInt(1));stu2.setName(rs.getString(2));stu2.setSex(rs.getString(3));stu2.setAge(rs.getInt(4));stu2.setWeight(rs.getFloat(5));stu2.setHeight(rs.getFloat(6));students.add(stu2);}JdbcUtil.free(rs, conn, pstmt);return students;}public void remove(Student stu) throws Exception{Connection conn = JdbcUtil.getConnection();String sql = "delete from stu_info where name=?";PreparedStatement pstmt = conn.prepareStatement(sql);pstmt.setString(1, stu.getName());pstmt.executeUpdate();JdbcUtil.free(null, conn, pstmt);}public void update(Student stu) throws Exception{Connection conn = JdbcUtil.getConnection();String sql = "update stu_info set id=?,name=?,sex=?,age=?,weight=?,height=? where name=? ";PreparedStatement pstmt = conn.prepareStatement(sql);pstmt.setInt(1, stu.getId());pstmt.setString(2, stu.getName());pstmt.setString(3, stu.getSex());pstmt.setInt(4, stu.getAge());pstmt.setFloat(5, stu.getWeight());pstmt.setFloat(6, stu.getHeight());pstmt.setString(7, stu.getName());pstmt.executeUpdate();JdbcUtil.free(null, conn, pstmt);}
}

JdbcUtil.java

package Util;import java.sql.*;
import java.sql.DriverManager;import com.mysql.cj.jdbc.Driver;public class JdbcUtil {public static Connection getConnection() throws Exception {String dbName = "students";String driverName = "com.mysql.jdbc.Driver";String userName = "root";String userPwd = "1234";String url1 = "jdbc:mysql://localhost:3306/"+dbName;String url2 = "?user="+userName+"&password"+userPwd;String url3 = "&useUnicode=true&characterEncoding=UTF-8";String url = url1+url2+url3;Class.forName(driverName);Connection conn = DriverManager.getConnection(url);return conn;}public static void free(ResultSet rs,Connection conn,PreparedStatement pstmt) throws Exception {if(rs!=null) {rs.close();}if(conn!=null) {conn.close();}if(pstmt!=null) {pstmt.close();}}}

servlet:   insert.java

package servlet;import java.io.IOException;
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 Dao.StudentDao;
import beans.Student;/*** Servlet implementation class Insert*/
@WebServlet("/Insert")
public class Insert extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public Insert() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubrequest.setCharacterEncoding("UTF-8");int id = Integer.parseInt(request.getParameter("id"));String name = request.getParameter("name");String sex = request.getParameter("sex");int age = Integer.parseInt(request.getParameter("age"));Float weight = Float.parseFloat(request.getParameter("weight"));Float height = Float.parseFloat("height");Student stu = new Student(id,name,sex,age,weight,height);StudentDao studentDao = new StudentDao();studentDao.create(stu);response.sendRedirect(StudentServlet?action=list);response.getWriter().append("Served at: ").append(request.getContextPath());}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8" import="java.util.*" import="beans.Student"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生信息管理</title>
</head>
<body><a href="insert.jsp">添加学生</a><table><tr><th>学号</th><th>姓名</th><th>性别</th><th>年龄</th><th>体重</th><th>身高</th><th>操作</th></tr><%List<Student> students = (List<Student>) request.getAttribute("students");if (students != null && !students.isEmpty()) {for (Student student : students) {%><tr><td><%=student.getId()%></td><td><%=student.getName()%></td><td><%=student.getSex()%></td><td><%=student.getAge()%></td><td><%=student.getWeight()%></td><td><%=student.getHeight()%></td><td><a href="edit.jsp?name=<%=student.getName()%>">编辑</a> <ahref="delete.jsp?name=<%=student.getName()%>"onclick="return confirm('确定要删除吗?')">删除</a></td></tr><%}}%></table>
</body>
</html>

insert.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body><form action="insert" method="post"><table><tr><td>学号</td><td><input type="text" name="id"></td></tr><tr><td>姓名</td><td><input type="text" name="name"></td></tr><tr><td>性别</td><td><input type="text" name="sex"></td></tr><tr><td>年龄</td><td><input type="text" name="age"></td></tr><tr><td>体重</td><td><input type="text" name="weight"></td></tr><tr><td>身高</td><td><input type="text" name="height"></td></tr><tr><td><input type="submit" value="提交"></td></tr></table></form>
</body>
</html>

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

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

相关文章

Docker Compose 部署 Prometheus + Grafana

安装 docker-compose.yml version: 3.8services:# Prometheus 监控服务prometheus:image: prom/prometheus:latestcontainer_name: prometheusrestart: unless-stoppedvolumes:- ./conf/prometheus.yml:/etc/prometheus/prometheus.yml- ./prometheus_data:/prometheuscomman…

准确--使用 ThinBackup 插件执行备份和恢复

使用 ThinBackup 插件执行备份和恢复 导出&#xff08;备份&#xff09;步骤&#xff1a; 进入 Manage Jenkins > ThinBackup。设置 Backup schedule for full backups&#xff08;可选&#xff09;&#xff0c;并配置 Files to exclude&#xff08;可选&#xff09;。点击…

Qt Creator 从入门到项目实战

Qt Creator 简介 Qt Creator 是一个跨平台的集成开发环境&#xff08;IDE&#xff09;&#xff0c;专门用于开发 Qt 应用程序。它为开发者提供了一个强大的工具集&#xff0c;包括代码编辑器、调试器、UI 设计器以及性能分析工具等。 1.1 Qt Creator 的安装 Qt Creator 支持…

公司内网远程访问配置教程:本地服务器(和指定端口应用)实现外网连接使用

在数字化时代&#xff0c;企业的办公模式日益多元化&#xff0c;远程办公、跨地区协作等需求不断增加。这使得在公司内网中配置远程访问变得至关重要&#xff0c;它能让员工无论身处何地&#xff0c;只要有网络连接&#xff0c;就能便捷地访问公司内部的各类资源&#xff0c;如…

边缘计算如何重塑能源管理?从技术原理到应用场景全解析

在全球能源数字化转型的浪潮中&#xff0c;一个看似不起眼的设备正在悄悄改变工业能效管理的模式 —— 这就是边缘计算网关。以能源领域为例&#xff0c;传统的 "设备 - 云端" 二层架构正面临数据传输延迟、网络带宽压力大、断网失效等挑战&#xff0c;而边缘计算技术…

自主导航巡检机器人系统解决方案

自主导航巡检机器人系统解决方案 运动性能强大的通用型履带式机器人底盘&#xff0c;整车采用克里斯蒂全独立悬挂设计&#xff0c;内部搭载高扭矩无刷电机&#xff0c;通过精心匹配的底盘高度和功率配置&#xff0c;底盘表现出卓越的通过性能、低重心、平稳运行以及高效的传动效…

Vim 撤销 / 重做 / 操作历史命令汇总

Vim 撤销 / 重做 / 操作历史命令汇总 Vim 提供了丰富的撤销&#xff08;undo&#xff09;、重做&#xff08;redo&#xff09;及查看操作历史的命令&#xff0c;帮助你在编辑过程中灵活地回退或前进到任意修改点。下面按功能分类整理常用命令&#xff0c;便于快速查阅和记忆。…

装饰模式(Decorator Pattern)重构java邮件发奖系统实战

前言 现在我们有个如下的需求&#xff0c;设计一个邮件发奖的小系统&#xff0c; 需求 1.数据验证 → 2. 敏感信息加密 → 3. 日志记录 → 4. 实际发送邮件 装饰器模式&#xff08;Decorator Pattern&#xff09;允许向一个现有的对象添加新的功能&#xff0c;同时又不改变其…

项目四.高可用集群_ansible

设备准备 安装wordpress [rootlocalhost ~]# nmcli c del "Wired connection 1" [rootlocalhost ~]# nmcli c add type ethernet ifname ens224 con-name ens224 ipv4.method manual ipv4.addr 192.168.88.40/24 gw4 192.168.88.1 autoconnect true [rootlocalhos…

TensorFlow深度学习实战(21)——Transformer架构详解与实现

TensorFlow深度学习实战&#xff08;21&#xff09;——Transformer架构详解与实现 0. 前言1. Transformer 架构1.1 关键思想1.2 计算注意力1.3 编码器-解码器架构1.4 Transformer 架构1.5 模型训练 2. Transformer 类别2.1 解码器(自回归)模型2.2 编码器(自编码)模型2.3 Seq2s…

20250608-在 Windows 上使用 PyCharm 通过 SSH 连接到远程 Ubuntu 机器的 Anaconda 环境

在 Windows 上使用 PyCharm 通过 SSH 连接到远程 Ubuntu 机器的 Anaconda 环境 1. 确保远程机器上的 SSH 服务已启动 在远程 Ubuntu 机器上&#xff0c;确保 SSH 服务已安装并启动&#xff1a; sudo apt-get install openssh-server sudo systemctl start ssh sudo systemct…

Oracle 条件索引 case when 报错解决方案(APP)

文章目录 环境文档用途详细信息 环境 系统平台&#xff1a;Linux x86-64 Red Hat Enterprise Linux 7 版本&#xff1a;4.5 文档用途 本内容介绍 Oracle条件索引 case when 如何在HGDB中转换使用。 详细信息 1、oracle 索引 create unique index I_GL_VOUCHER_7 on gl_vo…

鸿蒙期末总结

一、概念 HarmonyOS应用关键概念&#xff1a;元服务和App的关系 App具有手动下载安装、包大小无限制、应用内或应用市场更新、全量功能等特征&#xff0c;可使用全量API 元服务具有免安装、包大小有限制、即用即走、轻量化等特征&#xff0c;只能使用“元服务API集” 鸿蒙的…

Vue3 + TypeScript + Element Plus 表格行按钮不触发 row-click 事件、不触发勾选行,只执行按钮的 click 事件

点击表格行按钮不触发 row-click 事件、不触发勾选行&#xff0c;只执行按钮的 click 事件 点击第一行的【编辑】&#xff0c;第一行为当前选择行&#xff0c; 同时也勾选了复选框&#xff0c;也会执行 row-click 事件 原来的代码&#xff1a; <el-table-column label"…

SiteAzure4.x 版本 访问html静态页文件出现404错误

问题描述&#xff1a; SiteAzure4.*版本&#xff0c;在upload文件夹中放置了html静态页文件&#xff0c;访问出现404错误 问题分析&#xff1a; 1、确认访问路径是否正确以及文件是否存在 2、确认相应文件夹权限是否正确 3、确认IIS默认文档是否允许静态页&#xff0c;MIM…

[免费]微信小程序音乐播放器(爬取网易云音乐数据)(node.js后端)【论文+源码】

大家好&#xff0c;我是java1234_小锋老师&#xff0c;看到一个不错的微信小程序音乐播放器(爬取网易云音乐数据)(node.js后端)&#xff0c;分享下哈。 项目视频演示 【免费】微信小程序音乐播放器(爬取网易云音乐数据)(node.js后端) 微信小程序毕业设计_哔哩哔哩_bilibili …

强化学习:策略梯度概念

2.策略梯度方法 目标是使策略 不断更新&#xff0c;回报更高。 计算每一个轨迹的回报&#xff0c;和对应的概率 目标是使回报高的轨迹概率应该高。这样整个策略的期望回报也会高。 什么是策略期望回报&#xff1f; 就是用这个策略跑了若干个轨迹&#xff0c;得到回报&#x…

Java 中高级开发岗技能与面试要点梳理

目录 一、核心技术深度掌握 (一)Java 语言高阶特性 JVM 底层原理剖析 并发编程高级应用 Java 新特性实战 (二)主流框架与中间件精通 Spring 生态全面掌控 分布式中间件实战精通 (三)数据库与存储优化专家 SQL 与 ORM 高级应用 分库分表实战 NoSQL 实战(Elas…

职场生存发展指南 | 边界 / 责任 / 社交 / 情绪

注&#xff1a;本文为“职场生存发展”相关合辑。 略作重排&#xff0c;未整理去重。 如有内容异常&#xff0c;请看原文。 职场生存发展指南 | 边界 / 责任 / 社交 / 情绪 职场如江湖&#xff0c;充满机遇与挑战。在单位中立足&#xff0c;需深谙生存智慧——既要守住底线、…

vue3 daterange正则踩坑

<el-form-item label"空置时间" prop"vacantTime"> <el-date-picker v-model"form.vacantTime" type"daterange" start-placeholder"开始日期" end-placeholder"结束日期" clearable :editable"fal…