赞
踩
servlet实质就是按servlet规范编写的Java类,可以处理web应用中的相关请求。
1、功能强大
1、角色不同
(使用注解开发、简单啊、那个配置的还有修改配置文件、烦的一批。不过也好弄、没有注解方便、哈哈哈)
注解开发只需要在java类的上面加上这句话@WebServlet("/My")
,括号里的内容自己命名、反斜杠一定要带上。前端怎样找到这个类就要用到这个括号里的内容。例如用from表单提交数据、这样写: <form action="My" method="post">
代码结构(使用的idea开发工具、maven项目)
前端三个页面
主页index
<%--
Created by IntelliJ IDEA.
User: 静小文
Date: 2021/12/19
Time: 22:40
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="My" method="post">
姓名:<input type="text" name="username"><br>
密码:<input type="text" name="password"><br>
<button type="submit">提交</button>
</form>
</body>
</html>
登录成功页面success.jsp
<%--
Created by IntelliJ IDEA.
User: 静小文
Date: 2021/12/19
Time: 22:57
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>成功</title>
</head>
<body>
登录成功!!!
<a href="index.jsp">首页</a>
</body>
</html>
登录失败页面error.jsp
<%--
Created by IntelliJ IDEA.
User: 静小文
Date: 2021/12/19
Time: 22:58
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>错误页面</title>
</head>
<body>
登录失败!!!
<a href="index.jsp">首页</a>
</body>
</html>
servlet
package com.zheng;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
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("/My")
public class MyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置请求的编码,防止中文乱码
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");//获取用户名
String password = request.getParameter("password");//获取用户名
if ("admin".equals(username) && "123".equals(password)) {
//模拟数据库
RequestDispatcher requestDispatcher = request.getRequestDispatcher("success.jsp");//跳转登录成功页面
requestDispatcher.forward(request, response);
} else {
RequestDispatcher requestDispatcher = request.getRequestDispatcher("error.jsp");//跳转登录成功页面
requestDispatcher.forward(request, response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
注意:通过doget方式提交、参数会在url地址栏中显示
测试
用户名和密码正确的情况
用户名和密码错误的情况
提示:如果IDEA中没有servlet选项,则在pom中添加以下依赖
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。