JAVA遇见HTML——Servlet篇:Servlet基础

 

 

 

 

 

 

 

 

 

代码实现:

HelloServlet
 1 package servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 //1.继承于HttpServlet
11 public class HelloServlet extends HttpServlet {
12 
13     @Override
14     protected void doGet(HttpServletRequest request, HttpServletResponse response)
15             throws ServletException, IOException {
16         // TODO Auto-generated method stub
17         System.out.println("处理Get()请求...");
18         //获得给浏览器输出的对象
19         PrintWriter out =response.getWriter();
20         //指定输出的文件类型,指定字符集
21         response.setContentType("text/html;charset=utf-8");
22         out.println("<strong>Hello Servlet!</strong><br>");//html代码
23     }
24 
25     @Override
26     protected void doPost(HttpServletRequest request, HttpServletResponse response)
27             throws ServletException, IOException {
28         // TODO Auto-generated method stub
29         System.out.println("处理Post()请求...");
30         //获得给浏览器输出的对象
31         PrintWriter out =response.getWriter();
32         //指定输出的文件类型,指定字符集
33         response.setContentType("text/html;charset=utf-8");
34         out.println("<strong>Hello Servlet!</strong><br>");//html代码
35     }
36 }

 

web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
 3   <display-name></display-name>
 4   <welcome-file-list>
 5     <welcome-file>index.jsp</welcome-file>
 6   </welcome-file-list>
 7   
 8   <servlet>
 9   <!-- servlet取个名字  -->
10     <servlet-name>HelloServlet</servlet-name>
11     <!-- 包名.类名 -->
12     <servlet-class>servlet.HelloServlet</servlet-class>    
13   </servlet>
14   
15   <servlet-mapping>
16     <servlet-name>HelloServlet</servlet-name>
17     <!-- 名字叫HelloServlet的servlet访问路径,和界面上写的超链接地址要一一对应   <a href="servlet/HelloServlet">Get方式请求HelloServlet</a>-->
18     <!-- 第一个/:项目的根目录或者当前web工程的根目录-->
19     <url-pattern>/servlet/HelloServlet</url-pattern>
20   </servlet-mapping>
21 </web-app>

index.jsp

 1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'index.jsp' starting page</title>
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="cache-control" content="no-cache">
15     <meta http-equiv="expires" content="0">    
16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
17     <meta http-equiv="description" content="This is my page">
18     <!--
19     <link rel="stylesheet" type="text/css" href="styles.css">
20     -->
21   </head>
22   
23   <body>
24   <h1>第一个Servlet小例子</h1>
25   <hr>
26   <!-- 超链接访问的就是Get请求 -->
27   <a href="servlet/HelloServlet">Get方式请求HelloServlet</a><br>
28   <!-- Post请求 -->
29   <form action="servlet/HelloServlet" method="post">
30       <input type="submit" value="Post方式请求HelloServlet"/>
31   </form>  
32   </body>
33 </html>

 

 

 

 1 package servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 public class HelloServlet extends HttpServlet {
12 
13     /**
14      * Constructor of the object.
15      */
16     public HelloServlet() {
17         super();
18     }
19 
20     /**
21      * Destruction of the servlet. <br>
22      */
23     public void destroy() {
24         super.destroy(); // Just puts "destroy" string in log
25         // Put your code here
26     }
27 
28     /**
29      * The doGet method of the servlet. <br>
30      *
31      * This method is called when a form has its tag value method equals to get.
32      * 
33      * @param request the request send by the client to the server
34      * @param response the response send by the server to the client
35      * @throws ServletException if an error occurred
36      * @throws IOException if an error occurred
37      */
38     public void doGet(HttpServletRequest request, HttpServletResponse response)
39             throws ServletException, IOException {
40         System.out.println("处理Get请求...");
41         
42         response.setContentType("text/html;charset=utf-8");
43         PrintWriter out = response.getWriter();
44         out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
45         out.println("<HTML>");
46         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
47         out.println("  <BODY>");
48         out.print("    This is ");
49         out.print(this.getClass());
50         out.println(", using the GET method");
51         out.println("<strong>Hello Servlet!</strong></br>");
52         out.println("  </BODY>");
53         out.println("</HTML>");
54         out.flush();
55         out.close();
56     }
57 
58     /**
59      * The doPost method of the servlet. <br>
60      *
61      * This method is called when a form has its tag value method equals to post.
62      * 
63      * @param request the request send by the client to the server
64      * @param response the response send by the server to the client
65      * @throws ServletException if an error occurred
66      * @throws IOException if an error occurred
67      */
68     public void doPost(HttpServletRequest request, HttpServletResponse response)
69             throws ServletException, IOException {
70         System.out.println("处理Post请求...");
71         
72         response.setContentType("text/html;charset=utf-8");
73         PrintWriter out = response.getWriter();
74         out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
75         out.println("<HTML>");
76         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
77         out.println("  <BODY>");
78         out.print("    This is ");
79         out.print(this.getClass());
80         out.println(", using the POST method");
81         out.println("<strong>Hello Servlet!</strong></br>");
82         out.println("  </BODY>");
83         out.println("</HTML>");
84         out.flush();
85         out.close();
86     }
87 
88     /**
89      * Initialization of the servlet. <br>
90      *
91      * @throws ServletException if an error occurs
92      */
93     public void init() throws ServletException {
94         // Put your code here
95     }
96 
97 }

web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5"
 3     xmlns="http://java.sun.com/xml/ns/javaee"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd">
 6   <servlet>
 7     <description>This is the description of my J2EE component</description>
 8     <display-name>This is the display name of my J2EE component</display-name>
 9     <servlet-name>HelloServlet</servlet-name>
10     <servlet-class>servlet.HelloServlet</servlet-class>
11   </servlet>
12 
13   <servlet-mapping>
14     <servlet-name>HelloServlet</servlet-name>
15     <url-pattern>/servlet/HelloServlet</url-pattern>
16   </servlet-mapping>
17   
18   <welcome-file-list>
19       <welcome>index.jsp</welcome>
20   </welcome-file-list>
21 
22 </web-app>

index.jsp

 1 <%@ page language="java" import="java.util.*" contentType="text/html;charset=utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'index.jsp' starting page</title>
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="cache-control" content="no-cache">
15     <meta http-equiv="expires" content="0">    
16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
17     <meta http-equiv="description" content="This is my page">
18     <!--
19     <link rel="stylesheet" type="text/css" href="styles.css">
20     -->
21   </head>
22   
23   <body>
24    <h1>使用MyEclipse创建Servlet小例子</h1>
25    <hr>
26    <a href="servlet/HelloServlet">Get方式请求HelloServlet</a><br>
27    <form action="servlet/HelloServlet" method="post">
28        <input type="submit" value="Post方式请求HelloServlet"/>
29    </form>
30   </body>
31 </html>

 

 

 

 

 

 

 

 

 

 

 

 

 

 1 package servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 public class TestServlet1 extends HttpServlet {
12 
13     /**
14      * Constructor of the object.
15      */
16     public TestServlet1() {
17         System.out.println("TestServlet1构造方法被执行...");
18     }
19 
20     /**
21      * Destruction of the servlet. <br>
22      */
23     public void destroy() {
24         System.out.println("TestServlet1销毁方法被执行...");
25     }
26 
27     /**
28      * The doGet method of the servlet. <br>
29      *
30      * This method is called when a form has its tag value method equals to get.
31      * 
32      * @param request the request send by the client to the server
33      * @param response the response send by the server to the client
34      * @throws ServletException if an error occurred
35      * @throws IOException if an error occurred
36      */
37     public void doGet(HttpServletRequest request, HttpServletResponse response)
38             throws ServletException, IOException {
39         
40         System.out.println("TestServlet1的doGet方法被执行...");
41         
42         response.setContentType("text/html;charset=utf-8");
43         PrintWriter out = response.getWriter();
44         out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
45         out.println("<HTML>");
46         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
47         out.println("  <BODY>");
48         out.print("    This is ");
49         out.print(this.getClass());
50         out.println(", using the GET method");
51         out.println("<h1>大家好,我是TestServlet1!</h1>");
52         out.println("  </BODY>");
53         out.println("</HTML>");
54         out.flush();
55         out.close();
56     }
57 
58     /**
59      * The doPost method of the servlet. <br>
60      *
61      * This method is called when a form has its tag value method equals to post.
62      * 
63      * @param request the request send by the client to the server
64      * @param response the response send by the server to the client
65      * @throws ServletException if an error occurred
66      * @throws IOException if an error occurred
67      */
68     public void doPost(HttpServletRequest request, HttpServletResponse response)
69             throws ServletException, IOException {
70 
71         System.out.println("TestServlet1的doPost方法被执行...");
72         doGet(request,response);//让doPost执行与doGet()相同的操作
73     }
74 
75     /**
76      * Initialization of the servlet. <br>
77      *
78      * @throws ServletException if an error occurs
79      */
80     public void init() throws ServletException {
81         System.out.println("TestServlet1初始化方法被执行...");
82     }
83 
84 }

 

package servlet;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet2 extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public TestServlet2() {
        System.out.println("TestServlet2构造方法被执行...");
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        System.out.println("TestServlet2销毁方法被执行...");
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        System.out.println("TestServlet2的doGet方法被执行...");
        
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the GET method");
        out.println("<h1>大家好,我是TestServlet2!</h1>");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("TestServlet2的doPost方法被执行...");
        doGet(request,response);//让doPost执行与doGet()相同的操作
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        System.out.println("TestServlet2初始化方法被执行...");
    }

}

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>TestServlet1</servlet-name>
    <servlet-class>servlet.TestServlet1</servlet-class>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>TestServlet2</servlet-name>
    <servlet-class>servlet.TestServlet2</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>


  <servlet-mapping>
    <servlet-name>TestServlet1</servlet-name>
    <url-pattern>/servlet/TestServlet1</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>TestServlet2</servlet-name>
    <url-pattern>/servlet/TestServlet2</url-pattern>
  </servlet-mapping>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

 1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'index.jsp' starting page</title>
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="cache-control" content="no-cache">
15     <meta http-equiv="expires" content="0">    
16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
17     <meta http-equiv="description" content="This is my page">
18     <!--
19     <link rel="stylesheet" type="text/css" href="styles.css">
20     -->
21   </head>
22   
23   <body>
24     <h1>Servlet生命周期</h1>
25     <a href="servlet/TestServlet1">以Get方式请求TestServlet1</a><br>
26     <a href="servlet/TestServlet2">以Get方式请求TestServlet2</a>
27   </body>
28 </html>

 

 

 

 

 

 1 package entity;
 2 
 3 import java.util.Date;
 4 
 5 public class Users {
 6 
 7     private String username;//用户名
 8     private String mypassword;//密码
 9     private String email;//电子邮箱
10     private String gender;//性别
11     private Date birthday;//出生日期
12     private String[] favorites;//爱好
13     private String introduce;//自我介绍
14     private boolean flag;//是否接受协议
15     
16     public Users()
17     {
18         
19     }
20 
21     public String getUsername() {
22         return username;
23     }
24 
25     public void setUsername(String username) {
26         this.username = username;
27     }
28 
29     public String getMypassword() {
30         return mypassword;
31     }
32 
33     public void setMypassword(String mypassword) {
34         this.mypassword = mypassword;
35     }
36 
37     public String getEmail() {
38         return email;
39     }
40 
41     public void setEmail(String email) {
42         this.email = email;
43     }
44 
45     public String getGender() {
46         return gender;
47     }
48 
49     public void setGender(String gender) {
50         this.gender = gender;
51     }
52 
53     public Date getBirthday() {
54         return birthday;
55     }
56 
57     public void setBirthday(Date birthday) {
58         this.birthday = birthday;
59     }
60 
61     public String[] getFavorites() {
62         return favorites;
63     }
64 
65     public void setFavorites(String[] favorites) {
66         this.favorites = favorites;
67     }
68 
69     public String getIntroduce() {
70         return introduce;
71     }
72 
73     public void setIntroduce(String introduce) {
74         this.introduce = introduce;
75     }
76 
77     public boolean isFlag() {
78         return flag;
79     }
80 
81     public void setFlag(boolean flag) {
82         this.flag = flag;
83     }
84     
85 }

 

  1 package servlet;
  2 
  3 import java.io.IOException;
  4 import java.io.PrintWriter;
  5 import java.text.ParseException;
  6 import java.text.SimpleDateFormat;
  7 import java.util.Date;
  8 
  9 import javax.servlet.ServletException;
 10 import javax.servlet.http.HttpServlet;
 11 import javax.servlet.http.HttpServletRequest;
 12 import javax.servlet.http.HttpServletResponse;
 13 
 14 import entity.Users;
 15 
 16 public class RegServlet extends HttpServlet {
 17 
 18     /**
 19      * Constructor of the object.
 20      */
 21     public RegServlet() {
 22         super();
 23     }
 24 
 25     /**
 26      * Destruction of the servlet. <br>
 27      */
 28     public void destroy() {
 29         super.destroy(); // Just puts "destroy" string in log
 30         // Put your code here
 31     }
 32 
 33     /**
 34      * The doGet method of the servlet. <br>
 35      *
 36      * This method is called when a form has its tag value method equals to get.
 37      * 
 38      * @param request the request send by the client to the server
 39      * @param response the response send by the server to the client
 40      * @throws ServletException if an error occurred
 41      * @throws IOException if an error occurred
 42      */
 43     public void doGet(HttpServletRequest request, HttpServletResponse response)
 44             throws ServletException, IOException {
 45 
 46         doPost(request,response);
 47     }
 48 
 49     /**
 50      * The doPost method of the servlet. <br>
 51      *
 52      * This method is called when a form has its tag value method equals to post.
 53      * 
 54      * @param request the request send by the client to the server
 55      * @param response the response send by the server to the client
 56      * @throws ServletException if an error occurred
 57      * @throws IOException if an error occurred
 58      */
 59     public void doPost(HttpServletRequest request, HttpServletResponse response)
 60             throws ServletException, IOException {
 61 
 62         request.setCharacterEncoding("utf-8");
 63         
 64         Users u = new Users();
 65         String username,mypassword,gender,email,introduce,isAccept;
 66         Date birthday;
 67         String[] favorites;
 68         
 69         SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
 70         try 
 71         {
 72             username = request.getParameter("username");//返回指定参数的参数值
 73             mypassword = request.getParameter("mypassword");
 74             gender = request.getParameter("gender");
 75             email = request.getParameter("email");
 76             introduce = request.getParameter("introduce");
 77             birthday = sdf.parse(request.getParameter("birthday"));//sdf.parse() 解析字符串的文本,生成 Date。
 78             if(request.getParameterValues("isAccept")!=null)
 79             {
 80                 isAccept=request.getParameter("isAccept");
 81             }
 82             else
 83             {
 84                 isAccept="false";
 85             }
 86             //用来获取多个复选按钮的值
 87             favorites = request.getParameterValues("favorite");
 88             
 89             u.setUsername(username);
 90             u.setMypassword(mypassword);
 91             u.setGender(gender);
 92             u.setEmail(email);
 93             u.setFavorites(favorites);
 94             u.setIntroduce(introduce);
 95             
 96             if(isAccept.equals("true"))
 97             {
 98                 u.setFlag(true);
 99             }
100             else
101             {
102                 u.setFlag(false);
103             }
104             u.setBirthday(birthday);
105             //把注册成功的用户对象保存在session中
106             request.getSession().setAttribute("regUser", u);//存储此请求中的属性
107             //跳转到注册成功页面
108             request.getRequestDispatcher("../userinfo.jsp").forward(request, response);//跳转到外层目录userinfo.jsp
109         } catch (Exception ex) {
110             // TODO Auto-generated catch block
111             ex.printStackTrace();
112         }
113     }
114 
115     /**
116      * Initialization of the servlet. <br>
117      *
118      * @throws ServletException if an error occurs
119      */
120     public void init() throws ServletException {
121         // Put your code here
122     }
123 
124 }

web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5" 
 3     xmlns="http://java.sun.com/xml/ns/javaee" 
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 7   <display-name></display-name>
 8   <servlet>
 9     <description>This is the description of my J2EE component</description>
10     <display-name>This is the display name of my J2EE component</display-name>
11     <servlet-name>RegServlet</servlet-name>
12     <servlet-class>servlet.RegServlet</servlet-class>
13   </servlet>
14 
15   <servlet-mapping>
16     <servlet-name>RegServlet</servlet-name>
17     <url-pattern>/servlet/RegServlet</url-pattern>
18   </servlet-mapping>    
19   <welcome-file-list>
20     <welcome-file>index.jsp</welcome-file>
21   </welcome-file-list>
22 </web-app>

注册页面reg.jsp

  1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
  2 <%
  3 String path = request.getContextPath();
  4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  5 %>
  6 
  7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  8 <html>
  9   <head>
 10     <base href="<%=basePath%>">
 11     
 12     <title>My JSP 'reg.jsp' starting page</title>
 13     
 14     <meta http-equiv="pragma" content="no-cache">
 15     <meta http-equiv="cache-control" content="no-cache">
 16     <meta http-equiv="expires" content="0">    
 17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 18     <meta http-equiv="description" content="This is my page">
 19     <!--
 20     <link rel="stylesheet" type="text/css" href="styles.css">
 21     -->
 22     <style type="text/css">
 23      .label{
 24           width: 20%    
 25      }
 26      .controler{
 27           width: 80%    
 28      }
 29    </style>  
 30    <script type="text/javascript" src="js/Calendar3.js"></script>
 31   </head>
 32   
 33   <body>
 34     <h1>用户注册</h1>
 35     <hr>
 36     <form name="regForm" action="servlet/RegServlet" method="post" >
 37               <table border="0" width="800" cellspacing="0" cellpadding="0">
 38                 <tr>
 39                     <td class="lalel">用户名:</td>
 40                     <td class="controler"><input type="text" name="username" /></td>
 41                 </tr>
 42                 <tr>
 43                     <td class="label">密码:</td>
 44                     <td class="controler"><input type="password" name="mypassword" ></td>
 45                     
 46                 </tr>
 47                 <tr>
 48                     <td class="label">确认密码:</td>
 49                     <td class="controler"><input type="password" name="confirmpass" ></td>
 50                     
 51                 </tr>
 52                 <tr>
 53                     <td class="label">电子邮箱:</td>
 54                     <td class="controler"><input type="text" name="email" ></td>
 55                     
 56                 </tr>
 57                 <tr>
 58                     <td class="label">性别:</td>
 59                     <td class="controler"><input type="radio" name="gender" checked="checked" value="Male">男<input type="radio" name="gender" value="Female">女</td>
 60                     
 61                 </tr>
 62                
 63                 <tr>
 64                     <td class="label">出生日期:</td>
 65                     <td class="controler">
 66                       <input name="birthday" type="text" id="control_date" size="10"
 67                       maxlength="10" onclick="new Calendar().show(this);" readonly="readonly" />
 68                     </td>
 69                 </tr>
 70                 <tr>
 71                     <td class="label">爱好:</td>
 72                     <td class="controler">
 73                     <input type="checkbox" name="favorite" value="nba"> NBA &nbsp;
 74                       <input type="checkbox" name="favorite" value="music"> 音乐 &nbsp;
 75                       <input type="checkbox" name="favorite" value="movie"> 电影 &nbsp;
 76                       <input type="checkbox" name="favorite" value="internet"> 上网 &nbsp;
 77                     </td>
 78                 </tr>
 79                 <tr>
 80                     <td class="label">自我介绍:</td>
 81                     <td class="controler">
 82                         <textarea name="introduce" rows="10" cols="40"></textarea>
 83                     </td>
 84                 </tr>
 85                 <tr>
 86                     <td class="label">接受协议:</td>
 87                     <td class="controler">
 88                         <input type="checkbox" name="isAccept" value="true">是否接受霸王条款
 89                     </td>
 90                 </tr>
 91                 <tr>
 92                     <td colspan="2" align="center">
 93                         <input type="submit" value="注册"/>&nbsp;&nbsp;
 94                         <input type="reset" value="取消"/>&nbsp;&nbsp;
 95                     </td>
 96                 </tr>
 97               </table>
 98             </form>
 99   </body>
100 </html>

注册成功页面userinfo.jsp

 1 <%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=utf-8"%>
 2 
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7 
 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 9 <html>
10   <head>
11     <base href="<%=basePath%>">
12     
13     <title>My JSP 'userinfo.jsp' starting page</title>
14     
15     <meta http-equiv="pragma" content="no-cache">
16     <meta http-equiv="cache-control" content="no-cache">
17     <meta http-equiv="expires" content="0">    
18     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
19     <meta http-equiv="description" content="This is my page">
20     <!--
21     <link rel="stylesheet" type="text/css" href="styles.css">
22     -->
23     <style type="text/css">
24      .title{
25          width: 30%;    
26          background-color: #CCC;
27          font-weight: bold;
28      }
29      .content{
30          width:70%;
31          background-color: #CBCFE5;
32      }
33      
34    </style>  
35   </head>
36   
37   <body>
38     <h1>用户信息</h1>
39     <hr>
40     <center>
41      <jsp:useBean  id="regUser" class="entity.Users" scope="session"/>   
42      <table width="600" cellpadding="0" cellspacing="0" border="1">
43         <tr>
44           <td class="title">用户名:</td>
45           <td class="content">&nbsp;<jsp:getProperty name="regUser" property="username"/></td>
46         </tr>
47         <tr>
48           <td class="title">密码:</td>
49           <td class="content">&nbsp;<jsp:getProperty name="regUser" property="mypassword"/></td>
50         </tr>
51         <tr>
52           <td class="title">性别:</td>
53           <td class="content">&nbsp;<jsp:getProperty name="regUser" property="gender"/></td>
54         </tr>
55         <tr>
56           <td class="title">E-mail:</td>
57           <td class="content">&nbsp;<jsp:getProperty name="regUser" property="email"/></td>
58         </tr>
59         <tr>
60           <td class="title">出生日期:</td>
61           <td class="content">&nbsp;
62             <% 
63                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
64                String date = sdf.format(regUser.getBirthday());
65                
66             %>
67              <%=date%>
68           </td>
69         </tr>
70         <tr>
71           <td class="title">爱好:</td>
72           <td class="content">&nbsp;
73             <% 
74                String[] favorites = regUser.getFavorites();
75                for(String f:favorites)
76                {
77             %>
78                 <%=f%> &nbsp;&nbsp;
79             <% 
80                }
81             %>
82           </td>
83         </tr>
84         <tr>
85           <td class="title">自我介绍:</td>
86           <td class="content">&nbsp;<jsp:getProperty name="regUser" property="introduce"/></td>
87         </tr>
88         <tr>
89           <td class="title">是否介绍协议:</td>
90           <td class="content">&nbsp;<jsp:getProperty name="regUser" property="flag"/></td>
91         </tr>
92      </table>
93     </center>
94   </body>
95 </html>

 

 

 

 

 

 

 

 1 package servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 public class HelloServlet extends HttpServlet {
12 
13     /**
14      * Constructor of the object.
15      */
16     public HelloServlet() {
17         super();
18     }
19 
20     /**
21      * Destruction of the servlet. <br>
22      */
23     public void destroy() {
24         super.destroy(); // Just puts "destroy" string in log
25         // Put your code here
26     }
27 
28     /**
29      * The doGet method of the servlet. <br>
30      *
31      * This method is called when a form has its tag value method equals to get.
32      * 
33      * @param request the request send by the client to the server
34      * @param response the response send by the server to the client
35      * @throws ServletException if an error occurred
36      * @throws IOException if an error occurred
37      */
38     public void doGet(HttpServletRequest request, HttpServletResponse response)
39             throws ServletException, IOException {
40 
41         doPost(request,response);
42     }
43 
44     /**
45      * The doPost method of the servlet. <br>
46      *
47      * This method is called when a form has its tag value method equals to post.
48      * 
49      * @param request the request send by the client to the server
50      * @param response the response send by the server to the client
51      * @throws ServletException if an error occurred
52      * @throws IOException if an error occurred
53      */
54     public void doPost(HttpServletRequest request, HttpServletResponse response)
55             throws ServletException, IOException {
56 
57         response.setContentType("text/html;charset=utf-8");
58         PrintWriter out = response.getWriter();
59         out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
60         out.println("<HTML>");
61         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
62         out.println("  <BODY>");
63         out.print("    This is ");
64         out.print(this.getClass());
65         out.println(", using the POST method");
66         out.println("<h1>您好,我是HelloServlet!</h1>");
67         out.println("  </BODY>");
68         out.println("</HTML>");
69         out.flush();
70         out.close();
71     }
72 
73     /**
74      * Initialization of the servlet. <br>
75      *
76      * @throws ServletException if an error occurs
77      */
78     public void init() throws ServletException {
79         // Put your code here
80     }
81 
82 }

 

 1 package servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 public class TestServlet extends HttpServlet {
12 
13     /**
14      * Constructor of the object.
15      */
16     public TestServlet() {
17         super();
18     }
19 
20     /**
21      * Destruction of the servlet. <br>
22      */
23     public void destroy() {
24         super.destroy(); // Just puts "destroy" string in log
25         // Put your code here
26     }
27 
28     /**
29      * The doGet method of the servlet. <br>
30      *
31      * This method is called when a form has its tag value method equals to get.
32      * 
33      * @param request the request send by the client to the server
34      * @param response the response send by the server to the client
35      * @throws ServletException if an error occurred
36      * @throws IOException if an error occurred
37      */
38     public void doGet(HttpServletRequest request, HttpServletResponse response)
39             throws ServletException, IOException {
40 
41         doPost(request,response);
42     }
43 
44     /**
45      * The doPost method of the servlet. <br>
46      *
47      * This method is called when a form has its tag value method equals to post.
48      * 
49      * @param request the request send by the client to the server
50      * @param response the response send by the server to the client
51      * @throws ServletException if an error occurred
52      * @throws IOException if an error occurred
53      */
54     public void doPost(HttpServletRequest request, HttpServletResponse response)
55             throws ServletException, IOException {
56 
57         //请求重定向方式跳转到test.jsp,当前路径是ServletPathDirection/servlet/
58         response.sendRedirect("test.jsp");//404错误
59 //        response.sendRedirect("/test.jsp");//404错误
60         //使用request.getContext获得上下文对象
61 //        response.sendRedirect(request.getContextPath()+"/test.jsp");
62         
63         
64         
65         //服务器内部跳转,这里的斜线表示项目的根目录
66 //        request.getRequestDispatcher("/test.jsp").forward(request, response);
67 //        request.getRequestDispatcher("../test.jsp").forward(request, response);
68         
69     }
70 
71     /**
72      * Initialization of the servlet. <br>
73      *
74      * @throws ServletException if an error occurs
75      */
76     public void init() throws ServletException {
77         // Put your code here
78     }
79 
80 }

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>servlet.HelloServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>servlet.TestServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/servlet/HelloServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>TestServlet</servlet-name>
    <url-pattern>/servlet/TestServlet</url-pattern>
  </servlet-mapping>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

index.jsp

 1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'index.jsp' starting page</title>
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="cache-control" content="no-cache">
15     <meta http-equiv="expires" content="0">    
16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
17     <meta http-equiv="description" content="This is my page">
18     <!--
19     <link rel="stylesheet" type="text/css" href="styles.css">
20     -->
21   </head>
22   
23   <body>
24     <h1>Servlet路径跳转</h1>
25     <hr>
26     <!-- 使用相对路径访问HelloServlet -->
27     <!-- /servlet/HelloServlet 第一个/表示服务器的根目录 -->
28     <a href="servlet/HelloServlet">使用相对路径访问HelloServlet!</a><br>
29     <!-- 使用绝对路径 访问HelloServlet,可以使用path变量:path变量表示项目的根目录 -->
30     <a href="<%=path%>/servlet/HelloServlet">使用绝对路径访问HelloServlet!</a><br>
31     <!-- 表单中action的URL地址写法,与超链接方式完全相同。 -->
32     <a href="servlet/TestServlet">访问TestServlet,跳转到Test.jsp</a>
33   </body>
34 </html>

test.jsp

 1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'index.jsp' starting page</title>
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="cache-control" content="no-cache">
15     <meta http-equiv="expires" content="0">    
16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
17     <meta http-equiv="description" content="This is my page">
18     <!--
19     <link rel="stylesheet" type="text/css" href="styles.css">
20     -->
21   </head>
22   
23   <body>
24     <h1>Test.jsp</h1>
25   </body>
26 </html>

 

 

 1 package com.po;
 2 
 3 public class Users {
 4 
 5     private String username;
 6     private String password;
 7     public Users() {
 8         
 9     }
10     public String getUsername() {
11         return username;
12     }
13     public void setUsername(String username) {
14         this.username = username;
15     }
16     public String getPassword() {
17         return password;
18     }
19     public void setPassword(String password) {
20         this.password = password;
21     }    
22 }

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5" 
 3     xmlns="http://java.sun.com/xml/ns/javaee" 
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 7   <display-name></display-name>
 8   <servlet>
 9     <description>This is the description of my J2EE component</description>
10     <display-name>This is the display name of my J2EE component</display-name>
11     <servlet-name>LoginServlet</servlet-name>
12     <servlet-class>servlet.LoginServlet</servlet-class>
13   </servlet>
14 
15   <servlet-mapping>
16     <servlet-name>LoginServlet</servlet-name>
17     <url-pattern>/servlet/LoginServlet</url-pattern>
18   </servlet-mapping>    
19   <welcome-file-list>
20     <welcome-file>login.jsp</welcome-file>
21   </welcome-file-list>
22 </web-app>

 

 1 package servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import com.po.Users;
12 
13 public class LoginServlet extends HttpServlet {
14 
15     /**
16      * Constructor of the object.
17      */
18     public LoginServlet() {
19         super();
20     }
21 
22     /**
23      * Destruction of the servlet. <br>
24      */
25     public void destroy() {
26         super.destroy(); // Just puts "destroy" string in log
27         // Put your code here
28     }
29 
30     /**
31      * The doGet method of the servlet. <br>
32      *
33      * This method is called when a form has its tag value method equals to get.
34      * 
35      * @param request the request send by the client to the server
36      * @param response the response send by the server to the client
37      * @throws ServletException if an error occurred
38      * @throws IOException if an error occurred
39      */
40     public void doGet(HttpServletRequest request, HttpServletResponse response)
41             throws ServletException, IOException {
42 
43         doPost(request,response);
44     }
45 
46     /**
47      * The doPost method of the servlet. <br>
48      *
49      * This method is called when a form has its tag value method equals to post.
50      * 
51      * @param request the request send by the client to the server
52      * @param response the response send by the server to the client
53      * @throws ServletException if an error occurred
54      * @throws IOException if an error occurred
55      */
56     public void doPost(HttpServletRequest request, HttpServletResponse response)
57             throws ServletException, IOException {
58 
59         Users u = new Users();
60         String username=request.getParameter("username");
61         String password=request.getParameter("password");
62         u.setUsername(username);
63         u.setPassword(password);
64         //判断用户名和密码是否合法
65         if(u.getUsername().equals("admin")&&u.getPassword().equals("admin"))
66         {
67             response.sendRedirect(request.getContextPath()+"/login_success.jsp");
68         }
69         else
70         {
71             response.sendRedirect(request.getContextPath()+"/login_failure.jsp");
72         }
73         
74         request.getSession().setAttribute("loginUserid", u);//把注册成功的用户对象保存在session对象中
75     }
76 
77     /**
78      * Initialization of the servlet. <br>
79      *
80      * @throws ServletException if an error occurs
81      */
82     public void init() throws ServletException {
83         // Put your code here
84     }
85 
86 }

login.jsp

 1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
 2 <%
 3    String path = request.getContextPath();
 4    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 <html>
 7     <head>
 8         <!-- Page title -->
 9         <title>imooc - Login</title>
10         <!-- End of Page title -->
11         <!-- Libraries -->
12         <link type="text/css" href="css/login.css" rel="stylesheet" />    
13         <link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />    
14         <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
15         <script type="text/javascript" src="js/easyTooltip.js"></script>
16         <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
17         <!-- End of Libraries -->    
18     </head>
19     <body>
20     <div id="container">
21         <div class="logo">
22             <a href="#"><img src="assets/logo.png" alt="" /></a>
23         </div>
24         <div id="box">
25             <form action="servlet/LoginServlet" method="post">
26             <p class="main">
27                 <label>用户名: </label>
28                 <input name="username" value="" /> 
29                 <label>密码: </label>
30                 <input type="password" name="password" value="">    
31             </p>
32             <p class="space">
33                 <input type="submit" value="登录" class="login" style="cursor: pointer;"/>
34             </p>
35             </form>
36         </div>
37     </div>
38     </body>
39 </html>

 

login_failure

 1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
 2 <%
 3    String path = request.getContextPath();
 4    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 <html>
 7     <head>
 8         <!-- Page title -->
 9         <title>imooc - Login</title>
10         <!-- End of Page title -->
11         <!-- Libraries -->
12         <link type="text/css" href="css/login.css" rel="stylesheet" />    
13         <link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />    
14         <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
15         <script type="text/javascript" src="js/easyTooltip.js"></script>
16         <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
17         <!-- End of Libraries -->    
18     </head>
19     <body>
20     <div id="container">
21         <div class="logo">
22             <a href="#"><img src="assets/logo.png" alt="" /></a>
23         </div>
24         <div id="box">
25              登录失败!请检查用户或者密码!<br>
26           <a href="login.jsp">返回登录</a>   
27         </div>
28     </div>
29     </body>
30 </html>

 

 login_success.jsp

 1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
 2 <%
 3    String path = request.getContextPath();
 4    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 <html>
 7     <head>
 8         <!-- Page title -->
 9         <title>imooc - Login</title>
10         <!-- End of Page title -->
11         <!-- Libraries -->
12         <link type="text/css" href="css/login.css" rel="stylesheet" />    
13         <link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />    
14         <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
15         <script type="text/javascript" src="js/easyTooltip.js"></script>
16         <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
17         <!-- End of Libraries -->    
18     </head>
19     <body>
20      <!-- 
21     <div id="container">
22         <div class="logo">
23             <a href="#"><img src="assets/logo.png" alt="" /></a>
24         </div>
25         <div id="box">
26           <% 
27              String loginUser = "";
28              if(session.getAttribute("loginUser")!=null)
29              {
30                 loginUser = session.getAttribute("loginUser").toString();
31              }
32           %>
33              欢迎您<font color="red"><%=loginUser%></font>,登录成功!
34         </div>
35     </div>
36      -->
37  
38     <jsp:useBean id="loginUserid" class="com.po.Users" scope="session" />
39     <div id="container">
40         <div class="logo">
41             <a href="#"><img src="assets/logo.png" alt="" />
42             </a>
43         </div>
44         <div id="box">
45             欢迎您<font color="red"> <jsp:getProperty name="loginUserid"
46                     property="username" /> </font> ,登录成功!
47         </div>
48     </div>
49     
50 
51 </body>
52 </html>

 



posted on 2018-10-08 20:08  songsong_p_blue  阅读(237)  评论(0编辑  收藏  举报