// 假设您已经导入了 axios
import axios from 'axios';
// 获取表单元素
const form = document.getElementById('myForm');
// 为表单添加 submit 事件监听器
form.addEventListener('submit', function(e) {
// 阻止表单的默认提交行为
e.preventDefault();
// 创建 FormData 对象并从表单中获取数据
const formData = new FormData(form);
// 使用 axios 发送 POST 请求
axios.post('http://localhost:8080/untitled2_war_exploded/ser01', formData)
.then(response => {
// 请求成功时执行的代码
console.log('表单提交成功:', response.data);
// 这里可以添加代码处理服务器的响应,例如显示一个成功消息或跳转到另一个页面
alert('注册成功!');
})
.catch(error => {
// 请求失败时执行的代码
console.error('表单提交失败:', error);
// 这里可以添加代码处理错误,例如显示一个错误消息
alert('注册失败: ' + error.message);
});
});
当我使用表单默认提交方式才能使用axios.post的提交方式,当我们提交表单的按钮设置submit时就代表使用表单的按钮进行提交
如果我们给提交表的时候是使用自己蛇者的按钮(并且绑定监听事件的时候就不能使用这种形式,只能采用)
下面这种形式
axios({
url:"http://localhost:8080/untitled2_war_exploded/ser01",
method:"post",
params:{
username,email,password
}
}).then(response => {
// 请求成功时执行的代码
console.log('表单提交成功:', response.data);
})
.catch(error => {
// 请求失败时执行的代码
console.error('表单提交失败:', error);
});
设置编码格式
请求的设置格式
req.setCharacterEncoding("UTF-8");
回应的设置格式
resp.setContentType("text/html; charset=UTF-8");
package com.xxx.controller;
import com.xxx.controller.Param;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
/**
* @author 关岁安
*/
public abstract class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String methodName = request.getParameter("method");
if (methodName == null || methodName.isEmpty()) {
//返回404错误
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Method parameter is missing or empty");
return;
}
try {
System.out.println("方法名字:" + methodName);
Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
System.out.println("看看这里被执行到这里没?");
Parameter[] parameters = method.getParameters();
Object[] args = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
if (parameters[i].isAnnotationPresent(Param.class)) {
Param param = parameters[i].getAnnotation(Param.class);
String value = request.getParameter(param.value());
args[i] = value;
} else if (parameters[i].getType() == HttpServletRequest.class) {
args[i] = request;
} else if (parameters[i].getType() == HttpServletResponse.class) {
args[i] = response;
}
}
method.setAccessible(true);
method.invoke(this, args);
} catch (NoSuchMethodException e) {
//e.printStackTrace();
//返回500错误
//response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
System.out.println("拼写错误、方法参数类型不匹配");
}
catch (InvocationTargetException | IllegalAccessException e){
e.printStackTrace();
System.out.println("没有足够的权限,包装异常");
}
}
public abstract void register(@Param("username") String username, HttpServletRequest req, HttpServletResponse resp);
}
package com.xxx.controller;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author 关岁安
*
*/
@WebServlet("/Register")
public class RegisterController extends BaseServlet {
@Override
public void register(@Param("username") String username, HttpServletRequest req, HttpServletResponse resp) {
System.out.println("检测一下这个注册方法是否已经被执行");
// 注册逻辑
System.out.println("注册用户名: " + username + "看看是否已经获取到请求");
}
}
这里还有一个动态查询
重新实现了servlet那边的方法,按照发送的方式进行封装,如果是post方式就按照post来处理逻辑
如果是get请求就按照get方法来进行处理业务逻辑
这个相较于以前可以传送对象,和param数据,可接受的数据类型变得比以前更多
package com.xxx.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxx.annotation.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
/**
* @author 关岁安
*/
public abstract class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getQueryString();
request.setCharacterEncoding("UTF-8");
String uri = request.getRequestURI();
System.out.println(uri);
String methodName = new StringBuffer(uri.substring(uri.lastIndexOf("/") + 1)).toString();
Method method = null;
Method[] methods = this.getClass().getDeclaredMethods();
for (Method method1 : methods) {
if("POST".equals(request.getMethod())){
if(method1.getAnnotation(POST.class).value().equals(methodName)){
method = method1;
Parameter[] parameters = method.getParameters();
Object[] args = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
Annotation[] annotations = parameters[i].getAnnotations();
for (Annotation annotation : annotations) {
if(annotation instanceof Param){
String name = ((Param) annotation).value();
args[i] = request.getParameter(name);
}
else if(annotation instanceof Body){
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(request.getReader());
Object object = objectMapper.treeToValue(jsonNode, parameters[i].getType());
args[i] = object;
}
else {
if(parameters[i].getType() == HttpServletRequest.class){
args[i] = request;
}
else if(parameters[i].getType() == HttpServletResponse.class){
args[i] = response;
}
}
}
}
try {
method.invoke(this,args);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
else if("GET".equals(request.getMethod())){
if(method1.getAnnotation(GET.class).value().equals(methodName)){
method = method1;
Parameter[] parameters = method.getParameters();
Object[] args = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
Annotation[] annotations = parameters[i].getAnnotations();
for (Annotation annotation : annotations) {
if(annotation instanceof Param){
String name = ((Param) annotation).value();
args[i] = request.getParameter(name);
}
else if(annotation instanceof Body){
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(request.getReader());
Object object = objectMapper.treeToValue(jsonNode, parameters[i].getType());
args[i] = object;
}
else {
if(parameters[i].getType() == HttpServletRequest.class){
args[i] = request;
}
else if(parameters[i].getType() == HttpServletResponse.class){
args[i] = response;
}
}
}
}
try {
method.invoke(this,args);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
}
}
}