JavaWeb(Servlet预习)

发布于:2025-06-14 ⋅ 阅读:(15) ⋅ 点赞:(0)

案例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> 密码:<input
			type="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 stub
		request.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 stub
		doGet(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> <a
				href="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>


网站公告

今日签到

点亮在社区的每一天
去签到