手记

简单的JSP跳转Servlet

JSP代码:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <a href="TranDatabyLinkServlet?username=zyq&password=test">测试</a>
</body>
</html>

Servlet代码:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class TranDatabyLinkServlet
 */
@WebServlet("/TranDatabyLinkServlet")
public class TranDatabyLinkServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public TranDatabyLinkServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Servlet#init(ServletConfig)
     */
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub
    }

    /**
     * @see Servlet#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
     */
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //设置请求的字符编码为UTF-8,以保证中文字符正常显示
        request.setCharacterEncoding("utf-8");
        //设置响应的文本类型为HTML,字符编码为UTF-8,以保证中文字符的正常显示
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //x响应输出用户请求的数据
        out.println("<p>请求的用户名是:"+username+"</p>");
        out.println("<p>请求的密码是:"+password+"</p>");
        out.flush();
        out.close();
    }
}

运行JSP:

跳转后页面:

跳转完成。

0人推荐
随时随地看视频
慕课网APP