本文中使用到的软件:
Tomcat 8.0
Mysql 5.7
IntelliJ IDEA 2019
项目实现流程:
-
在数据库中新建如下的数据表:
-
IDEA中新建一个项目,选中Web Application:
-
在src文件夹下新建如下所示的文件夹:
dao: 用于数据库操作
model: 用于创建web开发需要用到的类
service: 用于为model类提供服务方法
Servlet: 用于新建重写Servlet处理Http请求的方法
Utils: 用于编写一些工具类,例如建立数据库连接的类
在web文件夹下建立libs文件夹:
-
在Libs文件夹中导入以下两个jar包并右键点击 Add as Library:
-
点击右上角的Edit Configuration配置Tomcat
-
点击左上角的加号,选中Tomcat,选择local:
然后需要在Configuration中填入电脑中Tomcat的安装地址:
设置完成后如果出现Warning就点击Fix一下即可:
然后点击上方的Deployment,清空下方的内容(这部分会导致写出的网页带一个很长的后缀):
6. 然后就到了我们的编写代码环节了,编写的内容如下:
model.user:
//User.java
public class User {
private int id;
private String name;
private String password;
private int age;
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
}
dao.UserDao:
//UserDao.java
public class UserDao {
public User selectByName(String name){
ResultSet rs = null;
Connection connection = null;
PreparedStatement pstmt = null;
DBUtil dbUtil = new DBUtil();
User user = new User();
try {
connection = dbUtil.getConnection();
pstmt = connection.prepareStatement("select * from user where name=?");
pstmt.setString(1,name);
rs = pstmt.executeQuery();
while(rs.next()){
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setPassword(rs.getString(3));
user.setAge(rs.getInt(4));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
dbUtil.closeAll(rs,pstmt,connection);
}
return user;
}
public boolean InsertUser(String name,String password,int age){
Connection connection = null;
PreparedStatement pstmt = null;
try {
connection = DBUtil.getConnection();
pstmt = connection.prepareStatement("insert into user(name,password,age) values (?,?,?)");
pstmt.setString(1,name);
pstmt.setString(2,password);
pstmt.setInt(3,age);
pstmt.execute();
return true;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
Service.UserService:
//UserService
public class UserService {
UserDao userDao = new UserDao();
//查找用户
public User SelectByName(String name){
return userDao.selectByName(name);
}
//插入一个新用户
public boolean Register(String name,String password,int age){
return userDao.InsertUser(name,password,age);
}
}
ServLet.LoginServLet
//loginServLet.java
public class LoginServLet extends HttpServlet {
UserService userService = new UserService();
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如果点击的是登录按钮则获取数据
String name = req.getParameter("name");
String password = req.getParameter("password");
System.out.println("name:"+name);
User user = userService.SelectByName(name);
System.out.println(user);
//验证密码是否正确
if (password.equals(user.getPassword())) {
resp.getWriter().write("success");
System.out.println("success");
} else {
resp.getWriter().write("fail");
System.out.println("fail");
}
}
}
ServLet.RegisterServLet:
//RegisterServlet.java
public class RegisterServLet extends HttpServlet {
UserService userService = new UserService();
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如果点击了注册按钮则显示如下的HTML页面
PrintWriter out = resp.getWriter();
out.write("<html>\n" +
" <head>\n" +
" <meta http-equiv=\"content-type\" content=\"text/html;charset=gbk\" />\n"+
" <title>register</title>\n" +
" </head>\n" +
" <body>\n" +
" <H1>register</H1>\n" +
" <form action=\"/register\" method=\"post\">\n" +
" name:<input name=\"name\" type=\"text\">\n" +
" password:<input name=\"password\" type=\"password\">\n" +
" age:<input name=\"age\" type=\"text\">\n"+
" <input type=\"submit\" formaction=\"/registerSubmit\" value=\"register\">\n" +
" </form>\n" +
" </body>\n" +
"</html>");
}
}
ServLet.RegisterSubmitServLet:
//RegisterSubmitServLet.java
public class RegisterSubmitServLet extends HttpServlet {
UserService userService = new UserService();
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取注册界面数据并插入
String name = req.getParameter("name");
String password = req.getParameter("password");
String age = req.getParameter("age");
//int age = Integer.parseInt(req.getParameter("age"));
boolean re = userService.Register(name,password,Integer.valueOf(age));
System.out.println(name+password+age);
//String msg = lStrings.getString("http.method_post_not_supported");
if (re) {
resp.getWriter().write("success");
} else {
resp.getWriter().write("fail");
}
}
}
Utils.DBUtil:
//DBUtil.java
public class DBUtil {
public static Connection connection = null;
public static Connection getConnection() throws ClassNotFoundException, SQLException {
if(connection==null) {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false&autoReconnect=true&serverTimezone=GMT", "root", "hxh19981225");
return connection;
}else {
return connection;
}
}
public static void closeAll(ResultSet rs, Statement statement, Connection connection){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
- 接下来还需要编写Web文件夹下的index.jsp以及在WEB-INF中注册编写的ServLet:
index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录界面</title>
</head>
<body>
<H1>登录界面</H1>
<form action="/login" method="post">
name:<input name="name" type="text">
password:<input name="password" type="password">
<input type="submit" formaction="/login" value="登录">
<input type="submit" formaction="/register" value="注册">
</form>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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_4_0.xsd"
version="4.0">
<!-- 登录界面-->
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.huxiaoheng.ServLet.LoginServLet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<!-- 注册界面-->
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>com.huxiaoheng.ServLet.RegisterServLet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>register</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
<!-- 注册提交-->
<servlet>
<servlet-name>registerSubmit</servlet-name>
<servlet-class>com.huxiaoheng.ServLet.RegisterSubmitServLet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>registerSubmit</servlet-name>
<url-pattern>/registerSubmit</url-pattern>
</servlet-mapping>
</web-app>
这样我们的项目就算完成了,点击运行效果如图所示:
(没有写css,所以长得很抽象)
点击注册显示界面:
注册成功跳转到显示success界面:
可以在数据库查看到该条数据:
然后就可以登录该账号了:
没错因为懒得修改了所以 显示的内容和注册成功是一样的。不过还是可以通过地址看到它们导向的是不一样的地址~~,而且自己所学有限,实在是做不出其他不一样的页面~~
今日的Debug日记:
在写SQL插入语句的时候报错:
查阅之后发现,如果是插入,删除等语句对应的函数一个是execute()而非executeQuery()。另外返回值为一个布尔类型, 而且,不是插入成功就返回True,插入失败返回False。 而是如果第一个结果是 ResultSet 对象,则返回 true;如果第一个结果是更新计数或者没有结果,则返回 false。
好了这差不多是本文的全部内容了,超级简陋的登录界面!