js中如果id不为空使用get请求/user/updateUser,如果为空使用get请求/user/addUser
时间: 2023-10-09 09:16:18 浏览: 67
好的,我理解了你的问题。针对你的问题,我可以为你提供以下的代码示例:
```javascript
// 假设id为一个字符串变量
let url = '';
if (id) {
url = '/user/updateUser';
} else {
url = '/user/addUser';
}
// 发送GET请求
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
```
以上代码中,我们首先判断id是否存在,如果存在则使用`/user/updateUser`作为请求的URL,否则使用`/user/addUser`作为请求的URL,然后使用`fetch()`函数发送GET请求,并在成功或失败时打印响应数据或错误信息。注意,这里我们使用了`Content-Type: application/json`来设置请求头。
相关问题
@RequestMapping("/addUser") public ModelAndView addUser(String userName,String passWord,String gender,String email,String phone,String address){ User user = new User(); user.setUname(userName); user.setPassword(passWord); user.setGender(gender); user.setEmail(email); user.setPhone(phone); user.setAdress(address); userService.addUser(user); return new ModelAndView("redirect:/manaUser.do"); } @RequestMapping("/updateUserPage") public String updateUserPage(Model model,HttpSession session){ User sessionUser= (User) session.getAttribute("user"); User user=userService.findUserById(sessionUser.getUid()); model.addAttribute("user",user); return "front/update"; } @RequestMapping("/updateUser") public ModelAndView updateUser(Integer uid,String uname,String gender,String email,String phone,String address){ User user=new User(); user.setUid(uid); user.setUname(uname); user.setGender(gender); user.setEmail(email); user.setPhone(phone); user.setAdress(address); userService.userModify(user); return new ModelAndView("redirect:/index.do"); }解释这段代码
这是一段使用Spring MVC框架编写的Java Web应用程序的控制器代码,主要包含三个请求映射方法:
1. "/addUser":用于添加新用户,接收请求参数包括用户名、密码、性别、电子邮件、电话和地址,将这些信息封装成一个User对象,通过userService的addUser方法添加到数据库中,并重定向到"manaUser.do"页面。
2. "/updateUserPage":用于跳转到用户信息修改页面,接收一个Model对象和一个HttpSession对象,从session中获取当前用户的id,通过userService的findUserById方法获取该用户的信息,将这些信息封装成一个User对象,放入Model中,最后返回"front/update"页面。
3. "/updateUser":用于更新用户信息,接收请求参数包括用户id、用户名、性别、电子邮件、电话和地址,将这些信息封装成一个User对象,通过userService的userModify方法更新用户信息,并重定向到"index.do"页面。
新建数据库 UserDB,新建表 user,表结构如下: user 表 字段名称 字段类型 备注 id Int 用户编号(主键、自增) username Varchar(20) 用户名称 password Varchar(20) 用户密码通过 JDBC连接数据库,编写 userlist.jsp,显示所有用户信息编写 addUser.jsp,实现用户信息的添加功能,在 UserController.java这个 Servlet中实现用户信息的删除功能编写 userUpdate.jsp,实现用户信息的更新功能。
以下是实现上述要求的代码示例:
#### 1. 创建 UserDB 数据库和 user 表
```sql
CREATE DATABASE UserDB;
USE UserDB;
CREATE TABLE user (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(20),
password VARCHAR(20)
);
```
#### 2. 编写 userlist.jsp 显示所有用户信息
```jsp
<%@ page import="java.sql.*" %>
<%@ page language="java" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>User List</title>
</head>
<body>
<h1>User List</h1>
<%
String url = "jdbc:mysql://localhost:3306/UserDB";
String user = "root";
String password = "password";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
String sql = "SELECT * FROM user";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
%>
<table border="1">
<tr>
<th>ID</th>
<th>Username</th>
<th>Password</th>
</tr>
<% while (rs.next()) { %>
<tr>
<td><%= rs.getInt("id") %></td>
<td><%= rs.getString("username") %></td>
<td><%= rs.getString("password") %></td>
</tr>
<% } %>
</table>
<%
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
%>
</body>
</html>
```
#### 3. 编写 addUser.jsp 实现用户信息的添加功能
```jsp
<%@ page import="java.sql.*" %>
<%@ page language="java" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Add User</title>
</head>
<body>
<h1>Add User</h1>
<form method="post" action="UserController">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br>
<button type="submit">Add User</button>
</form>
</body>
</html>
```
#### 4. 在 UserController.java 这个 Servlet 中实现用户信息的删除功能
```java
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if (action == null) {
// do nothing
} else if (action.equals("add")) {
String username = request.getParameter("username");
String password = request.getParameter("password");
String url = "jdbc:mysql://localhost:3306/UserDB";
String user = "root";
String pass = "password";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, pass);
String sql = "INSERT INTO user (username, password) VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
pstmt.executeUpdate();
pstmt.close();
conn.close();
response.sendRedirect("userlist.jsp");
} catch (Exception e) {
e.printStackTrace();
}
} else if (action.equals("delete")) {
int id = Integer.parseInt(request.getParameter("id"));
String url = "jdbc:mysql://localhost:3306/UserDB";
String user = "root";
String pass = "password";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, pass);
String sql = "DELETE FROM user WHERE id=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
pstmt.executeUpdate();
pstmt.close();
conn.close();
response.sendRedirect("userlist.jsp");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
#### 5. 编写 userUpdate.jsp 实现用户信息的更新功能
```jsp
<%@ page import="java.sql.*" %>
<%@ page language="java" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Update User</title>
</head>
<body>
<h1>Update User</h1>
<%
int id = Integer.parseInt(request.getParameter("id"));
String url = "jdbc:mysql://localhost:3306/UserDB";
String user = "root";
String password = "password";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
String sql = "SELECT * FROM user WHERE id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
rs.next();
%>
<form method="post" action="UserController">
<input type="hidden" name="action" value="update">
<input type="hidden" name="id" value="<%= id %>">
<label for="username">Username:</label>
<input type="text" id="username" name="username" value="<%= rs.getString("username") %>" required><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" value="<%= rs.getString("password") %>" required><br>
<button type="submit">Update User</button>
</form>
<%
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
%>
</body>
</html>
```
以上就是实现用户信息增删改查的完整代码示例。注意在 web.xml 中配置 Servlet 映射。
阅读全文