一、Servlet+JSP+JavaBean开发模式(MVC)介绍
Servlet+JSP+JavaBean模式(MVC)适合开发复杂的web应用,在这种模式下,servlet负责处理用户请求,jsp负责数据显示,javabean负责封装数据。 Servlet+JSP+JavaBean模式程序各个模块之间层次清晰,web开发推荐采用此种模式。
这里以一个最常用的用户登录注册程序来讲解Servlet+JSP+JavaBean开发模式,通过这个用户登录注册程序综合案例,把之前的学过的XML、Xpath、Servlet、jsp的知识点都串联起来。
二、创建MVC架构的Web项目
在MyEclipse中新创建一个webmvcframework项目,导入项目所需要的开发包(jar包),创建项目所需要的包,在java开发中,架构的层次是以包的形式体现出来的
项目所需要的开发包(jar包)
序号
开发包名称
描述
1
dom4j-1.6.1.jar
dom4j用于操作XML文件
2
jaxen-1.1-beta-6.jar
用于解析XPath表达式
3
commons-beanutils-1.8.0.jar
工具类,用于处理bean对象
4
commons-logging.jar
commons-beanutils-1.8.0.jar的依赖jar包
5
jstl.jar
jstl标签库和EL表达式依赖包
6
standard.jar
jstl标签库和EL表达式依赖包
一个良好的JavaWeb项目架构应该具有以上的11个包,这样显得层次分明,各个层之间的职责也很清晰明了,搭建JavaWeb项目架构时,就按照上面的1~11的序号顺序创建包:domain→dao→dao.impl→service→service.impl→web.controller→web.UI→web.filter→web.listener→util→junit.test,包的层次创建好了,项目的架构也就定下来了,当然,在实际的项目开发中,也不一定是完完全全按照
项目所需要的包
序号
包名
描述
所属层次
1
me.gacl.domain
存放系统的JavaBean类(只包含简单的属性以及属性对应的get和set方法,不包含具体的业务处理方法),提供给【数据访问层】、【业务处理层】、【Web层】来使用
domain(域模型)层
2
me.gacl.dao
存放访问数据库的操作接口类
数据访问层
3
me.gacl.dao.impl
存放访问数据库的操作接口的实现类
4
me.gacl.service
存放处理系统业务接口类
业务处理层
5
me.gacl.service.impl
存放处理系统业务接口的实现类
6
me.gacl.web.controller
存放作为系统控制器的Servlet
Web层(表现层)
7
me.gacl.web.UI
存放为用户提供用户界面的servlet(UI指的是user interface)
8
me.gacl.web.filter
存放系统的用到的过滤器(Filter)
9
me.gacl.web.listener
存放系统的用到的监听器(Listener)
10
me.gacl.util
存放系统的通用工具类,提供给【数据访问层】、【业务处理层】、【Web层】来使用
11
junit.test
存放系统的测试类
上面说的来创建包的层次结构,而是根据项目的实际情况,可能还需要创建其他的包,这个得根据项目的需要来定了
在src目录(类目录)下面,创建用于保存用户数据的xml文件(DB.xml)
在WEB-INF目录下创建一个pages目录,pages目录存放系统的一些受保护(不允许用户直接通过URL地址访问)的jsp页面,用户要想访问这些受保护的jsp页面,那么只能通过me.gacl.web.UI这个包里面的Servlet
三、分层架构的代码编写
分层架构的代码也是按照【域模型层(domain)】→【数据访问层(dao、dao.impl)】→【业务处理层(service、service.impl)】→【表现层(web.controller、web.UI、web.filter、web.listener)】→【工具类(util)】→【测试类(junit.test)】的顺序进行编写的。
一:首先我们因为要查询到数据 应该先建立我们需要的数据库
#判断存在即删除数据库
drop database if exists mydb;
#创建数据库
create database mydb;
#使用数据库
use mydb;
#创建表
create table t_user
(
uid int primary key auto_increment,
username varchar(20),
password varchar(20),
phone varchar(11),
address varchar(50)
);
insert into t_user(username,password,phone,address) values('张三','666','18965423548','南阳');
insert into t_user(username,password,phone,address) values('李四','333','18754263548','许昌');
insert into t_user(username,password,phone,address) values('小美','123','18565234759','信阳');
select * from t_user where username=? and password=?
select * from t_user;
create table t_goods
(
gid int primary key auto_increment,
gname varchar(20),
price double,
mark varchar(100)
);
insert into t_goods(gname,price,mark) values('泡面',4.5,'够香够辣就是这个味!');
insert into t_goods(gname,price,mark) values('火腿',8.5,'肉质细腻Q弹!');
insert into t_goods(gname,price,mark) values('雪碧',3.5,'清爽冰凉随心爽!');
select * from t_goods;
二:准备我们的登录页面jsp代码
1:首页
<%--
Created by IntelliJ IDEA.
User: 大大怪将军
Date: 2023/2/14
Time: 10:52
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>这是第一次JavaWeb项目</title>
</head>
<body>
<h2>这是第一次文本</h2>
<a href="login.jsp" >去登录</a>
<a href="zhuce.jsp" >注册</a>
</body>
</html>
2:登录页面
<%--
Created by IntelliJ IDEA.
User: 大大怪将军
Date: 2023/2/14
Time: 11:06
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<form action="dl" method="post">
账号:<input type="text" name="username" value=""><br>
密码:<input type="password" name="password" value=""><br>
<input type="submit" value="登录">
</form>
</body>
</html>
3:登录过后的主页内容显示
<%--
Created by IntelliJ IDEA.
User: 大大怪将军
Date: 2023/2/16
Time: 12:20
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主页</title>
</head>
<body>
<h2>欢迎来到javaweb项目</h2>
<table>
<thead>
<tr>
<th>编号</th>
<th>名称</th>
<th>价格</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>泡面</td>
<td>4.5</td>
<td>够香够辣就是这个味!</td>
</tr>
<tr>
<td>火腿</td>
<td>8.5</td>
<td>肉质细腻Q弹!</td>
</tr><tr>
<td>雪碧</td>
<td>3.5</td>
<td>清爽冰凉随心爽!</td>
</tr>
</tbody>
</table>
</body>
</html>
4:准备servlet映射
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.huanxiao.servlet.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>aa</servlet-name>
<servlet-class>com.huanxiao.servlet.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>aa</servlet-name>
<url-pattern>/dl</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>zhuce</servlet-name>
<servlet-class>com.huanxiao.servlet.ZhuCe</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>zhuce</servlet-name>
<url-pattern>/zhuce</url-pattern>
</servlet-mapping>
</web-app>
5:准备我们的实体类 (User类 和Goods类)起名和数据库的名字起的一样方便
package com.huanxiao.bean;
public class Goods {
private Integer gid;
private String gname;
private Double price;
private String mark;
public Integer getGid() {
return gid;
}
public void setGid(Integer gid) {
this.gid = gid;
}
public String getGname() {
return gname;
}
public void setGname(String gname) {
this.gname = gname;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
@Override
public String toString() {
return "Goods{" +
"gid=" + gid +
", gname='" + gname + '\'' +
", price=" + price +
", mark='" + mark + '\'' +
'}';
}
}
package com.huanxiao.bean;
public class User {
private Integer uid;
private String username;
private String password;
private String phone;
private String address;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"uid=" + uid +
", username='" + username + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
", address='" + address + '\'' +
'}';
}
}
7:登录失败后显示的页面
<%--
Created by IntelliJ IDEA.
User: 大大怪将军
Date: 2023/2/16
Time: 12:07
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>错误页面</title>
</head>
<body>
<a href="login.jsp">重新登录</a>
</body>
</html>
8:准备我们的java登录代码操作
package com.huanxiao.servlet;
import com.huanxiao.bean.User;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Login extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Login...Get");
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//这三个都是获取请求的地址相关
// String uri=request.getRequestURI();
// String contextPath = request.getContextPath();
// String servletPath = request.getServletPath();
//
// System.out.println(uri);//包含项目名和资源名
// System.out.println(contextPath);//项目名称
// System.out.println(servletPath);//请求的资源路径
//1:从请求中获取用户提交写参数(数据)
request.setCharacterEncoding("utf-8");//设置请求的编码格式为中文
String username = request.getParameter("username");
String password = request.getParameter("password");
// System.out.println(username);
// System.out.println(password);
Connection connection=null;
PreparedStatement pstm=null;
ResultSet rs=null;
User login=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC","root","123456");
String sql="select * from t_user where username=? and password=?";
pstm= connection.prepareStatement(sql);
pstm.setObject(1,username);
pstm.setObject(2,password);
rs= pstm.executeQuery();
if(rs.next()){
login=new User();
login.setUid(rs.getInt("uid"));
login.setUsername(rs.getString("username"));
login.setPassword(rs.getString("password"));
login.setPhone(rs.getString("phone"));
login.setAddress(rs.getString("address"));
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(rs!=null){
rs.close();
}
if(pstm!=null){
pstm.close();
}
if(connection!=null){
connection.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
if(login!=null){
response.sendRedirect("zhuye.jsp");
}else{
response.sendRedirect("erroir.jsp");
}
}
}
三:注册页面jsp代码
1:主页注册代码
<%--
Created by IntelliJ IDEA.
User: 大大怪将军
Date: 2023/2/14
Time: 10:52
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>这是第一次JavaWeb项目</title>
</head>
<body>
<h2>这是第一次文本</h2>
<a href="login.jsp" >去登录</a>
<a href="zhuce.jsp" >注册</a>
</body>
</html>
2:跳转到注册页面
<%--
Created by IntelliJ IDEA.
User: 大大怪将军
Date: 2023/2/14
Time: 11:14
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册</title>
</head>
<body>
<form action="zhuce" method="post">
请输入你的姓名:<input type="text" name="username" value=""><br>
请输入你的密码:<input type="password" name="password" value=""><br>
请输入你的手机号:<input type="text" name="phone" value=""><br>
请输入你的地址:<input type="text" name="address" value=""><br>
<input type="submit" value="注册">
</form>
</body>
</html>
3:准备servlet映射
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.huanxiao.servlet.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>aa</servlet-name>
<servlet-class>com.huanxiao.servlet.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>aa</servlet-name>
<url-pattern>/dl</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>zhuce</servlet-name>
<servlet-class>com.huanxiao.servlet.ZhuCe</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>zhuce</servlet-name>
<url-pattern>/zhuce</url-pattern>
</servlet-mapping>
</web-app>
4:注册页面java代码操作
package com.huanxiao.servlet;
import com.huanxiao.bean.User;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class ZhuCe extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");//设置请求的编码格式为中文
String username = request.getParameter("username");
String password = request.getParameter("password");
String phone = request.getParameter("phone");
String address = request.getParameter("address");
// System.out.println(username);
// System.out.println(password);
try {
Boolean zhucetext = zhucetext(username, password, phone, address);
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
if(zhucetext){
response.getWriter().write("<h1>注册成功</h1>");
} else {
response.getWriter().write("<h1>注册失败</h1>");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Boolean zhucetext(String username, String password, String phone, String address) throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC",
"root", "123456");
String sql = "insert into t_user (username,password,phone,address)values (?,?,?,?)";
PreparedStatement pstm = connection.prepareStatement(sql);
pstm.setObject(1, username);
pstm.setObject(2, password);
pstm.setObject(3, phone);
pstm.setObject(4, address);
int i = pstm.executeUpdate();
if (i > 0) {
if (pstm != null) {
pstm.close();
}
if (connection != null) {
connection.close();
}
return true;
} else {
return false;
}
}
}
四:登录页面显示效果
五:注册页面效果显示
分层操作:
一:创建4个包bean(放实体类) dao(放接口和java登录注册代码)servlet(放java调用运行代码)
util(放sql连接语句 关闭资源代码 )
1:把我们需要的sql语句连接放到我们新创建的JDBCUtil包中
package com.huanxiao.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class JDBCUtil {
private static String dirver="com.mysql.cj.jdbc.Driver";
private static String url="jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC";
private static String user="root";
private static String password="123456";
private static Connection connection=null;
public static Connection getCon(){
try {
Class.forName(dirver);
connection= DriverManager.getConnection(url,user,password);
}catch (Exception e){
e.printStackTrace();
}
return connection;
}
public static void close( PreparedStatement pstm, Connection connection){
try{
if(pstm!=null){
pstm.close();
}
if(connection!=null){
connection.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
public static void clos(ResultSet rs, PreparedStatement pstm, Connection con){
try{
if(rs!=null){
rs.close();
}
if(pstm!=null){
pstm.close();
}
if(con!=null){
con.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
2:创建我们所需要的接口
package com.huanxiao.dao;
import com.huanxiao.bean.User;
public interface UserDao {
public User login(String username, String password);
public int zhuce(User user);
}
3:准备java登录注册代码 开始需要连接接口
package com.huanxiao.dao.impl;
import com.huanxiao.bean.User;
import com.huanxiao.dao.UserDao;
import com.huanxiao.util.JDBCUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class UserDaoImpl implements UserDao {
Connection connection = null;
PreparedStatement pstm = null;
ResultSet rs = null;
User lo = null;
int row = 0;
@Override
public User login(String username, String password) {
Connection con = null;
PreparedStatement pstm = null;
try {
connection= JDBCUtil.getCon();
String sql = "select * from t_user where username=? and password=?";
pstm = connection.prepareStatement(sql);
pstm.setObject(1, username);
pstm.setObject(2, password);
rs = pstm.executeQuery();
if (rs.next()) {
lo = new User();
lo.setUid(rs.getInt("uid"));
lo.setUsername(rs.getString("username"));
lo.setPassword(rs.getString("password"));
lo.setPhone(rs.getString("phone"));
lo.setAddress(rs.getString("address"));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtil.clos(rs,pstm,connection);
}
return lo;
}
@Override
public int zhuce (User user){
Connection con = null;
PreparedStatement pstm = null;
try {
con = JDBCUtil.getCon();
String sql = "insert into t_user(username,password,phone,address) values(?,?,?,?);";
pstm = con.prepareStatement(sql);
pstm.setObject(1, user.getUsername());
pstm.setObject(2, user.getPassword());
pstm.setObject(3, user.getPhone());
pstm.setObject(4, user.getAddress());
row = pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtil.close(pstm, con);
}
return row;
}
}
5:准备java运行代码
package com.huanxiao.servlet;
import com.huanxiao.bean.User;
import com.huanxiao.dao.UserDao;
import com.huanxiao.dao.impl.UserDaoImpl;
import com.huanxiao.util.JDBCUtil;
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 java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@WebServlet("/dl")
public class Login extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Login...Get");
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//这三个都是获取请求的地址相关
// String uri=request.getRequestURI();
// String contextPath = request.getContextPath();
// String servletPath = request.getServletPath();
//
// System.out.println(uri);//包含项目名和资源名
// System.out.println(contextPath);//项目名称
// System.out.println(servletPath);//请求的资源路径
//1:从请求中获取用户提交写参数(数据)
request.setCharacterEncoding("utf-8");//设置请求的编码格式为中文
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
// System.out.println(username);
// System.out.println(password);
UserDaoImpl userDao=new UserDaoImpl();
User lo=userDao.login(username,password);
if(lo!=null){
response.sendRedirect("zhuye.jsp");
}else{
response.sendRedirect("erroir.jsp");
}
}
}
package com.huanxiao.servlet;
import com.huanxiao.bean.User;
import com.huanxiao.dao.UserDao;
import com.huanxiao.dao.impl.UserDaoImpl;
import javax.jws.WebService;
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 java.io.IOException;
@WebServlet("/zhuce")
public class Rsgister extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("type/html;charset=utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
String phone = request.getParameter("phone");
String address = request.getParameter("address");
User user=new User();
user.setUsername(username);
user.setPassword(password);
user.setPhone(phone);
user.setAddress(address);
UserDao userDao= new UserDaoImpl();
int row=userDao.zhuce(user);
if(row>0){
response.sendRedirect("login.jsp");
}else {
response.sendRedirect("erroir.jsp");
}
}
}
文章出处登录后可见!