转载自大神http://blog.csdn.net/chinacsharper/article/details/39777643
有好多年不搞Java Web开发了,这几天正好国庆放假,放松之余也有兴趣回头看看Java Web开发技术的基础。
我们都知道,Servlet是Java Web开发的重要基础,但是由于Servlet开发相对繁琐,代码量庞大而且不易维护,美工无法参与界面设计开发等不足,于是就诞生了jsp。jsp是对servlet开发模型的重要升级。有了jsp,Java Web开发技术才真正被广泛使用。
一、Servlet
在Java Web开发当中,新建一个类继承(派生)自HttpServlet类即可创建一个Servlet。
比如:
- @WebServlet(name="firstServlet",urlPatterns={"/firstServlet"})
- public class FirstServlet extends HttpServlet {
- /**
- * Constructor of the object.
- */
- public FirstServlet() {
- super();
- }
- /**
- * Destruction of the servlet. <br>
- */
- public void destroy() {
- super.destroy(); // Just puts "destroy" string in log
- // Put your code here
- }
- /**
- * 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 {
- response.setContentType("text/html");
- 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(" </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 {
- response.setContentType("text/html");
- 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 POST method");
- out.println(" </BODY>");
- out.println("</HTML>");
- out.flush();
- out.close();
- }
- /**
- * Initialization of the servlet. <br>
- *
- * @throws ServletException if an error occurs
- */
- public void init() throws ServletException {
- // Put your code here
- }
- }
- <servlet>
- <servlet-name>firstServlet</servlet-name>
- <servlet-class>包名.FirstServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>firstServlet</servlet-name>
- <url-pattern>/firstServlet</url-pattern>
- </servlet-mapping>
上面的配置有几点需要说明:
1、servlet里面的servlet-class节点需要填写servlet类的完整名称(包名.类名)
2、servlet-mapping下的servlet-name节点的名称要与servlet下的servlet-name节点的名称一致,才能找到。
3、url-pattern下的url要加"/"
启动tomcat,在ie中输入localhost:8080/工程名/firstServet,即可浏览该页面(Get请求)。8080端口是tomcat默认设置的端口号,可以在tomcat/conf/下面的server.xml文件中修改端口号。比如我们修改了默认端口号为8088,重新启动tomcat(加载xml)以后,访问的url即为:localhost:8088/工程名/servlet映射的urlpattern名。
- <Connector port="8088" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
可以看到servlet里面都是一行一行输出内容(out.println方法),所以现在基本上不会采用纯servlet开发Java Web项目,而是让其作为MVC的C(Controller,控制器)来使用。
二、jsp
正是由于纯servlet开发Java Web应用非常繁琐,而且美工和程序员无法很好的合作,jsp应运而生。jsp通过页面嵌入代码、标签库(比如JSTL,Java标准标签库)等手段,可以直接在页面中混入Java代码,从而简化开发。但是jsp的本质还是servlet,我们可以用文本编辑器(比如:editplus、notepad++)打开tomcat/work目录下的工程目录里面的classes文件就可以看到,实际上jsp还是被编译生成了servlet类文件(一个jsp对应生成一个servlet)。里面也有init、destroy、service(这个与之前的Get、Post、Put、Delete请求不同)等方法。
下面先演示一段从MySQL数据库中通过JDBC读取数据显示在页面上的功能,让读者快速上手jsp。
开发环境:
1、MySQL5.7
2、MyEclipse 2014、JDK7.0
MySQL安装后自带了一个MySQL Workbench工具,可以利用它新建数据库。
点击OK,出现如下界面。
输入密码即可登录到工作台主界面。
里面有默认的world数据库,可以在里面对Tables(表)、Views(视图)、Stored Procedures(存储过程)、Functions(函数)等进行相关操作。
当然你也可以在MySQL控制台用命令行对数据库进行操作。
我们就使用MySQL里面自带的world数据库,查询里面的city这张表,把数据显示出来(由于数据量比较大,只取前10条)。
先在MySQL的工具里面用SQL查询一下。
SQL语句测试通过,我们就可以在jsp页面中直接使用了。
MyJsp.jsp完整代码:
- <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%@ page import="java.sql.*" %>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP 'MyJsp.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- </head>
- <body>
- <%
- Class.forName("com.mysql.jdbc.Driver");//加载驱动
- Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/world", "root", "123456");//建立连接
- Statement stmt = conn.createStatement();//创建执行者
- ResultSet rs = stmt.executeQuery("select * from city limit 0,10");//返回结果集(游标)
- %>
- <table cellpadding="0" cellspacing="0" border="1" width="500" >
- <%
- while (rs.next()) {
- %>
- <tr>
- <td><%=rs.getString(1) %></td>
- <td><%=rs.getString(2) %></td>
- </tr>
- <%
- }
- %>
- </table>
- </body>
- </html>
可以看到,直接在jsp页面中嵌入了Java代码。由于我们使用的是JDBC查询的MySQL数据库,所以我们需要mysql-connector-java-5.1.9.jar这个Jar包作为驱动,直接放到该Web工程的WEB-INF/lib目录下即可。
在浏览器中显示的结果如下:
如我们所愿,显示出了前10条数据。
其实对比一下上面的页面代码,你会发现这种页面嵌入代码的方式非常熟悉。在ASP、ASP.NET开发中都可以使用这种嵌入后台代码的方式进行开发,所以基本上开发思想都可以互相套用。
由于篇幅原因,这篇博客就先到这里,下篇博客重点讲述jsp开发中的种种细节。