Home > front end >  A simple JSP achieve user login
A simple JSP achieve user login

Time:11-02

IndexServlet. JSP

<% @ page language="Java" contentType="text/HTML. Charset=utf-8 "
PageEncoding="utf-8" import="Java. IO. *" import="com. Liu. User" % & gt;


<meta HTTP - equiv="content-type" Content="text/HTML. Charset=utf-8 "& gt;
Insert the title here

<body>

<%
response.setContentType("text/html; charset=utf-8");

User User=(User) session. The getAttribute (" User ");
If (user==null) {
Response. GetWriter (). Print (" you have not login, please & lt; A href='https://bbs.csdn.net/topics/login.jsp' & gt; Login & lt;/a>" );
}
The else {
Response. GetWriter (). Print (" you have log in, you're welcome, "+ user. The getUsername () +"!" );
The response. GetWriter (). Print (" & lt; A href='https://bbs.csdn.net/topics/LogoutServlet.jsp' & gt; Exit & lt;/a>" );
Cookie Cookie=new Cookie (" JSESSIONID, "session. GetId ());
Cookies. SetMaxAge (60 * 30);
Cookies. SetPath ("/L ");
The response addCookie (cookies);
}


% & gt;






The login. The JSP

<% @ page language="Java" contentType="text/HTML. Charset=utf-8 "
PageEncoding="utf-8" % & gt;


<meta HTTP - equiv="content-type" Content="text/HTML. Charset=utf-8 "& gt;
Insert the title here

<body>
Name & lt; Input type="text" name="username"/& gt;
Password & lt; Input type="password" name="password"/& gt;






LoginServlet. JSP


<% @ page language="Java" contentType="text/HTML. Charset=utf-8 "
PageEncoding="utf-8" import="Java. IO. *" import="com. Liu. User" % & gt;


<meta HTTP - equiv="content-type" Content="text/HTML. Charset=utf-8 "& gt;
Insert the title here

<body>

<%
response.setContentType("text/html; charset=utf-8");
String username=request. The getParameter (" username ");
String password=request. The getParameter (" password ");
PrintWriter pw=response. GetWriter ();
If ((" luo ". The equals (username)) & amp; & (" 123456 "). The equals (password)) {
User User=new User ();
User. SetUsername (username);
The user. The setPassword (password);
Request. GetSession (). The setAttribute (" user ", the user);
Response. SendRedirect (" IndexServlet. JSP ");
} else {
Pw. Write (" user name or password error, login fails ");
}

% & gt;






LogoutServlet. JSP


<% @ page language="Java" contentType="text/HTML. Charset=utf-8 "
PageEncoding="utf-8" % & gt;


<meta HTTP - equiv="content-type" Content="text/HTML. Charset=utf-8 "& gt;
Insert the title here

<body>
<%
Request. GetSession (). RemoveAttribute (" user ");
Response. SendRedirect (" IndexServlet. JSP ");


% & gt;






User. Java


Package com. Liu;
Public class User {
private String username;
private String password;
Public String getUsername () {
Return the username.
}
Public void setUsername (String username) {
Enclosing the username=username;
}
Public String getPassword () {
Return the password;
}
Public void setPassword (String password) {
Enclosing the password=password;
}

}

  • Related