Login. jsp
Code:
- <Body>
- <%
- String [] userinfo = {"",""};
- Cookie [] cookie = request. getcookies ();
- If (cookie! = NULL ){
- For (INT I = 0; I <cookie. length; I ++ ){
- If (cookie [I]. getname (). Equals ("logininfo ")){
- Userinfo = cookie [I]. getvalue (). Split ("#");
- }
- }
- }
- %>
- <Form action = "Servlet/login" method = "Post">
- Account: <input type = "text" class = "TXT" name = "username" value = <% = userinfo [0] %>/> <br/>
- Password: <input type = "password" class = "TXT" name = "password" value = <% = userinfo [1] %>/> <br/>
- Allow cookie writing: <input type = "radio" name = "agree" value = "yes" checked/> Yes <input type = "radio" name = "agree" value = "no"/> no <br/>
- <Input type = "Submit" value = "Submit"/> <input type = "reset" value = "cancel"/>
- </Form>
- </Body>
Dopost method in Servlet
If response. sendredirect (request. getcontextpath () + "/login. jsp") is used in the dopost method, null is always obtained in result. jsp.
That is to say, the value in the session is never obtained, and the solution has not been found online for a long time.
Code:
- Public void dopost (httpservletrequest request, httpservletresponse response)
- Throws servletexception, ioexception {
- Response. setcontenttype ("text/html ");
- Request. setcharacterencoding ("UTF-8 ");
- Response. setcharacterencoding ("UTF-8 ");
- String username = request. getparameter ("username ");
- String Password = request. getparameter ("password ");
- String agree = request. getparameter ("agree ");
- User u = new user ();
- U. setname (username );
- U. setpassword (password );
- Httpsession session = NULL;
- If (U. canpass ()){
- If (agree. Equals ("yes ")){
- Cookie mycookie = new cookie ("logininfo", username + "#" + password );
- Mycookie. setmaxage (60*60*24*7 );
- Response. addcookie (mycookie );
- Session = request. getsession ();
- Session. setattribute ("user", (User) U );
- }
- Servletcontext SC = getservletcontext ();
- Requestdispatcher RD = NULL;
- RD = SC. getrequestdispatcher ("/result. jsp"); // targeted page
- Rd. Forward (request, response );
- } Else {
- Response. sendredirect (request. getcontextpath () + "/login. jsp ");
- Return;
- }
- }
Result page
Code:
- <Body>
- <%
- User u = (User) Session. getattribute ("user ");
- System. Out. println (U );
- If (u = NULL ){
- U = new user ();
- U. setname ("");
- U. setpassword ("");
- }
- %>
- Current Login User information: Account (<% = U. getname () %>) password (<% = U. GetPassword () %>)
- </Body>