欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JSP与Servlet

程序员文章站 2022-04-30 15:51:41
...

JSP代码:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>用户名</p>
<form action="../Login" method="GET">
<input type="text" name="username">
<input type="submit"  value="提交">

</form>

<a href="../Login">相对路径访问Servlet</a>

</body>
</html> 

 

Servlet代码:

package cn;

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

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 Login
 */
@WebServlet(name = "LoginServlet", urlPatterns = { "/LoginServlet" })
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//设置语言编码
	    response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//获得前台输入的账号密码
		String username = request.getParameter("username");
		//判断前台输入的账号密码是否正确 
		if("zhangsan".equals(username)){
			response.getWriter().print("<h1><font color='red'> 登录成功!</font></h1>");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 

web.xml文件配置Servlet代码段:

 <servlet> 
 <servlet-name>Login</servlet-name> 
 <servlet-class>cn.Login</servlet-class> 
 </servlet> 
 <servlet-mapping> 
 <servlet-name>Login</servlet-name> 
 <url-pattern>/Login</url-pattern> 
 </servlet-mapping>

这样就可以运行啦!