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
繁體地址,請注明出處:http://hk.pswp.cn/news/909237.shtml
英文地址,請注明出處:http://en.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…