这里是JSP+DAO+Bean+Servlet四个技术实现MVC模式的简单用户登录与注册的攻略。我们使用MySQL作为数据库。
1. 创建数据库表
首先我们需要创建两个表:用户表和用户信息表。
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `t_user_info` (
`id` int(11) NOT NULL,
`realname` varchar(50) DEFAULT NULL,
`gender` varchar(10) DEFAULT NULL,
`birthday` date DEFAULT NULL,
`address` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `fk_id` FOREIGN KEY (`id`) REFERENCES `t_user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2. 编写Java Bean
我们需要针对用户表和用户信息表创建Java Bean。
public class User implements Serializable {
private int id;
private String username;
private String password;
private String email;
//getters and setters
}
public class UserInfo implements Serializable {
private int id;
private String realname;
private String gender;
private Date birthday;
private String address;
//getters and setters
}
3. 创建DAO层
DAO层负责处理数据库操作,主要包含增删改查。
public interface UserDao {
void addUser(User user);
void updateUser(User user);
void deleteUser(int id);
User getUserById(int id);
User getUserByUsername(String username);
List<User> getAllUsers();
}
public interface UserInfoDao {
void addUserInfo(UserInfo info);
void updateUserInfo(UserInfo info);
UserInfo getUserInfoById(int id);
}
使用JdbcTemplate工具类实现DAO层:
public class UserDaoImpl implements UserDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void addUser(User user) {
String sql = "insert into t_user (username,password,email) values (?,?,?)";
jdbcTemplate.update(sql,new Object[]{user.getUsername(),user.getPassword(),user.getEmail()});
}
public void updateUser(User user) {
String sql = "update t_user set username = ?,password = ?,email = ? where id = ?";
jdbcTemplate.update(sql,new Object[]{user.getUsername(),user.getPassword(),user.getEmail(),user.getId()});
}
public void deleteUser(int id) {
String sql = "delete from t_user where id = ?";
jdbcTemplate.update(sql,new Object[]{id});
}
public User getUserById(int id) {
String sql = "select * from t_user where id = ?";
List<User> userList = jdbcTemplate.query(sql, new Object[]{id}, new BeanPropertyRowMapper(User.class));
if(userList.isEmpty()){
return null;
}
return userList.get(0);
}
public User getUserByUsername(String username) {
String sql = "select * from t_user where username = ?";
List<User> userList = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper(User.class));
if(userList.isEmpty()){
return null;
}
return userList.get(0);
}
public List<User> getAllUsers() {
String sql = "select * from t_user";
return jdbcTemplate.query(sql, new BeanPropertyRowMapper(User.class));
}
}
public class UserInfoDaoImpl implements UserInfoDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void addUserInfo(UserInfo info) {
String sql = "insert into t_user_info (id,realname,gender,birthday,address) values (?,?,?,?,?)";
jdbcTemplate.update(sql,new Object[]{info.getId(),info.getRealname(),info.getGender(),info.getBirthday(),info.getAddress()});
}
public void updateUserInfo(UserInfo info) {
String sql = "update t_user_info set realname = ?,gender = ?,birthday = ?,address = ? where id = ?";
jdbcTemplate.update(sql,new Object[]{info.getRealname(),info.getGender(),info.getBirthday(),info.getAddress(),info.getId()});
}
public UserInfo getUserInfoById(int id) {
String sql = "select * from t_user_info where id = ?";
List<UserInfo> userInfoList = jdbcTemplate.query(sql, new Object[]{id}, new BeanPropertyRowMapper(UserInfo.class));
if(userInfoList.isEmpty()){
return null;
}
return userInfoList.get(0);
}
}
4. 编写Service层
Service层实现业务逻辑,调用DAO层进行增删改查。
public interface UserService {
void register(User user,UserInfo info);
User login(String username,String password);
}
public class UserServiceImpl implements UserService {
private UserDao userDao;
private UserInfoDao userInfoDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void setUserInfoDao(UserInfoDao userInfoDao) {
this.userInfoDao = userInfoDao;
}
public void register(User user, UserInfo info) {
userDao.addUser(user);
info.setId(user.getId());
userInfoDao.addUserInfo(info);
}
public User login(String username, String password) {
User user = userDao.getUserByUsername(username);
if(user == null){
return null;
}
if(!user.getPassword().equals(password)){
return null;
}
return user;
}
}
5. 编写Servlet层
Servlet层作为控制器,将请求转发给Service层处理。
public class RegisterServlet extends HttpServlet {
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/jsp/register.jsp").forward(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
String realname = request.getParameter("realname");
String gender = request.getParameter("gender");
String birthdayStr = request.getParameter("birthday");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date birthday = null;
try {
birthday = sdf.parse(birthdayStr);
} catch (ParseException e) {
e.printStackTrace();
}
String address = request.getParameter("address");
User user = new User();
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
UserInfo info = new UserInfo();
info.setRealname(realname);
info.setGender(gender);
info.setBirthday(birthday);
info.setAddress(address);
userService.register(user,info);
response.sendRedirect(request.getContextPath() + "/login.do");
}
}
public class LoginServlet extends HttpServlet {
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userService.login(username,password);
if(user != null){
request.getSession().setAttribute("user",user);
response.sendRedirect(request.getContextPath() + "/index.do");
}else {
request.setAttribute("errorMsg","用户名或密码错误");
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
}
}
}
6. 编写JSP页面
最后使用JSP页面展示页面。
<!--register.jsp-->
<form method="post" action="${pageContext.request.contextPath}/register.do">
<label>用户名:</label>
<input type="text" name="username" required><br>
<label>密码:</label>
<input type="password" name="password" required><br>
<label>确认密码:</label>
<input type="password" name="repassword" required><br>
<label>邮箱:</label>
<input type="email" name="email" required><br>
<label>真实姓名:</label>
<input type="text" name="realname" ><br>
<label>性别:</label>
<input type="radio" name="gender" value="男">男
<input type="radio" name="gender" value="女">女<br>
<label>生日:</label>
<input type="date" name="birthday" ><br>
<label>地址:</label>
<input type="text" name="address" ><br>
<input type="submit" value="注册">
</form>
<!--login.jsp-->
<form method="post" action="${pageContext.request.contextPath}/login.do">
<label>用户名:</label>
<input type="text" name="username" required><br>
<label>密码:</label>
<input type="password" name="password" required><br>
<input type="submit" value="登录">
</form>
以上是JSP+DAO+Bean+Servlet(MVC模式)实现简单用户登录和注册页面的完整攻略。下面是两条示例说明:
- 示例1:将用户对象传递给UserController的两个方法,获取用户列表和根据ID获取用户:
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/list")
public String list(Model model){
List<User> userList = userService.getAllUsers();
model.addAttribute("userList",userList);
return "user/list";
}
@RequestMapping("/get")
public String get(@RequestParam("id")int id,Model model){
User user = userService.getUserById(id);
model.addAttribute("user",user);
return "user/view";
}
}
- 示例2:通过注册http servlet将UserService依赖注入到注册servlet:
<bean id="userService" class="com.example.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
<property name="userInfoDao" ref="userInfoDao"/>
</bean>
<bean id="registerServlet" class="com.example.servlet.RegisterServlet">
<property name="userService" ref="userService"/>
</bean>
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:jsp+dao+bean+servlet(MVC模式)实现简单用户登录和注册页面 - Python技术站