新建项目,结构如下:
对于新建的项目,需要做一些基本配置,如果已经配置,略过,不会配置的详见:
JAVA WEB 学习笔记 Idea下常用配置-Hello Servlet。
新建数据库连接工具类:
/**
* 数据库连接工具类
* Created by Chao on 2016/12/3.
*/
public class DBUtils {
private static String driverClass;
private static String url;
private static String username;
private static String password;
static {
ResourceBundle bundle = ResourceBundle.getBundle("dbinfo");//加载文件
driverClass = bundle.getString("driverClass");
url = bundle.getString("url");
username = bundle.getString("username");
password = bundle.getString("password");
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//得到连接
public static Connection getConnection() throws Exception {
return DriverManager.getConnection(url, username, password);
}
//关闭资源
public static void closeAll(ResultSet rs, Statement stm, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if (stm != null) {
try {
stm.close();
} catch (SQLException e) {
e.printStackTrace();
}
stm = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
上面数据库连接信息,写在了配置文件里,附上文件:
编写一个登陆和一个注册的jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户注册</title>
</head>
<body>
<h2 style="color: red">新用户注册</h2>
${error}
<form action="/register" method="post">
账号:<input type="text" value="zhangzhichao" name="name"><br/>
密码:<input type="password" value="chaochao" name="pwd"><br/>
手机:<input type="text" value="13500000000" name="phone"><br/>
<input type="submit" value="注册"><br/>
</form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户登录</title>
</head>
<body>
<h2 style="color: red">登陆</h2>
${error}
<form action="/login" method="post">
账号:<input type="text" value="zhangzhichao" name="name"><br/>
密码:<input type="password" value="chaochao" name="pwd"><br/>
<input type="submit" value="登陆"><br/>
</form>
</body>
</html>
到这里页面编写已经完成,只需完成响应页面即可。
对了,这里先设计数据库和表,与上面的连接配置中的数据库名和表名一致。
下面编写在bean包名下的实体类,属性与数据库表对应:
/**
* 用户信息实体类
* Created by Chao on 2016/12/11.
*/
public class User implements Serializable {
private int id;
private String name;
private String pwd;
private String phone;
private Date date;
public User() {
//由于为了简便,我这里直接取当前时间作为创建用户时间,先进行赋值。
date = new Date();
}
public boolean validate() {
return true;
}
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 getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
在包名dao目录下新建接口:
/**
* Created by Chao on 2016/12/11.
*/
public interface UserDao {
/**
* 添加用户信息
*
* @param user
* @throws Exception
*/
public void addUser(User user) throws Exception;
/**
* 根据用户名和密码查找用户信息
*
* @param user
* @return
* @throws Exception
*/
public User findUser(User user) throws Exception;
/**
* 根据用户名查找用户是否存在
* @param name
* @return
*/
public boolean findUserByName(String name);
}
接下来daoimpl包名下新建类实现功能:
/**
* Created by Chao on 2016/12/11.
*/
public class UserDaoImpl implements UserDao {
/**
* 添加用户
*
* @param user
*/
@Override
public void addUser(User user) throws Exception {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = DBUtils.getConnection();
ps = conn.prepareStatement("INSERT INTO users(name,pwd,phone,DATE) VALUES(?,?,?,?)");
ps.setString(1, user.getName());
ps.setString(2, user.getPwd());
ps.setString(3, user.getPhone());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = sdf.format(user.getDate());
ps.setString(4, date);
int i = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("添加失败!");
} finally {
DBUtils.closeAll(null, ps, conn);
}
}
/**
* 查询用户
*
* @param user
* @return
* @throws Exception
*/
public User findUser(User user) throws Exception {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
User u = null;
try {
conn = DBUtils.getConnection();
ps = conn.prepareStatement("select * from users where name=? and pwd=?");
ps.setString(1, user.getName());
ps.setString(2, user.getPwd());
rs = ps.executeQuery();
if (rs.next()) {
u = new User();
u.setId(rs.getInt(1));
u.setName(rs.getString(2));
u.setPwd(rs.getString(3));
u.setPhone(rs.getString(4));
u.setDate(rs.getDate(5));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(rs, ps, conn);
}
return u;
}
public boolean findUserByName(String name) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DBUtils.getConnection();
ps = conn.prepareStatement("select * from users where name=?");
ps.setString(1, name);
rs = ps.executeQuery();
if (rs.next()) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(rs, ps, conn);
}
return false;
}
}
包名servlet包名下编写接口:
/**
* Created by Chao on 2016/12/11.
*/
public interface UserServlet {
/**
* 添加用户信息
*
* @param user
* @throws Exception
*/
public void register(User user) throws Exception;
/**
* 根据用户名和密码查找用户信息
*
* @param user
* @return
*/
public User login(User user) throws UsersException;
/**
* 根据用户名查找用户是否存在
* @return
* @throws UserExistException
*/
public boolean findUserByName(String name) throws UserExistException;
}
包名servletimpl实现接口:
public class UserServiceImpl implements UserServlet {
UserDao userDao = new UserDaoImpl();
public void register(User user) throws Exception {
userDao.addUser(user);
}
public User login(User user) {
User u = null;
try {
u = userDao.findUser(user);
} catch (Exception e) {
e.printStackTrace();
//写入日志
}
return u;
}
public boolean findUserByName(String name) throws UserExistException {
boolean b = userDao.findUserByName(name);
if(b){
throw new UserExistException("用户名已存在");
}
return b;
}
}
包名webservlet下编写登陆和注册响应服务:
/**
* Created by Chao on 2016/12/11.
*/
public class LoginServlet extends BaseHttpServlet {
@Override
public void httpAll(HttpServletRequest request, HttpServletResponse resp) throws IOException, ServletException {
super.httpAll(request, resp);
User user = new User();
try {
BeanUtils.populate(user, request.getParameterMap());
} catch (Exception e1) {
e1.printStackTrace();
}
UserServlet us = new UserServiceImpl();
User u;
try {
u = us.login(user);
//分发转向
if (u != null) {
request.getSession().setAttribute("u", user);//如果登录成功,就把user对象放到session对象 中
request.getRequestDispatcher("/index.jsp").forward(request, resp);
} else {
request.setAttribute("error", "登陆失败,请检查账号密码是否正确");
request.getRequestDispatcher("/login.jsp").forward(request, resp);
}
} catch (UsersException e) {
e.printStackTrace();
}
}
}
/**
* Created by Chao on 2016/12/11.
*/
public class RegServlet extends BaseHttpServlet {
@Override
public void httpAll(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
super.httpAll(request, response);
// 获取表单数据
// 验证操作
User uf = new User();
try {
BeanUtils.populate(uf, request.getParameterMap());
} catch (Exception e1) {
e1.printStackTrace();
}
if (!uf.validate()) {// 如果map中不为空,说明有错误信息
request.setAttribute("uf", uf);
request.getRequestDispatcher("/register.jsp").forward(request, response);
return;
}
User user = new User();
try {
/*
* ConvertUtils.register(new Converter() {//注册一个日期转换器
*
* public Object convert(Class type, Object value) { Date date1 =
* null; if(value instanceof String){ String date = (String) value;
* SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try {
* date1 = sdf.parse(date); } catch (ParseException e) {
* e.printStackTrace(); } } return date1; } }, Date.class);
*/
ConvertUtils.register(new DateLocaleConverter(), Date.class);
BeanUtils.populate(user, request.getParameterMap());
// 调用业务逻辑
UserServlet us = new UserServiceImpl();
//查看用户名是否已被注册
us.findUserByName(user.getName());
us.register(user);
} catch (UserExistException e) {
request.setAttribute("error", "用户名已存在");
request.getRequestDispatcher("/register.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
// 分发转向
response.getWriter().write("注册成功!1秒跳转到主页");
response.setHeader("refresh", "1;url=" + request.getContextPath()
+ "/login.jsp");
}
}
以上,项目已经可以运行,需要注意上面的异常,可以改成Exception,我为了测试继承Exception写了测试用的异常,请忽略。
整个项目结构如上:
上面有几个jar包,这里解释一下,到处都可以下载,我用这个版本比较老,上面3个jar包功能是:数据库连接jar包和bean映射jar包。
最后我们jsp页面配置的响应服务记得别忘了在xml里配置一下哦web.xml:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.chao.webservlet.LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>com.chao.webservlet.RegServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>register</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
</web-app>
对了,新建项目的index.jsp文件内容小改了一下,用于显示登陆成功用户名等操作,附上源码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主页</title>
</head>
<body>
欢迎您${u.name}
</body>
</html>
所有代码基本都贴出来了,为防有遗漏,稍后附上Demo地址。