编写一个servlet,发送请求参数是username,如果username是zhangsan那么转发到a.html;是lisi重定向到b.html;是wangwu弹框展示很好,到达c.html;是zhaoliu展示按钮到浏览器,按钮上展示zhaoliu;否则展示字符串你好到网页浏览器
时间: 2024-02-27 21:55:45 浏览: 45
好的,以下是代码实现:
```java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
if (username.equals("zhangsan")) {
request.getRequestDispatcher("/a.html").forward(request, response);
} else if (username.equals("lisi")) {
response.sendRedirect("/b.html");
} else if (username.equals("wangwu")) {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("<script>alert('很好');</script><a href='/c.html'>跳转到c.html</a>");
} else if (username.equals("zhaoliu")) {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("<input type='button' value='" + username + "' onclick='window.location.href=\"/d.html\"'>");
} else {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("你好");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
```
在web.xml中配置servlet:
```xml
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.example.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/myservlet</url-pattern>
</servlet-mapping>
```
这样,当访问/myservlet?username=zhangsan时,就会转发到a.html;访问/myservlet?username=lisi时,就会重定向到b.html;访问/myservlet?username=wangwu时,就会弹框展示“很好”,并跳转到c.html;访问/myservlet?username=zhaoliu时,就会展示一个按钮,点击按钮可以跳转到d.html,按钮上展示的是“zhaoliu”;其他情况下,就会展示字符串“你好”到浏览器。
阅读全文