日期:2014-5-17 浏览次数:20386次

JSP页面和Servlet页面不在同一个目录下,JSP页面通过表单的action如何跳转到servlet页面
我的项目的名称是Exercise,然后在src目录下有一个包edu.zhang.servlet,这个包里存放了一个servlet页面,名称是verify,在webroot目录下,有一个文件夹叫chapter7,然后有两个JSP页面,一个是input.jsp,另一个是ShowMessage.jsp,现在通过input.jsp页面输入数据通关表单提交到verify这个servlet页面,通过这个servlet页面进行验证,通过就跳转到ShowMessage.jsp页面,不通过返回input.jsp。


input.jsp页面代码:
<%@ page language="java" import="java.util.*,edu.zhang.servlet.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body bgcolor="cyan"><font size=3>
  <form action="<%=path %>/src/edu/zhang/servlet/verify" method="post">
  <p>输入姓名:<input type="text" name="name">
  <br>输入年龄:<input type="text" name="age">
  <br><input type="submit" value="提交">
  </form>
  </font>
  </body>
</html>

verify代码:

package edu.zhang.servlet;

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 verify extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
String name=request.getParameter("name");
String age=request.getParameter("age");
try{
int age_number=Integer.parseInt(age);
if(name==""||age==""){
response.sendRedirect("input.jsp");
}else if(age_number>150||age_number<1){
response.sendRedirect("input.jsp");
}else{
RequestDispatcher dispatcher=request.getRequestDispatcher("Exercise/chapter7/ShowMessage.jsp");
dispatcher.forward(request, response);
}
}catch(Exception e){}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}


ShowMessage.jsp代码:

<%@ page language="java" import="java.util.*,edu.zhang.servlet.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
  <%
  String name=request.getParameter("name");
  String age=request.getParameter("age");
  %>
  <p>您的姓名是:<%=name %>
  <br>您的年龄是:<%=age %>
  </body>
</html>

web.xml文件内容是:


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
&n