编写一个servlet,用注解方式创建两个参数,读取并输出这两个参数
时间: 2024-10-17 18:13:06 浏览: 30
在Servlet中,我们可以利用Java的注解技术简化配置,特别是Spring框架提供的`@ModelAttribute`和`@RequestParam`注解。下面是一个简单的例子,展示如何通过注解创建和获取两个请求参数:
```java
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = "/myServlet")
public class MyServlet extends HttpServlet {
// 使用@RequestParam注解读取请求参数
@ModelAttribute("param1")
public String getParam1(@RequestParam(value = "param1", defaultValue = "") String param1) {
return "Received param1: " + param1;
}
// 使用@ModelAttribute注解读取请求体数据(如果有POST请求)
@ModelAttribute("param2")
public String getParam2(HttpServletRequest request) throws IOException {
String param2 = request.getParameter("param2");
if (param2 == null) {
param2 = request.getInputStream().readUTF();
}
return "Received param2: " + param2;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取参数并输出
String param1Output = getParam1();
String param2Output = getParam2(request);
response.setContentType("text/plain");
response.getWriter().write("Parameter values:\n" + param1Output + "\n" + param2Output);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 对于POST请求,doPost方法会被调用
doGet(request, response);
}
}
```
在这个例子中,当用户发送GET或POST请求到"/myServlet"时,会自动从URL查询字符串或请求体中获取名为"param1"和"param2"的参数。然后在doGet或doPost方法中将它们输出。
阅读全文