日期:2014-05-17  浏览次数:20695 次

无法从表单中把值传给servlet
form.htm
<form action="formServlet" method="post">
用户名:<input type="text" name="uname">
<input type="submit" value="提交">
</form>

FormServlet.java
package cn.mldn.lxh.servlet ;
import java.io.* ;
import javax.servlet.* ;
import javax.servlet.http.* ;

public class FormServlet extends HttpServlet
{
private ServletConfig config = null ;
public void init(ServletConfig config) throws ServletException 
{
this.config = config ;
}
// 表示处理get请求
public void doGet(HttpServletRequest req,HttpServletResponse resp) throws IOException,ServletException
{
this.doPost(req,resp) ;
}
// 处理post请求
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException,ServletException
{
String name = req.getParameter("uname") ;
// 取得application对象
ServletContext app = this.config.getServletContext() ;
app.setAttribute("addr","www.MLDN.cn") ;
// 取得一个session对象
HttpSession session = req.getSession() ;
session.setAttribute("sname",name) ;
 System.out.println("** Servlet doPost处理提交参数 ...") ;
System.out.println("name = "+name) ;
// 重定向
resp.sendRedirect("demo.jsp") ;
}
};

/*
  <servlet>
<servlet-name>form</servlet-name>
<servlet-class>cn.mldn.lxh.servlet.FormServlet</servlet-class>
  </servlet>
  <servlet-mapping>
<servlet-name>form</servlet-name>
<url-pattern>/formServlet</url-pattern>
  </servlet-mapping>
*/
demo.jsp
<h1><%=session.getAttribute("sname")%></h1>

<h1><%=getServletContext().getAttribute("addr")%></h1>
<h1><%=application.getAttribute("addr")%></h1>


tomcat已经启动
按提交以后地址栏转到:file:///C:/Program%20Files/Apache%20Software%20Foundation/Tomcat%207.0/webapps/daima/formServlet
servlet input session application

------解决方案--------------------
好像是你的重定向有点问题吧,要不试试加上全的路径 
如:resp.sendRedirect("../../demo.jsp") ;

// 重定向
resp.sendRedirect("demo.jsp") ;
------解决方案--------------------
你看看你form.htm页面上有没有下面这一段:如果没有加上
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>

然后再修改你的form

<form action="<%=basePath%>formServlet" method="post">
用户名:<input type="text" name="uname">
<input type="submit" value="提交">
</form>

------解决方案--------------------
你web.xml配置的没有问题 ,应该是Servlet这块代码有问题。
<