从jsp页面提交数据到servlet页面问题

input.jsp

<%@ page language="java" contentType="text/html; charset=gb2312"
    pageEncoding="gb2312"%>




Insert title here


	
用户名
密码

此处值得注意的是action的值应该<%=request.getContextPath()%>/ShowServlet,其中<%=request.getContextPath()%>代表的是当前项目,/ShowServlet代表的是web.xml中配置的url-pattern。(表示之前不知道,找了很久……

ShowServlet.java

package com.cn.student;

import java.io.IOException;
import java.io.PrintWriter;

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

public class ShowServlet extends HttpServlet {
	PrintWriter pw = null;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("gb2312");
		resp.setContentType("text/html;charset=gb2312");
		pw = resp.getWriter();
		String name = req.getParameter("username");
		String pass = req.getParameter("pass");
		pw.println("你输入的用户名为:" + name);
		pw.println("
"); pw.println("你输入的密码为:" + pass); } }
web.xml配置如下



  MyDemo
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
  
  	ShowServlet
  	com.cn.student.ShowServlet
  
  
  	ShowServlet
  	/ShowServlet
  



你可能感兴趣的:(J2EE_Learning)