Java Web开发之Servlet、JSP基础
有好多年不搞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
}
}这段代码是在myeclipse工具其中创建servlet时自己主动生成的,能够看到我们新建的FirstServlet类继承自HttpServlet。并且又实现了里面的doGet(Get请求时调用的方法)、doPost(Post请求时调用的方法)、init(初始化对象)、destroy(销毁对象)。值得注意的是我们採用了Annotation的方式进行了修饰,即:@WebServlet(name="firstServlet",urlPatterns={"/firstServlet"})。这是servlet3.0開始推荐的,曾经採用的方式是在web.xml里面加入servlet和servlet-mapping配置。
比方:
<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/project名/firstServet,就可以浏览该页面(Get请求)。8080port是tomcat默认设置的port号,能够在tomcat/conf/以下的server.xml文件里改动port号。比方我们改动了默认port号为8088。又一次启动tomcat(载入xml)以后,訪问的url即为:localhost:8088/project名/servlet映射的urlpattern名。
<Connector port="8088" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />最后须要说明的是。假设我们在servlet里面改动了代码,比方又一次输出了一段html表格。要又一次编译、部署到tomcat web容器执行,不像jsp是即时编译的。
能够看到servlet里面都是一行一行输出内容(out.println方法),所以如今基本上不会採用纯servlet开发Java Web项目,而是让其作为MVC的C(Controller。控制器)来使用。
二、jsp
正是因为纯servlet开发Java Web应用很繁琐。并且美工和程序猿无法很好的合作,jsp应运而生。
jsp通过页面嵌入代码、标签库(比方JSTL。Java标准标签库)等手段,能够直接在页面中混入Java代码,从而简化开发。
可是jsp的本质还是servlet。我们能够用文本编辑器(比方:editplus、notepad++)打开tomcat/work文件夹下的project文件夹里面的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,出现例如以下界面。
输入password就可以登录到工作台主界面。
里面有默认的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包作为驱动,直接放到该Webproject的WEB-INF/lib文件夹下就可以。
在浏览器中显示的结果例如以下:
如我们所愿。显示出了前10条数据。
事实上对照一下上面的页面代码,你会发现这样的页面嵌入代码的方式很熟悉。在ASP、ASP.NET开发中都能够使用这样的嵌入后台代码的方式进行开发,所以基本上开发思想都能够互相套用。
因为篇幅原因,这篇博客就先到这里,下篇博客重点讲述jsp开发中的种种细节。
浙公网安备 33010602011771号