上机实现用户在inputUserName.jsp页面输入用户姓名提交给servlet,servlet将用户的请求再转发给showUserName.jsp页面。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>用户信息</title>
</head>
<body>
<form action="showServlet" method="post">
<p>用户名:<input type="text" name="username"></p>
<p><input type="submit" value="提交"></p>
</form> <br>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>显示用户名</title>
</head>
<body>
<p>用户名:<%=session.getAttribute("username") %></p>
</body>
</html>
<?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
" target="_blank">http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>showServlet</servlet-name>
<servlet-class>com.inspur.ch10.ShowServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>showServlet</servlet-name>
<url-pattern>/showServlet</url-pattern>
</servlet-mapping>
</web-app>
package com.inspur.ch10;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ShowServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws UnsupportedEncodingException,IOException {
String username = null;
username = new String(request.getParameter("username").getBytes(
"ISO-8859-1"), "UTF-8");
HttpSession session = request.getSession();
session.setAttribute("username", username);
response.sendRedirect(request.getContextPath()
+ "/showUserName.jsp");
}
}