View层:jsp+servlet:

jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>青芒管理系统-注册页面</title>
<style type="text/css">
span {
color: red;
}
</style>
<script type="text/javascript" src="js/userCheck.js"></script>
</head>
<body>
<!-- jsp中有九大内置对象,铜鼓pageContext对象可以获取其他内置对象 -->
<form action="${pageContext.request.contextPath }/regist?type=reg" method="post">
<table align="center">
<tr>
<td>用户名:</td>
<td><input id="uname" type="text" name="uname" /> <span
id="spname">${message }</span></td><!-- 此处message对应注册的servlet中的 信息请求赋值-->
</tr>
<tr>
<td>密码:</td>
<td><input id="upwd" type="password" name="upassword" /> <span
id="sppwd"></span></td>
</tr>

<tr>
<td>姓名:</td>
<td><input id="urealname" type="text" name="urealname" /> <span
id="sprealname"></span></td>
</tr>
<tr>
<td>年龄:</td>
<td><input id="uage" type="text" name="uage" /> <span
id="spage"></span></td>
</tr>
<tr>
<td>性别:</td>
<td>男<input type="radio" name="usex" value="1" />女<input
type="radio" name="usex" value="0" checked="checked" /></td>
</tr>
<tr>
<td><input type="submit" value="提交数据"
onclick="return checkControl();" /></td>
<td><input type="reset" /></td>
</tr>
</table>
</form>
</body>
</html>

servlet:

/**
*
*/
package com.qingmang.servlet;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.qingmang.domain.User;
import com.qingmang.exception.UserExistException;
import com.qingmang.service.UserService;

/**
* @author administrator
* 用户添加和注册servlet
*
*/
@SuppressWarnings("serial")
public class RegistServlet extends HttpServlet {

private UserService service = new UserService();

public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {

req.setCharacterEncoding("UTF-8");
res.setContentType("text/html;charset=UTF-8");

String type = req.getParameter("type");
String uname = req.getParameter("uname");
String upwd = req.getParameter("upassword");
String realName = req.getParameter("urealname");
String age = req.getParameter("uage");
String sex = req.getParameter("usex");

// 将信息封装进User
User user = new User();
user.setUname(uname);
user.setUpassword(upwd);
user.setUrealname(realName);
user.setUage(Integer.parseInt(age));
user.setUsex(Integer.parseInt(sex));

try {
// 将user信息存入数据库,并判断是否存入成功,只要返回不报错就成功
boolean boo = service.add(user);
if (boo) {
if ("reg".equals(type)) {
// 注册成功,跳转到登录页面
res.sendRedirect(req.getContextPath() + "/login.jsp");
} else {
// 为了跳到用户列表页面时显示数据,应该跳到用户查询servlet中执行查询方法
res.sendRedirect(req.getContextPath() + "/user");
}

}
} catch (UserExistException e) {
// 跳转回注册页面
req.setAttribute("message", e.getMessage());// 在request对象中加入名为message的属性并附值为e.getMessage())

} catch (Exception e) {
// 跳转到错误页面

}
}

public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {

doGet(req, res);
}

}

service业务逻辑层:

service:

实现类:

public interface IUserService {

public boolean add(User user);
public User getByName(String name);
public boolean existName(String name);
public User existUser(String name, String pwd);
public List<User> getAll();
public List<User> getByKey(String key);
public boolean delete(String uid) throws Exception;
public User findUserById(int id);
public boolean updateUser(User user);
}

service类

/**
*
*/
package com.qingmang.service;

import java.util.List;
import com.qingmang.dao.UserDao;
import com.qingmang.domain.User;
import com.qingmang.exception.UserExistException;
import com.qingmang.service.IService.IUserService;

/**
* @author administrator
*
*/
public class UserService implements IUserService{

// 声明并初始化UserDao
UserDao dao = new UserDao();

/*
* (non-Javadoc)
*
* @see
* com.qingmang.service.inter.IUserService#add(com.qingmang.domain.User)
*/
public boolean add(User user) {

if (existName(user.getUname()))
throw new UserExistException("该用户已经存在!");

return dao.add(user);
}

/*
* (non-Javadoc)
*
* @see com.qingmang.service.inter.IUserService#getByName(java.lang.String)
*/
public User getByName(String name) {
return dao.getByName(name);
}

/*
* (non-Javadoc) 判断用户名是否已经存在
*
* @see com.qingmang.service.inter.IUserService#existName(java.lang.String)
*/
public boolean existName(String name) {
boolean flag = false;
User user = getByName(name);
if (user != null)
flag = true;

return flag;
}

/*
* (non-Javadoc) 判断用户名密码是否正确
*
* @see com.qingmang.service.inter.IUserService#existUser(java.lang.String,
* java.lang.String)
*/
public User existUser(String name, String pwd) {

User user = getByName(name);
if (user != null && user.getUpassword().equals(pwd)) {
return user;
}

return null;
}

/*
* (non-Javadoc)
*
* @see com.qingmang.service.inter.IUserService#getAll()
*/
public List<User> getAll() {
return dao.getAll();
}

/*
* (non-Javadoc)
*
* @see com.qingmang.service.inter.IUserService#getByKey(java.lang.String)
*/
public List<User> getByKey(String key) {
return dao.getByKey(key);
}

public boolean delete(String uid) throws Exception {
return dao.delete(uid);
}

public User findUserById(int id) {
return dao.findUserById(id);

}

public boolean updateUser(User user) {

return dao.updateUser(user);

}

}

实现的Runtime异常类

/**
*
*/
package com.qingmang.exception;

/**
* @author administrator
*
*/
@SuppressWarnings("serial")
public class UserExistException extends RuntimeException{

/**
*
*/
public UserExistException() {
super();
// TODO Auto-generated constructor stub
}

/**
* @param message
* @param cause
*/
public UserExistException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}

/**
* @param message
*/
public UserExistException(String message) {
super(message);
// TODO Auto-generated constructor stub
}

/**
* @param cause
*/
public UserExistException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}

}

实体类:

/**
*
*/
package com.qingmang.domain;

import java.util.Date;

/**
* @author administrator
*
*/
public class User {

private int uid;
private String uname;
private String upassword;
private String urealname;
private int uage;
private int usex;
/**
*
*/
public User() {
super();
// TODO Auto-generated constructor stub
}
/**
* @param uid
* @param uname
* @param upassword
* @param urealname
* @param uage
* @param usex
*/
public User(int uid, String uname, String upassword, String urealname,
int uage, int usex) {
super();
this.uid = uid;
this.uname = uname;
this.upassword = upassword;
this.urealname = urealname;
this.uage = uage;
this.usex = usex;
}
/**
* @return the uid
*/
public int getUid() {
return uid;
}
/**
* @param uid the uid to set
*/
public void setUid(int uid) {
this.uid = uid;
}
/**
* @return the uname
*/
public String getUname() {
return uname;
}
/**
* @param uname the uname to set
*/
public void setUname(String uname) {
this.uname = uname;
}
/**
* @return the upassword
*/
public String getUpassword() {
return upassword;
}
/**
* @param upassword the upassword to set
*/
public void setUpassword(String upassword) {
this.upassword = upassword;
}
/**
* @return the urealname
*/
public String getUrealname() {
return urealname;
}
/**
* @param urealname the urealname to set
*/
public void setUrealname(String urealname) {
this.urealname = urealname;
}
/**
* @return the uage
*/
public int getUage() {
return uage;
}
/**
* @param uage the uage to set
*/
public void setUage(int uage) {
this.uage = uage;
}
/**
* @return the usex
*/
public int getUsex() {
return usex;
}
/**
* @param usex the usex to set
*/
public void setUsex(int usex) {
this.usex = usex;
}



}

数据持久层:dao 层

/**
*
*/
package com.qingmang.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.qingmang.domain.User;
import com.qingmang.utils.JdbcUtil;

/**
* @author administrator
*
*/
public class UserDao {

private Connection conn = null;// 初始化Connection连接对象,用于与数据库建立连接
private PreparedStatement pstmt = null;// 初始化向数据库发送预编译sql的PrepareSatement对象
private Statement stmt = null;// 初始化用于向数据库发送SQL的Statement对象
private ResultSet rs = null; // 初始化结果集对象

/*
* PreperedStatement可以避免SQL注入的问题。
* Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢出。PreparedStatement
* 可对SQL进行预编译,从而提高数据库的执行效率。
* 并且PreperedStatement对于sql中的参数,允许使用占位符的形式进行替换,简化sql语句的编写。
* 简单记:使用?传值的时候要使用预编译PreperedStatement对象
*/

/*
* (non-Javadoc) 用户添加方法
*
* @see com.qingmang.dao.inter.IUserDao#add(com.qingmang.domain.User)
*/
public boolean add(User user) {
boolean flag = false;// 初始化布尔类型对象值

try {

conn = JdbcUtil.getConnection();// 连接数据库
String sql = "INSERT INTO users " + "(uname,upassword,"
+ "urealname,uage,usex) " + "VALUES (?,?,?,?,?)";// 在数据库执行的sql语句
pstmt = conn.prepareStatement(sql);// 预编译sql语句;作用:将会大大降低运行时间,提高代码的可读性和可维护性
// 为sql语句中的?设置参数,第一个位置的?占位符为1;第2个?位置的占位符为2,其后为参数
pstmt.setString(1, user.getUname());
pstmt.setString(2, user.getUpassword());
pstmt.setString(3, user.getUrealname());
pstmt.setInt(4, user.getUage());
pstmt.setInt(5, user.getUsex());

int count = pstmt.executeUpdate();// 完成数据添加操作,并计数
if (count > 0)
flag = true;// 如果添加成功,返回true,跳出方法

} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
} finally {
try {
JdbcUtil.close(conn, pstmt);// 关闭连接
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
return flag;
}

/*
* (non-Javadoc) 根据用户名得到用户方法
*
* @see com.qingmang.dao.inter.IUserDao#getByName(java.lang.String)
*/
public User getByName(String uname) {
// 创建user的null
User user = null;
try {
conn = JdbcUtil.getConnection();
String sql = "select * from users where uname=?";
pstmt = conn.prepareStatement(sql);
// 设置参数
pstmt.setString(1, uname);

rs = pstmt.executeQuery();// 执行数据查询操作,并返回数据结果集
if (rs.next()) {
user = new User();// 新建User对象,以便之后将结果集中的数据封装进对象
user.setUname(rs.getString("uname"));
user.setUpassword(rs.getString("upassword"));
user.setUrealname(rs.getString("urealname"));
user.setUage(rs.getInt("uage"));
user.setUsex(rs.getInt("usex"));

}

} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
} finally {
try {
JdbcUtil.close(conn, pstmt);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}

return user;// 返回查询的对象
}

/*
* (non-Javadoc) 得到所有用户信息
*
* @see com.qingmang.dao.inter.IUserDao#getAll()
*/
public List<User> getAll() {

return getByKey(null);
}

/**
* 根据关键词查询用户
*
* @param key
* @return
*/
public List<User> getByKey(String key) {
List<User> list = new ArrayList<User>();
try {
conn = JdbcUtil.getConnection();// 连接数据库
String sql = "";
sql = "select * from users where 1=1";

/* 此处where 1=1 妙处在于在之后加条件时直接用and并列条件即可;也有一个在jsp页面多条件查询的方法,但需用到没学过的知识 */

if (key != null && !"".equals(key)) {
sql += " and uname like '" + key + "%'";
} // 加key值的null和""的判断,如果为空,则全部查询,若不为空,则按条件查询

stmt = conn.createStatement();// 创建用于向数据库发送SQL的Statement对象

rs = stmt.executeQuery(sql);// 执行sql语句的数据查询操作
while (rs.next()) {
User user = new User();

// 将数据封装进对象
user.setUid(rs.getInt("uid"));
user.setUname(rs.getString("uname"));
user.setUpassword(rs.getString("upassword"));
user.setUrealname(rs.getString("urealname"));
user.setUage(rs.getInt("uage"));
user.setUsex(rs.getInt("usex"));

list.add(user);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
try {
JdbcUtil.close(conn, pstmt, rs);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
return list;
}

/**
* 单条用户删除 是通过超链接方式,用post方式向servlet提交一个id, 依照这个id对数据库中的记录进行删除操作。
* */
// 执行静态的sql(delete)
public boolean delete(String uid) throws Exception {
boolean flag = false;
try {

conn = JdbcUtil.getConnection();// 连接数据库
stmt = conn.createStatement();// 得到Statement对象
String sql = "delete from users where uid='" + uid + "'";// 静态的sql语句
int count = stmt.executeUpdate(sql);// 执行sql语句
if (count >= 1) {
flag = true;
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
try {
JdbcUtil.close(conn, stmt);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
return flag;
}

/**
* 根据id得到用户
*
* @param id
* @return
*/
public User findUserById(int id) {

// 创建user的null
User user = null;
try {
conn = JdbcUtil.getConnection();
String sql = "select * from users where uid=?";
pstmt = conn.prepareStatement(sql);
// 设置参数
pstmt.setInt(1, id);

rs = pstmt.executeQuery();
if (rs.next()) {
user = new User();
user.setUname(rs.getString("uname"));
user.setUpassword(rs.getString("upassword"));
user.setUrealname(rs.getString("urealname"));
user.setUage(rs.getInt("uage"));
user.setUsex(rs.getInt("usex"));

}

} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
} finally {
try {
JdbcUtil.close(conn, pstmt);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}

return user;
}

/**
* 修改用户信息
*
* @param user
*/
public boolean updateUser(User user) {
boolean falg = false;
try {
conn = JdbcUtil.getConnection();
String sql = "update users set uname=?,upassword=?,urealname=?,uage=?,usex=? where uid=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user.getUname());
pstmt.setString(2, user.getUpassword());
pstmt.setString(3, user.getUrealname());
pstmt.setInt(4, user.getUage());
pstmt.setInt(5, user.getUsex());
pstmt.setInt(6, user.getUid());

pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
try {
JdbcUtil.close(conn, pstmt);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}

}
return falg;

}
}

连接数据库的工具类:

/**
*
*/
package com.qingmang.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

/**
* 自定义连接数据库工具类
* @author kh
*
*/
public class JdbcUtil {

private static String url = null;
private static String user = null;
private static String password = null;

static{
InputStream is = null;
try {
//File f = new File(".\\src\\mysql.properties");
//System.out.println(f.getAbsolutePath());
//is = new FileInputStream(f);
is = JdbcUtil.class.getResourceAsStream("/mysql.properties");
Properties pro = new Properties();
pro.load(is);

url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");

} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally{
if(is!=null)
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}

/**
* 得到数据库连接
* @return
* @throws Exception
*/
public static Connection getConnection() throws Exception{
Class.forName("com.mysql.jdbc.Driver");//加载数据库驱动类;由于注册过程在Driver类的静态类已经实现。
//也就是说只要类被加载,就完成了向驱动管理器的注册
return DriverManager.getConnection(url, user, password);//得到数据库连接
}

/**
* 关闭数据库连接
* @param conn
* @param stmt
* @param rs
*/
public static void close(Connection conn,Statement stmt,ResultSet rs){
if (rs != null)
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
if (stmt != null)
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
if (conn != null)
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}

/**
* 关闭数据库连接
* @param conn
* @param stmt
* @param rs
*/
public static void close(Connection conn,Statement stmt){
if (stmt != null)
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
if (conn != null)
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}

使用的properties:

url = jdbc\:mysql\://localhost\:3306/qingmang
user = root
password =root

使用jsp+servlet+mysql用户管理系统之用户注册-----------使用简单三层结构分析页面显示层(view),业务逻辑层(service),数据持久层(dao)的更多相关文章

  1. jsp+servlet+mysql 实现简单的银行登录转账功能

    jsp+servlet+mysql 实现简单的银行登录转账功能 [前期的准备] html(登录界面),servlet(处理业务逻辑),jsp(主要实现界面),mysql(实现与数据库的简单的交互)先从 ...

  2. jsp+servlet+mysql简单实现用户登陆注册

    原码,项目中遇到的错误,解决方法,文章最后有链接可以获取 项目简介 *有的网友说在修改和删除时会触发error,建议各位不要去把用户名命名为中文! 功能描述 登陆,注册,用户一览表,修改,删除,添加, ...

  3. (详细)Eclips+jsp+servlet+mysql+登录实例+源代码

    欢迎任何形式的转载,但请务必注明出处. 该教程较全,从软件的安装以及相关的环境配置我都放置了相关教程的链接,读者可直接点击进入.自己写电商网站作业时查找了很多资料,但都不是很全,所以趁着寒假写了这份教 ...

  4. jsp+servlet+mysql增删改查

    用的IntelliJ IDEA开发的,jdk1.8 1 首先是项目结构,如下图所示 2看各层的代码 首先是web.xml <?xml version="1.0" encodi ...

  5. 学生成绩管理系统3.0(JSP+Servlet+MySQL)

    源代码:戳这里! (2019-01-08 更新 惊讶于这么久了还有人看这个项目 于是把代码传到 github 了(辣鸡CSDN) https://github.com/G-lory/StudentAc ...

  6. jsp/servlet/mysql/linux基本概念和操作

    一.什么是OOP编程? 面向对象,以结果为导向,并封装整个过程,并尽可能地增加代码的复用性和可扩展性...... 二.Junit? JUnit是一个java语言的单元测试框架.Junit测试时程序员测 ...

  7. Jsp+servlet+mysql搭建套路

    1.建立数据库根据需求建立相应的数据库确立数据库的字段.属性.主键等2.建立javaweb项目,搭建开发环境在开发环境的/WebRoot/WEB-INF下建立lib文件夹,存放需要使用的jar包常用的 ...

  8. JSP+Servlet+mysql简单示例【图文教程】

    下载MYSQL:http://dev.mysql.com/downloads/ 下载安装版的 然后安装(安装步骤就不详细说了) 安装好之后,点击托盘图标,打开管理工具 创建一个数据库   数据库的名字 ...

  9. 基于JSP servlet mysql 的登陆页面

    数据库中建表: login.jsp <%@ page language="java" contentType="text/html; charset=UTF-8&q ...

  10. JSP+Servlet开发物流管理系统 源码

    开发环境: Windows操作系统开发工具:Myeclipse+Jdk+Tomcat+MYSQL数据库 运行效果图:

随机推荐

  1. ruby 常用代码片段

    # 文件的当前目录 puts __FILE__ # string.rb # 文件的当前行 puts __LINE__ # 6 #文件的当前目录 puts __dir__ #/media/haima/3 ...

  2. WEB服务与NGINX(16)-网站logo之favicon.ico文件

    目录 1. 网站logo之favicon.ico文件 1.1 favicon.ico文件的作用 1.2 favicon.ico文件带来的问题 1. 网站logo之favicon.ico文件 1.1 f ...

  3. Oracle中ALTER TABLE的五种用法(四、五)

    首发微信公众号:SQL数据库运维 原文链接:https://mp.weixin.qq.com/s?__biz=MzI1NTQyNzg3MQ==&mid=2247485212&idx=1 ...

  4. 🔥httpsok-v1.8.1 一分钟搞定SSL证书自动续期

    httpsok-v1.8.1 一分钟搞定SSL证书自动续期 简介 一行命令,一分钟轻松搞定SSL证书自动续期 httpsok 是一个便捷的 HTTPS 证书自动续签工具,专为 Nginx 服务器设计. ...

  5. 十三、.net core(.NET 6)搭建ElasticSearch(ES)系列之dotnet操作ElasticSearch进行存取的方法

    .net core操作ES进行读写数据操作 在Package包项目下,新增NEST包.注意,包版本需要和使用的ES的版本保持一致,可以避免因为不兼容所导致的一些问题.例如我本机使用的ES版本是7.13 ...

  6. Maven项目中整合SSH(pom.xml文件的配置详解)

    Maven项目中整合SSH比较繁琐,需要解决版本冲突问题,博主在下面给出了pom.xml文件的配置信息,改配置文件整合的是:struts2-2.3.24.spring4.2.4.hibernate5. ...

  7. .net core 5,6,7【多线程笔记】取消令牌(CancellationToken) CancellationTokenSource

    介绍 在使用C#异步的场景,多多少少会接触到CancellationTokenSource.它和取消异步任务相关的,CancellationToken就是它生产出来的. 演示 任务取消执行回调 var ...

  8. itest(爱测试) 4.5.7 发布,开源BUG 跟踪管理 & 敏捷测试管理&极简项目管理软件

    itest 简介 itest 开源敏捷测试管理,testOps 践行者,极简的任务管理,测试管理,缺陷管理,测试环境管理,接口测试5合1,又有丰富的统计分析.可按测试包分配测试用例执行,也可建测试迭代 ...

  9. echarts的示例跟做出来的不一样

    先给大家看下我做出来的和echarts官网做出来的 代码什么的都是一模一样但是颜色不一样 它字的颜色和柱状图颜色还一样不知道是不是脑子有猫病~ 上面是我做的  下面是官网的 主要是代码都是一样 我又不 ...

  10. Java中可以用的大数据推荐算法

    在Java中实现大数据推荐算法时,通常会使用一些开源的机器学习库,如Apache Mahout.Weka.DL4J(DeepLearning4j,用于深度学习)或者Spark MLlib(用于在Spa ...