JavaWeb6 Tomcat+postman请求,响应+常用注解整理
import org.apache.catalina.core.ApplicationContext;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.Tomcat.FixTriggered;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TomcatPostmanController {
@PostMapping("/postData")
public String postData(@RequestBody String data) {
return "Received POST data: " + data;
}
@GetMapping("/getData")
public String getData() {
return "Received GET request";
}
public static void main(String[] args) throws Exception {
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);
StandardContext ctx = (StandardContext) tomcat.addWebapp("/", new File("src/main/webapp").getAbsolutePath());
// 禁用JAR扫描
ctx.setJarScanning(StandardContext.JAR_SCAN_NONE);
// 设置应用的加载器为当前线程的ClassLoader
ctx.setLoader(new WebappLoader(Thread.currentThread().getContextClassLoader()));
// 将Spring应用上下文作为Servlet添加到Tomcat
Tomcat.addServlet(ctx, "dispatcher", new DispatcherServlet()).setLoadOnStartup(1);
ctx.addServletMappingDecoded("/", "dispatcher");
// 禁用SSL重定向
for (Connector con : tomcat.getService().findConnectors()) {
if (con.getProtocolHandler() instanceof AbstractHttp11Protocol<?>) {
((AbstractHttp11Protocol<?>) con.getProtocolHandler()).setRedirectPort(null);
}
}
// 添加安全约束,要求所有请求必须是HTTPS
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
ctx.addConstraint(securityConstraint);
tomcat.start();
tomcat.getServer().await();
}
}
这段代码演示了如何在Java中使用Spring框架的@RestController
注解创建一个简单的REST API,并使用Tomcat作为服务器。它还展示了如何通过Postman发送POST请求和接收响应。在main
方法中,我们配置了Tomcat服务器,并设置了应用的加载器和
评论已关闭