I've set up the first jsp file "hello.jsp". Now I wanna add Servlet into my project:
In Project Explore, find project "Sample01", open it. Right click on "Java Resources: src".
First we new a new package "com.company.servlets" to store the servlet file.
Then new a servlet file: "HelloServlet.servlet":
Right click on "com.company.servlets" =>New => Other => Web => Servlet
After creation, we can see Eclipse has automatically inserted the basic block into the file. And in Web.xml, we can see two blocks have been inserted:
<servlet>
<description></description>
<display-name>HelloServlet</display-name>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.company.servlets.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
In J2EE#2 Target: JSP + Servlet + Service + DAO + JDBC (Oracle) + SP (1),
We can see the form
11 <form action = "HelloServlet" method="get">
12 <table>
13 <tr>
14 <td>Name :</td>
15 <td><input type="text" name="name" /></td>
16 </tr>
17 <tr>
18 <td>Age :</td>
19 <td><input type="text" name="age" /></td>
20 </tr>
21 <tr>
22 <td></td>
23 <td>
24 <input type="reset" value="Clear" />
25 <input type="submit" value="Submit" />
26 </td>
27 </tr>
28 </table>
29 </form>
Here I need to mention the mapping relationship between jsp and servlet. How does the server locate servlet? It's very important. We can get the idea through the picture below:
After we understand the scheme, we can modify the Web.xml ourselves.
Now we go back to the servlet file "HelloServlet.servlet".
Initially:
01 package com.company.servlets;
02
03 import java.io.IOException;
04 import javax.servlet.ServletException;
05 import javax.servlet.http.HttpServletRequest;
06 import javax.servlet.http.HttpServletResponse;
07
08 /**
09 * Servlet implementation class for Servlet: HelloServlet
10 *
11 */
12 public class HelloServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
13 static final long serialVersionUID = 1L;
14
15 /* (non-Java-doc)
16 * @see javax.servlet.http.HttpServlet#HttpServlet()
17 */
18 public HelloServlet() {
19 super();
20 }
21
22 /* (non-Java-doc)
23 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
24 */
25 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
26 // TODO Auto-generated method stub
27 }
28
29 /* (non-Java-doc)
30 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
31 */
32 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
33 // TODO Auto-generated method stub
34 }
35 }
We can see that there are three functions in the template. We mainly focus on the function "doGet" and "doPost". In "hello.jsp", we can see the form from line 11 :
11 <form action = "HelloServlet" method="get">
Now the method = "get". Then it will call the function "doGet". If we change the method to "post", then it will call function "doPost", if we do not declare method, it'll default call "doGet".
Now we add some code into function "doGet":
1 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
2 // TODO Auto-generated method stub
3 String name = request.getParameter("name");
4 int age = Integer.parseInt(request.getParameter("age")); //controller deal with this
5
6 response.setContentType("text/html");
7 PrintWriter out = response.getWriter();
8 out.println("Hello " + name + ", your age is " + age);
9 }
Now we run "hello.jsp" and input some value, Submit:
Now we can see that JSP and Servlet successfully setup the connection.
JSP + Servlet are realized.
If we want to write HTML into the page instead of text. We can modify the code:
01 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
02 // TODO Auto-generated method stub
03 String name = request.getParameter("name");
04 int age = Integer.parseInt(request.getParameter("age")); //controller deal with this
05
06 response.setContentType("text/html");
07 PrintWriter out = response.getWriter();
08 out.println("<HTML><body>");
09 out.println("<h2><font color = blue>");
10 out.println("Hello " + name + ", your age is " + age);
11 out.println("</h2></font>");
12 out.println("</HTML></body>");
13 }
The result will be:
But we can see two problems in the previous code.
One is that, what if the dataset is big? When there're a lot of parameters, write code like this may cause mistakes because of careless. Wooooo, there're so many parameters! A small mistake may take you a long time to check. So in industry, JavaBeans are used to solve this problem.We know that JavaBeans can be used to hold and transfer data and maximum the code reuse. So, in industy, we almost use JavaBeans instead of writing all code into servlet's functions.
We new a new package "com.company.beans". In this package, new a java file "User.java".
Code:
01 package com.company.beans;
02
03 public class User {
04
05 private String name;
06 private int age;
07 public String getName() {
08 return name;
09 }
10 public void setName(String name) {
11 this.name = name;
12 }
13 public int getAge() {
14 return age;
15 }
16 public void setAge(int age) {
17 this.age = age;
18 }
19
20 }
02
03 public class User {
04
05 private String name;
06 private int age;
07 public String getName() {
08 return name;
09 }
10 public void setName(String name) {
11 this.name = name;
12 }
13 public int getAge() {
14 return age;
15 }
16 public void setAge(int age) {
17 this.age = age;
18 }
19
20 }
There is a little trick in writing beans. That is we do not need to write all the set and get functions ourself. We only need to define all the parameters. Then, right click => source => Generate Getters and Setters...
Then Eclipse does all the work for us!
Then we modify the "HelloServlet.servlet":
01 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
02 // TODO Auto-generated method stub
03 User user = parse(request);
04 response.setContentType("text/html");
05 PrintWriter out = response.getWriter();
06 out.println("<HTML><body>");
07 out.println("<h2><font color = blue>");
08 out.println("Hello " + user.getName() + ", your age is " + user.getAge());
09 out.println("</h2></font>");
10 out.println("</HTML></body>");
11 }
12
13 /* (non-Java-doc)
14 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
15 */
16 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
17 // TODO Auto-generated method stub
18 }
19 private User parse(HttpServletRequest request){
20 User user = new User();
21 user.setName(request.getParameter("name"));
22 user.setAge(Integer.parseInt(request.getParameter("age")));
23 return user;
24 }
The second problem is that:
The HTML code are all written in the function "doGet". If we want to reuse the code, it's inconvenient. So we introduce Service package.
We new a new package "com.company.services". In this package, new a java file "HelloService,java".
Code:
01 package com.company.services;
02 import com.company.beans.*;
03
04 public class HelloService {
05
06 public HelloService(){
07 }
08 public String sayHello1(User user){
09 StringBuffer sb = new StringBuffer();
10 sb.append("<HTML><body>");
11 sb.append("<h2><font color = blue>");
12 sb.append("Hello " + user.getName() + ", with age " + user.getAge() + ", welcome to J2EE!");
13 sb.append("</h2></font>");
14 sb.append("</body></HTML>");
15 return sb.toString();
16 }
17 }
Then we modify the "HelloServlet.servlet":
1 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
2 // TODO Auto-generated method stub
3 User user = parse(request);
4 response.setContentType("text/html");
5 PrintWriter out = response.getWriter();
6 HelloService hs = new HelloService();
7 out.println(hs.sayHello1(user));
8 }
There's also a problem. Anytime we call doGet, one HelloService object will be created. It's unnecessary. So we rely on the thought of Singleton. We modify the code like:
01 package com.company.servlets;
02
03 import java.io.IOException;
04 import java.io.PrintWriter;
05 import javax.servlet.ServletException;
06 import javax.servlet.http.HttpServletRequest;
07 import javax.servlet.http.HttpServletResponse;
08 import com.company.beans.*;
09 import com.company.services.*;
10
11 /**
12 * Servlet implementation class for Servlet: HelloServlet
13 *
14 */
15 public class HelloServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
16 static final long serialVersionUID = 1L;
17 private HelloService hs;
18 /* (non-Java-doc)
19 * @see javax.servlet.http.HttpServlet#HttpServlet()
20 */
21 public HelloServlet() {
22 super();
23 if(hs==null){
24 hs = new HelloService(); // simulate singleton
25 }
26 }
27
28 /* (non-Java-doc)
29 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
30 */
31 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
32 // TODO Auto-generated method stub
33 User user = parse(request);
34 response.setContentType("text/html");
35 PrintWriter out = response.getWriter();
36 HelloService hs = new HelloService();
37 out.println(hs.sayHello1(user));
38 }
39
40 /* (non-Java-doc)
41 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
42 */
43 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
44 // TODO Auto-generated method stub
45 }
46 private User parse(HttpServletRequest request){
47 User user = new User();
48 user.setName(request.getParameter("name"));
49 user.setAge(Integer.parseInt(request.getParameter("age")));
50 return user;
51 }
52 }
"JSP + Servlet + Service" are realized.
To be continued...
No comments:
Post a Comment