目录
学好Servlet必须紧紧围绕着请求和响应这两个概念。
下面开始写在请求的时候前端带数据到servlet里面,我们servlet要接收前端给我们的这个数据。
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="user/login" method="post">
<input type="text" name="username"/><br>
<input type="text" name="password"/><br>
<input type="submit" value="提交">
</form>
</body>
</html>
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//html页面中 input标签发送的数据,都会存到HttpServlet这个对象里面
//通过前端input标签name的属性值获取前端发送的数据
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username: " + username+"===password"+password);
//Servlet响应数据到客户端的时候,如果是中文的话,会乱码
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("username: " + user+"===password"+password);
}
}
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.by.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
结果:
//前端发送数据到Servlet,如果是post请求的话,input输入中文数据的时候,Servlet接到的数据是乱码的。
request.setCharacterEncoding("utf-8");
//Servlet响应数据到客户端的时候,如果是中文的话,会乱码
response.setContentType("text/html;charset=utf-8");