ssm用户注册功能,要求如果当前用户名不存在则注册成功重定向到登录页面,如果存在则重新注册代码
时间: 2023-08-22 20:24:43 浏览: 171
好的,以下是一个简单的实现示例代码,供您参考:
User.java(用户实体类):
```java
public class User {
private int id;
private String username;
private String password;
// 省略getter和setter方法
}
```
UserMapper.xml(MyBatis映射文件):
```xml
<!-- 查询用户名是否存在 -->
<select id="selectByUsername" resultType="int">
SELECT COUNT(*) FROM user WHERE username=#{username}
</select>
<!-- 插入用户信息 -->
<insert id="insertUser" parameterType="User">
INSERT INTO user (username, password) VALUES (#{username}, #{password})
</insert>
```
UserController.java(控制器):
```java
@Controller
public class UserController {
@Autowired
private UserService userService;
// 处理用户注册请求
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(User user, Model model) {
// 查询用户名是否已存在
int count = userService.selectByUsername(user.getUsername());
if (count > 0) {
// 用户名已存在,提示重新注册
model.addAttribute("msg", "用户名已存在,请重新注册!");
return "register";
} else {
// 用户名不存在,插入用户信息并重定向到登录页面
userService.insertUser(user);
return "redirect:/login";
}
}
}
```
UserService.java(服务层接口):
```java
public interface UserService {
// 查询用户名是否存在
int selectByUsername(String username);
// 插入用户信息
void insertUser(User user);
}
```
UserServiceImpl.java(服务层实现类):
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public int selectByUsername(String username) {
return userMapper.selectByUsername(username);
}
@Override
public void insertUser(User user) {
userMapper.insertUser(user);
}
}
```
register.jsp(注册页面):
```html
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>用户注册</title>
</head>
<body>
<h1>用户注册</h1>
<form action="${pageContext.request.contextPath}/register" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username" required></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password" required></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="注册">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
<p style="color:red">${msg}</p>
</body>
</html>
```
login.jsp(登录页面):
```html
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>用户登录</title>
</head>
<body>
<h1>用户登录</h1>
<form action="${pageContext.request.contextPath}/login" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username" required></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password" required></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="登录">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</body>
</html>
```
以上代码仅供参考,实际开发中还需要根据具体需求进行调整。
阅读全文