Servlet获取前端提交的参数

学好Servlet必须紧紧围绕着请求和响应这两个概念 以上写的代码只是进行请求,然后再响应到客户端。请求的时候没有带数据给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>
  • servlet实例

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);
    }
}
  • web.xml

   <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>

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值