Bootstrap

JavaWeb原生框架开发JSP+Servlet+JDBC案例

目录

概要

功能

技术名词解释

技术细节

        1. 项目列表

        2. 网页

        3. Servlet 

小结


概要

        JavaWeb开发案例,使用JSP、Servlet、JDBC原生框架技术,实现用户模块的功能开发,主要用于学习。

功能

        1. 注册

        2. 登录

        3. 用户模块

                3.1 查询用户信息

                3.2 删除用户信息

                3.3 修改用户信息

技术名词解释

        JSP:全称Java Server Pages, 是由Sun公司主导创建的一种动态网页技术标准,JSP中可以编写Java脚本

        Servlet: 是Java Servlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序,用来接收和响应来自web客户端发送的请求

        JDBC:Java数据库连接,(Java Database Connectivity,简称JDBC)是Java语言中用来规范程序如何来访问数据库的应用程序接口

技术细节

1. 项目列表

2. 网页

res.html 注册页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>用户注册</h1>
	<form action="res" method="post">
		<input type="text" name="username"><br><br>
		<input type="password" name="password"><br><br>
		<button type="submit">注册</button>
	</form>
</body>
</html>

login.html 登录页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>用户登录</h1>
	<form action="login" method="post">
		<input type="text" name="username"><br><br>
		<input type="password" name="password"><br><br>
		<button type="submit">登录</button>
	</form>
</body>
</html>

main.jsp 首页 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!-- 引入list包 -->
<%@ page import="java.util.List"%>
<!-- 引入user包 -->
<%@ page import="com.qls.bean.User"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<h1>XXX官网</h1>
	
	<!-- 编写Java代码,从当前请求中获取到用户信息 -->
	<p>
		欢迎你,
		<%=request.getParameter("username") %>
	</p>
	
	<!-- 编写Java代码,获取请求对象中存储的list集合 -->
	<%
		List<User> list = (List)request.getAttribute("list");
	%>
	
	<table>
		<thead>
			<tr>
				<th>序号</th>
				<th>账号</th>
				<th>密码</th>
				<th>操作</th>
			</tr>
		</thead>
		<tbody>
			<%for(User user : list){ %>
				<tr>
					<td><%=user.getId()%></td>
					<td><%=user.getUsername()%></td>
					<td><%=user.getPassword()%></td>
					<td><a href="deleteUser?id=<%=user.getId()%>">删除</a></td>
				</tr>
			<%}%>
		</tbody>
	</table>
	
</body>
</html>
3. Servlet 

 DBUtils工具类,建立数据库连接

package com.qls.utils;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBUtils {
	String url = "jdbc:mysql://localhost:3306/user";
	String user = "root";
	String pword = "root";
	
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public Connection getConn() throws Exception {
		
		Connection con = DriverManager.getConnection(url, user, pword);
		
		return con;
	}
}

User类,创建JavaBean

package com.qls.bean;

/**
 * 用户类,存储用户表中的数据
 * 		属性与用户表的字段保持一致
 * */
public class User {

	int id;
	String username;
	String password;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

 ResServlet 注册功能

package com.qls.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

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 com.qls.utils.DBUtils;

/**
 * 注册请求
 * */
@WebServlet("/res")
public class ResServlet extends HttpServlet {
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//接受请求
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		//获得链接
		DBUtils db = new DBUtils();
		try {
			Connection conn = db.getConn();
			String sql = "insert into user(username,password) values(?,?)";
			PreparedStatement ps = conn.prepareStatement(sql);
			//设置sql语句的参数
			ps.setString(1, username);
			ps.setString(2, password);
			//执行sql 得到执行结果
			int i = ps.executeUpdate();
			//处理结果
			if(i > 0) {
				//执行成功,重定向跳转到登录页面 
				response.sendRedirect("login.html");
			}else {
				//执行失败 重定向跳转到注册页面  
				response.sendRedirect("res.html");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

LoginSertvlet 登录功能

package com.qls.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

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 com.qls.utils.DBUtils;

/**
 * 登录请求
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		DBUtils db = new DBUtils();
		try {
			Connection conn = db.getConn();
			String sql = "select username,password from user where username=? and password=?";
            //预处理对象
			PreparedStatement ps = conn.prepareStatement(sql);
            //给sql语句中的?占位符赋值
			ps.setString(1, username);
			ps.setString(2, password);
            //执行sql,获取结果集
			ResultSet rs = ps.executeQuery();
			//处理结果集
			while(rs.next()) {
				String uname = rs.getString("username");
				String pword = rs.getString("password");
				
                //判断结果
				if(username.equals(uname) && password.equals(pword)) {
					//请求转发 跳转到主页
					request.getRequestDispatcher("/show").forward(request, response);
				}else {
					//重定向,跳转到登录页面
					response.sendRedirect("login.html");
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 ShowAllServlet 用户模块,查询用户信息功能

package com.qls.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

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 com.qls.bean.User;
import com.qls.utils.DBUtils;

/**
 * 查询用户功能
 */
@WebServlet("/show")
public class ShowAllServlet extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DBUtils db = new DBUtils();
		try {
			Connection conn = db.getConn();
			String sql = "select * from user";
			PreparedStatement ps = conn.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			
			//创建集合,保存user对象
			List<User> list = new ArrayList<User>();//user user
			
			while(rs.next()) {  //2   root   root
				int id = rs.getInt("id");//2
				String username = rs.getString("username");//root
				String password = rs.getString("password");//root
				
				//创建User类对象  将遍历出来的一条数据,保存到user对象的属性中
				User user = new User();
				user.setId(id);
				user.setUsername(username);
				user.setPassword(password);
				
				//将user对象 添加到list集合中
				list.add(user);
			}
			
			//将list集合保存到request对象中
			request.setAttribute("list", list);
			
			//请求转发
			request.getRequestDispatcher("main.jsp").forward(request, response);
			
		}catch (Exception e) {
			// TODO: handle exception
		}
}
	
}

 DeleteUserServlet  用户模块,删除用户信息功能

package com.qls.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

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 com.qls.bean.User;
import com.qls.utils.DBUtils;

/**
 * 删除用户功能
 */
@WebServlet("/deleteUser")
public class DeleteUserServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String id = request.getParameter("id");
		
		int uid = Integer.parseInt(id);
		
		
		DBUtils db = new DBUtils();
		try {
			Connection conn = db.getConn();
			String sql = "delete from user where id=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, uid);
			
			int i = ps.executeUpdate();
			
			if(i > 0) {
				//请求转发   删除成功,将请求转发到查询表用户的servlet中,重新查询用户,重新展示用户信息
				request.getRequestDispatcher("/show").forward(request, response);
			}else {
				//请求转发
				request.getRequestDispatcher("main.jsp").forward(request, response);
			}
			
		}catch (Exception e) {
			// TODO: handle exception
		}
}
	
}

小结

        本文主要使用JavaWeb原生框架,完成一个简单的学习案例,提供增删改查方法。

        JSP中使用Java代码获取数据、展示数据。

        Servlet中接收请求、处理业务逻辑、资源跳转。

        JDBC建立数据库连接。

;