上一篇博文写到模式一:JSP+JavaBean
链接地址:http://wxmimperio.coding.io/?p=155
JSP中两种模式的总结
链接地址:http://wxmimperio.coding.io/?p=207
这篇对模式二:JSP+Servlet+JavaBean,做一个小的总结。
模式二中结合了JSP和Servlet,充分利用了两个技术的原有特点。是最典型的MVC设计模式,将输入、处理、输出分成视图、模型和控制器,各自执行各自的任务。请求会由前面的Servlet接受并处理后,重新定向到JSP页面。在Servlet作为控制器时,每个Servlet通常只实现很少的一部分功能,多个Servlet控制器就可以结合起来完成复杂的逻辑任务。这样的好处是Servlet的重用性很好利用,一个副作用就是可能会导致请求相应加长。在此模式里,JavaBean作为模型的角色,它充当JSP和Servlet通信的中间工具。Setvlet处理完成设置Bean的属性,JSP读取此Bean的属性,然后进行显示。
在项目开发过程中,前端页面设计者可以方便地开发JSP页面,而Servlet则更适合后台开发,因为Servlet技术需要更多的Java编程。
实例说明:
这里写一个留言并查看的小例子帮助理解这种模式,会用到JDBC编程、SQL、Servlet的相关知识,这里不做相关介绍。
(开发环境是Idea+Tomcat+Mysql,提前做好相应jar包的引入)
数据库脚本:
- create database messages;
- use messages;
- #留言信息
- create table message(
- title varchar(20) not null, #标题
- username varchar(20) not null, #名字
- content varchar(20) not null, #内容
- mail varchar(20) #邮箱
- );
1.添加留言的Servlet(AddMessageServlet.java)
- package jsp_javabean_servlet;
- import javax.servlet.*;
- import javax.servlet.http.*;
- import java.io.*;
- import java.sql.*;
- public class AddMessageServlet extends HttpServlet{
- private Connection con;
- /**
- * 创建数据库连接
- */
- public AddMessageServlet() {
- try {
- Class.forName("com.mysql.jdbc.Driver");
- String url = "jdbc:mysql://localhost:3306/messages?user=root&password=root";
- con = DriverManager.getConnection(url);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- /**
- * 接受get请求,执行数据库操作,把视图发送到下一个页面
- */
- public void doGet(HttpServletRequest request,HttpServletResponse response)
- throws IOException,ServletException {
- //接收请求的参数
- request.setCharacterEncoding("gbk");
- String name = request.getParameter("name");
- String mail = request.getParameter("email");
- String title = request.getParameter("title");
- String content = request.getParameter("content");
- //插入留言
- try {
- String sql = "insert into message(title,username,content,mail) values(?,?,?,?)";
- PreparedStatement stm = con.prepareStatement(sql);
- stm.setString(1,title);
- stm.setString(2,name);
- stm.setString(3,content);
- stm.setString(4,mail);
- try {
- stm.executeUpdate();
- } catch (Exception e){}
- con.close();
- //把视图发送给目标
- RequestDispatcher requestDispatcher =
- request.getRequestDispatcher("/viewMessages_servlet");
- requestDispatcher.forward(request,response);
- }catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * doPost请求
- */
- public void doPost(HttpServletRequest request,HttpServletResponse response)
- throws IOException,ServletException {
- doGet(request,response);
- }
- }
2.留言浏览的Servlet(ViewMessageServlet.java)
- package jsp_javabean_servlet;
- import javax.servlet.*;
- import javax.servlet.http.*;
- import java.io.*;
- import java.sql.*;
- import java.util.*;
- public class ViewMessageServlet extends HttpServlet{
- private Connection con;
- /**
- * 接受get请求,执行数据库操作,结果保存到request中
- * 把视图发送到下一个页面
- */
- public void doGet(HttpServletRequest request,HttpServletResponse response)
- throws IOException,ServletException{
- Collection ret = new ArrayList();
- try {
- Statement stm = con.createStatement();
- ResultSet result = stm.executeQuery("select count(*) from message");
- //统计留言数量
- int message_count = 0;
- if(result.next()) {
- message_count = result.getInt(1);
- result.close();
- }
- //从数据库中读取留言信息
- if(message_count > 0) {
- result = stm.executeQuery("select * from message");
- while (result.next()) {
- String title = result.getString("title");
- String name = result.getString("username");
- String mail = result.getString("mail");
- String content = result.getString("content");
- MessageVO message = new MessageVO();
- message.setName(name);
- message.setTitle(title);
- message.setEmail(mail);
- message.setContent(content);
- ret.add(message);
- }
- result.close();
- stm.close();
- }
- //将执行结果发送到目标
- request.setAttribute("messages",ret);
- RequestDispatcher requestDispatcher =
- request.getRequestDispatcher("viewMessage.jsp");
- requestDispatcher.forward(request,response);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * doPost请求
- */
- public void doPost(HttpServletRequest request,HttpServletResponse response)
- throws IOException,ServletException{
- doGet(request,response);
- }
- /**
- * 数据库连接
- */
- public ViewMessageServlet() {
- try {
- Class.forName("com.mysql.jdbc.Driver");
- String url = "jdbc:mysql://localhost:3306/messages?user=root&password=root";
- con = DriverManager.getConnection(url);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
3.用来set和get数据的JavaBean(MessageVO.java)
- package jsp_javabean_servlet;
- /**
- * 这个JavaBean,表示留言的数据
- */
- public class MessageVO implements java.io.Serializable {
- //定义留言的相关参数
- private String name,email,title,content;
- private java.sql.Date date;
- //get和set方法
- public void setName(String name) {
- this.name = name;
- }
- public String getName() {
- return this.name;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public String getEmail() {
- return this.email;
- }
- public void setTitle(String title) {
- this.title = title;
- }
- public String getTitle() {
- return this.title;
- }
- public void setContent(String content) {
- this.content = content;
- }
- public String getContent() {
- return this.content;
- }
- }
4.web.xml的配置文件
- <display-name>jsp_javabean_servlet</display-name>
- <description>jsp_javabean_servlet</description>
- <servlet>
- <servlet-name>ViewMessageServlet</servlet-name>
- <servlet-class>jsp_javabean_servlet.ViewMessageServlet</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>AddMessageServlet</servlet-name>
- <servlet-class>jsp_javabean_servlet.AddMessageServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>ViewMessageServlet</servlet-name>
- <url-pattern>/viewMessages_servlet</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>AddMessageServlet</servlet-name>
- <url-pattern>/addMessages_servlet</url-pattern>
- </servlet-mapping>
5.留言输入的html(index.html)
- <html>
- <head lang="en">
- <meta charset="gbk">
- <title></title>
- </head>
- <body>
- <td><table align="center" border="1" cellspacing="0" cellpadding="0">
- <form action="addMessages_servlet" method="post">
- <tr>
- <td>姓名:</td>
- <td><input type="text" name="name" size="25"></td>
- </tr>
- <tr>
- <td>E-mail:</td>
- <td><input type="text" name="email" size="25"></td>
- </tr>
- <tr>
- <td>主题:</td>
- <td><input type="text" name="title" size="25"></td>
- </tr>
- <tr>
- <td >留言:</td>
- <td><input type="text" name="content" size="25"></td>
- </tr>
- <tr><td colspan="3">
- <table align="center" width="100%" cellspacing="0" cellpadding="0">
- <tr>
- <td align="center"><input type="submit" value="提交"></td>
- <td align="center"><a href="viewMessages_servlet">查看留言</a></td>
- <td align="center"><input type="reset" value="重新填写"></td>
- </tr>
- </table>
- </td></tr>
- </form>
- </table></td>
- </body>
- </html>
6.显示留言的JSP(viewMessage.jsp)
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <%@ page import="java.sql.*,jsp_javabean_servlet.*,java.util.*" %>
- <html>
- <head>
- <title></title>
- </head>
- <body>
- <p align="center">所有留言</p>
- <hr>
- <%
- int messgae_count = 1;
- Collection messages = (Collection)request.getAttribute("messages");
- Iterator it = messages.iterator();
- while (it.hasNext()) {
- MessageVO message = (MessageVO)it.next();
- %>
- <table width="30%" align="center" border="1" cellpadding="0" cellspacing="0">
- <tr>
- <td>主题:</td>
- <td><%=message.getTitle()%></td>
- </tr>
- <tr>
- <td>留言人:</td>
- <td><%=message.getName()%></td>
- </tr>
- <tr>
- <td>邮箱:</td>
- <td><%=message.getEmail()%></td>
- </tr>
- <tr>
- <td>楼层:
- <%
- out.println("("+messgae_count+")");
- %>
- </td>
- <td><%=message.getContent()%></td>
- </tr>
- </table>
- <%
- out.println("<hr>");
- messgae_count++;
- }
- %>
- <p align="center"><a href="index.html">我要留言</a></p>
- </body>
- </html>
运行
在浏览器里输入index.html的地址,填入留言信息点击提交,会跳转到viewMessage.jsp页面显示信息,其实已经经过两个Servlet的处理。
index.html填写留言页面:
viewMessage.jsp显示留言页面:
参考:JSP应用开发详解(第三版)