Java Web 入门学习4:响应Response

响应Response

  • 修改servlet
  • 测试

Java Web 入门学习3:请求Request已经成功发送了get和post请求,本文介绍获取页面响应。

修改servlet

打开Testservlet.java,在doGet中添加代码

	response.setContentType("text/html;charset=utf-8");
	PrintWriter message = response.getWriter();
	message.write("欢迎您,"+username);

添加完成后代码如下

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	System.out.println("This is doGet");
	String username=request.getParameter("username1");
	String password=request.getParameter("password1");
	System.out.println("用户:"+username+",密码:"+password+",登录!");
		
	response.setContentType("text/html;charset=utf-8");//修改编码格式,避免中文乱码
	PrintWriter message = response.getWriter();
	message.write("欢迎您,"+username);
}

同样修改doPost方法,修改完成后

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	System.out.println("This is doPost");
	String username=request.getParameter("username2");
	String password=request.getParameter("password2");
	System.out.println("用户:"+username+",密码:"+password+",登录!");
		
	response.setContentType("text/html;charset=utf-8");
	PrintWriter message = response.getWriter();
	message.write("欢迎您,"+username);
}

测试

启动tomcat服务器,浏览器打开http://localhost:8080/mytestwebproject/Login.html
在这里插入图片描述
点击第一行的登录,get请求,获得响应信息
在这里插入图片描述
点击第二行的登录,post请求,获得响应信息
在这里插入图片描述

你可能感兴趣的:(Java,Web,java,web)