1、使用Servlet作为表现层的三个劣势
- 开发效率低,所有的HTML标签都需使用页面输出流完成;
- 不利于团队协作开发, 美工人员无法参与Servlet界面的开发;
- 程序可维护性差,即使修改一个按钮的标题,都必须重新编辑Java代码,并重新编译。
2、Servlet仅作为控制器使用
在标准的MVC模式中,Servlet仅作为控制器使用。Java EE应用架构正式遵循MVC模式的, 对于遵循MVC模式的Java EE应用而言,JSP仅作为表现层(View)技术, 其作用有两点:
- 负责收集用户请求参数;
- 将应用的处理结果、状态数据呈现给用户。
3、示例,一个简单的登录验证(Servlet作为控制器的MVC应用):
1)登录页面login.jsp
<%--
Created by IntelliJ IDEA.
User: Chuan
Date: 2017/9/1
Time: 20:27
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" errorPage="" %>
<html>
<head>
<title>登录页面</title>
</head>
<body>
<%--输出出错提示--%>
<span style="color:red; font-weight: bold">
<%
if (request.getAttribute("err") != null)
{
out.println(request.getAttribute("err") + "<br/>");
}
%>
</span>
请输入用户名和密码:
<%--登录表单,该表单提交到一个Servlet--%>
<form id="login" method="post" action="login">
用户名:<input type="text" name="username" /><br/>
密  码:<input type="password" name="pass" /><br/>
<input type="submit" value="登录">
</form>
</body>
</html>
2)控制器Servlet代码LoginServlet.java
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
@WebServlet(name = "login", urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet
{
//响应客户端请求的方法
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String errMsg = "";
//Servlet本身并不输出响应到客户端,因此必须将请求转发到视图页面
RequestDispatcher rd;
//设置请求的编码方式
request.setCharacterEncoding("UTF-8");
//获取请求参数
String username = request.getParameter("username");
String pass = request.getParameter("pass");
try
{
//Servlet本身并不执行任何的业务逻辑处理,它调用JavaBean处理用户请求
DbDao dd = new DbDao("com.mysql.jdbc.Driver",
"jdbc:mysql://localhost:3306/您的数据库名字", "您的用户名", "您的密码");
//查询结果集
ResultSet rs = dd.query("select pass from user_inf"
+ " where name = ?", username);
if (rs.next())
{
//用户名和密码匹配
if (rs.getString("pass").equals(pass))
{
//获取session对象
HttpSession session = request.getSession(true);
//设置session属性,跟踪会话状态
session.setAttribute("name", username);
//获取转发对象
rd = request.getRequestDispatcher("/welcom.jsp");
rd.forward(request, response);
}
else
{
//用户名和密码不匹配
errMsg += "您的用户名密码不符合, 请重新输入";
}
}
else
{
//用户名不存在时
errMsg += "您的用户名不存在,请先注册";
}
}
catch (Exception e)
{
e.printStackTrace();
}
if(errMsg != null && !errMsg.equals(""))
{
rd = request.getRequestDispatcher("/login.jsp");
request.setAttribute("err", errMsg);
rd.forward(request, response);
}
}
}
3)本应用中的Modle: DbDao.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DbDao
{
private Connection conn;
private String driver;
private String url;
private String username;
private String pass;
public DbDao()
{
}
public DbDao(String driver, String url, String username, String pass)
{
this.driver = driver;
this.url = url;
this.username = username;
this.pass = pass;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
//获取数据库连接
public Connection getConnection() throws Exception
{
if (conn == null)
{
Class.forName(this.driver);
conn = DriverManager.getConnection(url, username, this.pass);
}
return conn;
}
//插入记录
public boolean insert(String sql, Object... args) throws Exception
{
PreparedStatement pstmt = getConnection().prepareCall(sql);
for (int i = 0; i < args.length; i++)
{
pstmt.setObject(i + 1, args[i]);
}
if (pstmt.executeUpdate() != 1)
{
return false;
}
return true;
}
//执行查询
public ResultSet query(String sql, Object... args) throws Exception
{
PreparedStatement pstmt = getConnection().prepareStatement(sql);
for (int i = 0; i < args.length; i++)
{
pstmt.setObject(i + 1, args[i]);
}
return pstmt.executeQuery();
}
//执行修改
public void modify(String sql, Object... args) throws Exception
{
PreparedStatement pstmt = getConnection().prepareStatement(sql);
for (int i = 0; i < args.length; i++)
{
pstmt.setObject(i + 1, args[i]);
}
pstmt.executeUpdate();
pstmt.close();
}
//关闭连接
public void closeConn() throws Exception
{
if(conn != null && !conn.isClosed())
{
conn.close();
}
}
}
4)登录成功欢迎页面welcome.jsp
<%--
Created by IntelliJ IDEA.
User: Chuan
Date: 2017/9/1
Time: 21:23
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>欢迎页面</title>
</head>
<body>
<h3>欢迎登陆</h3>
<%=session.getAttribute("name")%>,欢迎登录
</body>
</html>
5)数据表
6)演示结果