package demo.servlet;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.renren.api.client.RenrenApiConfig;
import demo.dao.UserDAO;
import demo.model.User;
/**
* 网站进行用户登录的界面
* @author Administrator
*
*/
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
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
String appId=RenrenApiConfig.renrenAppID;
String redirectUri=URLEncoder.encode("http://127.0.0.1/demo4web/rr_login", "UTF-8");
//"https://graph.renren.com/oauth/authorize"连接的参数如下:
StringBuffer params=new StringBuffer();
params.append("client_id=").append(appId);
params.append("&").append("response_type=").append("code");
params.append("&").append("redirect_uri=").append(redirectUri);
params.append("&").append("display=").append("page");
//操作的权限,根据具体需求自行选择
params.append("&").append("scope=").append("read_user_status,status_update,read_user_feed,publish_feed,photo_upload");
params.append("&").append("x_renew=").append("true"); //设置每次使用人人连接用户都需要登陆
request.setAttribute("params", params.toString());
RequestDispatcher welcomeDispatcher = request.getRequestDispatcher("/views/login.jsp");
welcomeDispatcher.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,
IOException {
// TODO Auto-generated method stub
String username = request.getParameter("username");
String password = request.getParameter("password");
if( username!=null && !"".equals(username) && password!=null && !"".equals(password) ){
User user = UserDAO.getInstance().getUser(username);
if (user != null) {
if (password.equals(user.getPassword())) {
//用户名和密码验证通过,将用户身份信息保存在会话中
request.getSession().setAttribute("user", user);
//已登录,跳转到个人主页
response.sendRedirect("profile");
return;
}
}
}
//没登录成功,跳转到登录页
response.sendRedirect("login");
}
}