servlet向jsp传值

public class LoginServlet extends HttpServlet {
	int a=110;
	String userName;
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		userName=request.getParameter("userName");
		request.setAttribute("a", a);
		request.setAttribute("username", userName);
		request.getRequestDispatcher("first.jsp").forward(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		doGet(request, response);
	}

首先看提交到这个servlet的jsp表单

  
method="post"> 用户名 密码 忘记密码 用户注册

提交到这个servlet后,调用doPost()方法(同时我在post()方法中调用doGet()方法,这样的好处是不论之后的哪个action以什么样的形式请求servlet,都会调用两个方法)

servlet中声明两个变量a,和username;

userName=request.getParameter("userName");可以获取到请求页面中的标签名为"userName"的属性值
通过以下两个setAttribute()方法,可以将两个对象set到以request为生命周期的Attribute内置对象中,
request.setAttribute("a", a);
request.setAttribute("username", userName);

然后以

request.getRequestDispatcher("first.jsp").forward(request, response);进行跳转
这时我们在跳转的页面中便可以取值了
" />
" />
名字是:<%=request.getAttribute("username")%>

(实验过程中从jsp向servlet传值的时候出现了汉子乱码,试着在doPost方法或者doGet方法中进行request重新编码)

你可能感兴趣的:(java)