Servlet简单例子:模拟登入
需要做的事:html代码 + Servlet代码 + 运行操作
html代码:一个简陋的表单代码
要点:
- 给form添加action属性,属性值为:/动态web项目名/Servlet类名
- 给input添加name属性
- html文件要放到Web项目中的WebContent文件夹下
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>一个简单表单</title>
</head>
<body>
<!-- action赋值为:/动态web项目名/Servlet类名 -->
<form action="/Servlet_01/Submit_Servlet">
<div>
<label for="">用户名</label>
<!-- name属性通过submit提交给action对应的服务器 -->
<input type="text" name="userName">
</div>
<div>
<label for="">密码</label>
<input type="text" name="password">
</div>
<div>
<button type="button">取消</button>
<button type="submit">登入</button>
</div>
</form>
</body>
</html>
代码效果:
我的项目文件树如下:
Servlet代码
要点:
- 防止请求和回复因用中文而出现乱码,操作为以下两点
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset = utf-8");
- 获取容器中的参数
代码:
package case_01;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Submit_Servlet
*/
@WebServlet("/Submit_Servlet")
public class Submit_Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Submit_Servlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
// 以下两条语句防止输入中文出现乱码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset = utf-8");
// 用request的getParameter方法获取容器中的参数
String userName = request.getParameter("userName");
PrintWriter out = response.getWriter();
out.println("用户名:"+userName);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
运行操作
方法一:在eclipse中看效果
- 在html文件中鼠标右键选择 Run As 中的 Run on Server
- 在输入框中,输入用户名,密码,然后点击登入,服务器上就会出现用户名信息
方法二:在浏览器中查看效果,前提是Servlet已经部署
-
在浏览器中输入:http://localhost:8080/Servlet_01/html/form.html,格式为:http://localhost:8080/项目名/html位置
-
填入对应信息,点击登入