javaweb-通过servlet获取请求参数

本文介绍如何获取请求参数
servlet容器在调用servlet时会传递请求对象ServletRequset给程序,只需要调用ServletRequset的方法getParameter()即可得到浏览器传递来的请求参数

1.编写servlet

/**
这里用到了一个User Bean,拥有4个属性.需要另外编写
*/
package org.zhwc.web.examples;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class exam1 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		User user = new User();
		request.setCharacterEncoding("utf-8");
		user.setUserID(request.getParameter("userID"));
		user.setUsername(request.getParameter("username"));
		user.setPassword(request.getParameter("password"));
		user.setRole(request.getParameter("role"));
		request.setAttribute("user", user);
//		response.sendRedirect(request.getContextPath()+"/userInfo.jsp");
		request.getRequestDispatcher("/userInfo.jsp").forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

2.在web.xml配置servlet

    获取表单信息
    exam1
    org.zhwc.web.examples.exam1
  

  
    exam1
    /servlet/exam1
  
3.编写测试页面
	userform.jsp
	主要代码:

    	
ID
名称
密码
角色

userInfo.jsp
    主要代码:

	用户ID: ${user.userID }
名称:${user.username }
密码:${user.password }
角色:${user.role }
4.在浏览器中访问userform.jsp可以看到效果
    程序通过以post方法提交参数,并且设置请求编码request.setCharacterEncoding("utf-8"); 解决中文乱码问题

你可能感兴趣的:(学习日志)