web层交互数据库

  1. 1. 注册代码 RegistServlet.java
  2. 2. 登录代码 LoginServlet.java

注册代码 RegistServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.white.web;

import com.white.pojo.User;
import com.white.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegistServlet extends HttpServlet {

private UserServiceImpl userService = new UserServiceImpl();

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1.RegistServlet程序接受注册请求
String username = req.getParameter("username");
String password = req.getParameter("password");
String call = req.getParameter("tell");
String code = req.getParameter("code");

if("abcd".equalsIgnoreCase(code)){
if (userService.existsUsername(username)){
System.out.println("用户名["+username+"]已经存在!");
req.getRequestDispatcher("/pages/regist.html").forward(req,resp);//返回注册界面
//不可用
}else{
userService.registUser(new User(null,username,password,call));
System.out.println("注册成功");
System.out.println("用户名为["+username+"]欢迎");
req.getRequestDispatcher("/pages/regist_success.html").forward(req,resp);
}
// 2.检测验证码是否正确
// 3.检测用户名是否可用
}
else {
//调回注册页面
System.out.println("验证码错误["+ code +"]错误");
req.getRequestDispatcher("/pages/regist.html").forward(req,resp);
}

// 3.1可用 调用service保存到数据库
// 3.2不可用调回注册页面

}
}

登录代码 LoginServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.white.web;

import com.white.pojo.User;
import com.white.service.UserService;
import com.white.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
private UserService userService = new UserServiceImpl();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.获取请求
String username = req.getParameter("username");
String password = req.getParameter("password");
User loginUser = userService.login(new User(null,username,password,null));
//如果等于null,说明登录失败
if (loginUser == null){
//调回登录界面
System.out.println("登录失败");
req.getRequestDispatcher("/pages/login_false.html").forward(req,resp);

}
else
{
//登录成功
System.out.println("登录成功");
req.getRequestDispatcher("/pages/login_true.html").forward(req,resp);
}

// 2.调用service.xxx处理业务
// 3.login()方法返回处理结果判断是否成功
// 成功条到成功页面
// 失败返回登录界面
}
}