日期:2014-05-17 浏览次数:20833 次
package com.test.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.process(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.process(req, resp);
}
protected void process(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
//假设username=admin password="123"的时候才可以登录
if(username!=null && username.equals("admin") && password!=null && password.equals("123")){
req.getSession().setAttribute("username", username);//把username放到session里面
req.getRequestDispatcher("/welcome.jsp").forward(req, resp);
}else{
req.getRequestDispatcher("/error.jsp").include(req, resp);
}
}
}
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="login" method="post">
username:<input type="text" name="username"><br/>
password:<input type="password" name="password"><br/>
<input type="submit" value="commit">
</form>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC