mapper Service servlet html 的代码demo
时间: 2024-03-25 20:41:42 浏览: 54
下面是一个简单的代码示例,演示了这些组件之间的关系:
1. Mapper示例:
```java
public interface UserMapper {
User findUserById(int id);
void insertUser(User user);
void updateUser(User user);
void deleteUser(int id);
}
```
2. Service示例:
```java
public interface UserService {
User getUserById(int id);
void addUser(User user);
void updateUser(User user);
void deleteUser(int id);
}
```
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(int id) {
return userMapper.findUserById(id);
}
@Override
public void addUser(User user) {
userMapper.insertUser(user);
}
@Override
public void updateUser(User user) {
userMapper.updateUser(user);
}
@Override
public void deleteUser(int id) {
userMapper.deleteUser(id);
}
}
```
3. Servlet示例:
```java
@WebServlet("/user/*")
public class UserServlet extends HttpServlet {
@Autowired
private UserService userService;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取请求参数
int userId = Integer.parseInt(request.getParameter("id"));
// 调用Service层方法
User user = userService.getUserById(userId);
// 将结果转换为JSON格式并返回给客户端
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(JSON.toJSONString(user));
}
}
```
4. HTML示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>User Info</title>
<meta charset="utf-8">
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h1>User Info</h1>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
<tbody id="userList">
</tbody>
</table>
<script>
$(document).ready(function(){
// 发送Ajax请求获取用户信息
$.ajax({
url: "/user?id=1",
type: "GET",
dataType: "json",
success: function(data){
// 将结果展示到HTML页面上
var tr = $("<tr></tr>");
tr.append("<td>" + data.id + "</td>");
tr.append("<td>" + data.name + "</td>");
tr.append("<td>" + data.age + "</td>");
tr.append("<td>" + data.gender + "</td>");
$("#userList").append(tr);
},
error: function(){
alert("获取用户信息失败");
}
});
});
</script>
</body>
</html>
```
以上示例仅供参考,实际开发中可能需要根据具体需求进行修改。
阅读全文