双人网页游戏网站,以前自己做的网站怎么样删除,收费网站空间,山东电力建设第一工程公司网站Java后端开发——MVC商品管理程序
本篇文章内容主要有下面几个部分#xff1a;
MVC架构介绍项目环境搭建商品管理模块Servlet代码重构BaseServlet文件上传
MVC 是模型-视图-控制器#xff08;Model-View-Controller#xff09;#xff0c;它是一种设计模式#xff0c;也…Java后端开发——MVC商品管理程序
本篇文章内容主要有下面几个部分
MVC架构介绍项目环境搭建商品管理模块Servlet代码重构BaseServlet文件上传
MVC 是模型-视图-控制器Model-View-Controller它是一种设计模式也是一种软件架构模式用于构建用户界面UI应用程序。 1.模型Model
模型代表应用程序的数据结构和业务逻辑。它负责处理应用程序的数据逻辑部分包括数据的获取、修改、验证等。
在一个应用程序中模型可以是一个简单的数据对象也可以是包含大量业务规则和处理逻辑的复杂对象。
2.视图View 视图负责将数据渲染成用户可以看到的界面。它展示了模型的数据给用户并允许用户与数据进行交互。 在 Web 应用程序中视图通常是 HTML、CSS 和用户界面组件。
3.控制器Controller 控制器是模型和视图之间的中介它接收用户的输入并处理用户请求。控制器根据用户的请求选择合适的模型进行处理并将处理结果传递给视图进行显示。 在 Web 应用程序中控制器通常是处理 HTTP 请求、调度逻辑以及返回 HTTP 响应的代码。
MVC 框架的工作流程
1.用户交互 用户与应用程序交互发送请求给控制器。
2.控制器处理请求 控制器接收到用户的请求根据请求的类型GET、POST 等和参数来决定调用哪个模型处理数据。
控制器可能还需要处理一些逻辑例如验证用户的输入、选择合适的模型进行处理等。
3.模型处理数据 模型接收控制器传递过来的数据请求并进行相应的数据处理包括数据的获取、更新、存储等操作。
.4.控制器获取处理结果 模型处理完数据后将结果返回给控制器。 5.控制器选择视图 控制器根据模型返回的数据结果选择合适的视图进行渲染。
6.视图渲染结果 视图将模型返回的数据渲染成用户可以看到的界面。 7.用户界面更新 更新后的用户界面展示给用户用户可以进行下一步操作。
这种分离有利于代码的组织和维护。每个组件都专注于特定的功能降低了耦合性使得代码更易于理解、测试和扩展。MVC 模式在各种软件开发中都有广泛的应用特别是在 Web 开发中诸如Spring MVCJava、DjangoPython、Ruby on RailsRuby等框架中都采用了 MVC 架构。
MVC商品管理程序
项目环境搭建 1.创建数据库db_goods表goods 在MySQL数据库中创建一个名称为db_goods的数据库并根据表结构在数据库中创建相应的表。
CREATE TABLE goods (id INT NOT NULL AUTO_INCREMENT,name VARCHAR(45) DEFAULT NULL,cover VARCHAR(45) DEFAULT NULL,image1 VARCHAR(45) DEFAULT NULL,image2 VARCHAR(45) DEFAULT NULL,price FLOAT DEFAULT NULL,intro VARCHAR(300) DEFAULT NULL,stock INT DEFAULT NULL,type_id INT DEFAULT NULL,PRIMARY KEY (id)
);在goods表中插入一些商品数据 2.创建项目mygoods引入JAR包 新建Dynamic web project 将项目所需JAR包导入到项目的WEB-INF/lib文件夹下。
3.配置c3p0-config.xml文件 将JAR包导入到项目中并发布到类路径后在src根目录下新建c3p0-config.xml文件用于配置数据库连接参数。我的mysql数据库账号和密码都是root.
?xml version1.0 encodingUTF-8?
c3p0-config
default-config
property namedriverClasscom.mysql.jdbc.Driver/property
property namejdbcUrl
jdbc:mysql://localhost:3306/db_goods?useSSLfalseamp;serverTimezoneUTCamp;useUnicodetrueamp;characterEncodingutf-8
/property
property nameuserroot/property
property namepasswordroot/property
property namecheckoutTimeout30000/property
property nameinitialPoolSize5/property
property namemaxIdleTime30/property
property namemaxPoolSize10/property
property nameminPoolSize2/property
property namemaxStatements200/property
/default-config
/c3p0-config4.编写DBUtils工具类 在src下创建一个名称为utils的包在该包下新建DataSourceUtils类用于获取数据源和数据库连接。
package com.java.utils;import java.sql.SQLException;import javax.sql.DataSource;import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mysql.jdbc.Connection;public class DataSourceUtils {private static DataSource dsnew ComboPooledDataSource();public static DataSource getDataSource(){return ds;}public static Connection getConnection() throws SQLException {return (Connection) ds.getConnection();}
}商品管理模块 1.创建Goods.java的JavaBean类
//创建Goods.java的JavaBean类
package com.javaweb.model;public class Goods {
private int id;
private String name;
private String cover;
private String image1;
private String image2;
private float price;
private String intro;
private int stock;
private int type_id;
//利用工具自动生成Getter/Setter方法
public int getId() {
return id;
}
public void setId(int id) {
this.id id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name name;
}
public String getCover() {
return cover;
}
public void setCover(String cover) {
this.cover cover;
}
public String getImage1() {
return image1;
}
public void setImage1(String image1) {
this.image1 image1;
}
public String getImage2() {
return image2;
}
public void setImage2(String image2) {
this.image2 image2;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price price;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro intro;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock stock;
}
public int getType_id() {
return type_id;
}
public void setType_id(int type_id) {
this.type_id type_id;
}
}2.创建GoodsDao.java类
package com.javaweb.dao;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import com.java.utils.DataSourceUtils;
import com.javaweb.model.Goods;
public class GoodsDao {public ListGoods findByTypeID(int typeID) throws SQLException {if(typeID0){String sqlselect * from goods;QueryRunner rnew QueryRunner(DataSourceUtils.getDataSource());return r.query(sql,new BeanListHandlerGoods(Goods.class));}else{String sqlselect * from goods where type_id?;QueryRunner rnew QueryRunner(DataSourceUtils.getDataSource());return r.query(sql,new BeanListHandlerGoods(Goods.class),typeID);}} public ListGoods findByTypeID(int typeID,int pageNumber,int pageSize) throws SQLException {if(typeID0){String sqlselect * from goods limit ?,?;QueryRunner rnew QueryRunner(DataSourceUtils.getDataSource());return r.query(sql,new BeanListHandlerGoods(Goods.class),(pageNumber-1)*pageSize,pageSize);}else{String sqlselect * from goods where type_id? limit ?,?;QueryRunner rnew QueryRunner(DataSourceUtils.getDataSource());return r.query(sql,new BeanListHandlerGoods(Goods.class),typeID,(pageNumber-1)*pageSize,pageSize);}} public Goods findById(int id) throws SQLException {QueryRunner r new QueryRunner(DataSourceUtils.getDataSource());String sql select * from goods where id ?;return r.query(sql, new BeanHandlerGoods(Goods.class),id);}public int getCountByTypeID(int typeID) throws SQLException {String sql;QueryRunner rnew QueryRunner(DataSourceUtils.getDataSource());if(typeID0){sqlselect count(*) from goods;return r.query(sql,new ScalarHandlerLong()).intValue();}else{sqlselect count(*) from goods where type_id?;return r.query(sql,new ScalarHandlerLong(),typeID).intValue();}}public void insert(Goods g) throws SQLException {QueryRunner r new QueryRunner(DataSourceUtils.getDataSource());String sql insert into goods(name,cover,image1,image2,price,intro,stock,type_id) values(?,?,?,?,?,?,?,?);r.update(sql,g.getName(),g.getCover(),g.getImage1(),g.getImage2(),g.getPrice(),g.getIntro(),g.getStock(),g.getType_id());}public void update(Goods g) throws SQLException {QueryRunner r new QueryRunner(DataSourceUtils.getDataSource());String sql update goods set name?,cover?,image1?,image2?,price?,intro?,stock?,type_id? where id?;r.update(sql,g.getName(),g.getCover(),g.getImage1(),g.getImage2(),g.getPrice(),g.getIntro(),g.getStock(),g.getType_id(),g.getId());}public void delete(int id) throws SQLException {QueryRunner r new QueryRunner(DataSourceUtils.getDataSource());String sql delete from goods where id ?;r.update(sql,id);}}3.创建goods_add.jsp表单页
% page languagejava contentTypetext/html; charsetUTF-8
pageEncodingUTF-8%
!DOCTYPE html
html
head
meta charsetUTF-8
titleInsert title here/title
link relstylesheet hrefcss/bootstrap.css /
/head
body
div classcontainer-fluid
h3添加商品页面/h3
brbr
form classform-horizontal action${pageContext.request.contextPath}/GoodsServlet?madd methodpost
div classform-group
label forinput_name classcol-sm-1 control-label名称/label
div classcol-sm-6
input typetext classform-control idinput_name namename requiredrequired
/div
/div
div classform-group
label forinput_name classcol-sm-1 control-label价格/label
div classcol-sm-6
input typetext classform-control idinput_name nameprice
/div
/div
div classform-group
label forinput_name classcol-sm-1 control-label介绍/label
div classcol-sm-6
input typetext classform-control idinput_name nameintro
/div
/div
div classform-group
label forinput_name classcol-sm-1 control-label库存/label
div classcol-sm-6
input typetext classform-control idinput_name namestock
/div
/div
div classform-group
label forinput_file classcol-sm-1 control-label封面图片/label
div classcol-sm-6
input typetext namecover idinput_file requiredrequired推荐尺寸: 500 * 500
/div
/div
div classform-group
label forinput_file classcol-sm-1 control-label详情图片1/label
div classcol-sm-6
input typetext nameimage1 idinput_file requiredrequired推荐尺寸: 500 * 500
/div
/div
div classform-group
label forinput_file classcol-sm-1 control-label详情图片2/label
div classcol-sm-6
input typetext nameimage2 idinput_file requiredrequired推荐尺寸: 500 * 500
/div
/div
div classform-group
label forselect_topic classcol-sm-1 control-label类目/label
div classcol-sm-6
select classform-control idselect_topic nametype_id
option value1食品/option
option value2生活用品/option
option value3学习用品/option
/select
/div
/div
div classform-group
div classcol-sm-offset-1 col-sm-10
button typesubmit classbtn btn-success提交保存/button
/div
/div
/form
/div
/body
/html4.创建GoodServlet.java根据请求参数m的值调用增删改查方法
WebServlet(/GoodsServlet)
public class GoodsServlet extends HttpServlet {GoodsDao goodsDaonew GoodsDao();protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String mrequest.getParameter(m);if(m.equals(add)) {add(request,response);}else if(m.equals(find)) {find(request,response);}else if(m.equals(update)) {update(request,response);}else if(m.equals(delete)) {delete(request,response);}else if(m.equals(findById)) {findById(request,response);}}
}5.完善GoodServlet的商品增加add方法
private void add(HttpServletRequest request, HttpServletResponse response) {
Goods goods new Goods();
try {
BeanUtils.populate(goods,request.getParameterMap());
goodsDao.insert(goods);
response.sendRedirect(GoodsServlet?mfind);
} catch (Exception e) {
e.printStackTrace();
} 6.测试商品保存 运行tomact服务器添加一条商品信息 提交保存再查看所有商品信息页发现添加商品测试成功 7.完善GoodServlet的商品查询find方法。
private void find(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
int type 0;//推荐类型
if(request.getParameter(type) ! null) {
typeInteger.parseInt(request.getParameter(type) ) ;
}
try {
ListGoods glistgoodsDao.findByTypeID(type);
request.setAttribute(glist, glist);
request.getRequestDispatcher(/goods_list.jsp).forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}8.创建商品列表页面goods_list.jsp
% page languagejava contentTypetext/html; charsetUTF-8
pageEncodingUTF-8%
% taglib urihttp://java.sun.com/jsp/jstl/core prefixc %
!DOCTYPE html
html
head
meta charsetUTF-8
titleInsert title here/title
link relstylesheet hrefcss/bootstrap.css /
/head
body
div classcontainer-fluid
h3商品列表页面/h3
div classtext-righta classbtn btn-warning hrefgoods_add.jsp添加商品/a/div
table classtable table-bordered table-hover
tr
th width5%ID/th
th width10%名称/th
th width10%价格/th
th width10%介绍/th
th width10%库存/th
th width10%封面图片/th
th width10%详情图片1/th
th width10%详情图片2/th
th width10%类目/th
th width10%操作/th
/tr
c:forEach items${glist } varg
tr
tdp${g.id }/p/td
tdp${g.name }/p/td
tdp${g.price }/p/td
tdp${g.intro }/p/td
tdp${g.stock }/p/td
tdp${g.cover }/p/td
tdp${g.image1 }/p/td
tdp${g.image2}/p/td
tdp${g.type_id }/p/td
td
a classbtn btn-primary href${pageContext.request.contextPath}/GoodsServlet?mfindByIdid${g.id}修改/a
a classbtn btn-danger href${pageContext.request.contextPath}/GoodsServlet?mdeleteid${g.id}删除/a
/td
/tr
/c:forEach
/table
/div
/body
/html9.测试商品查询全部 运行tomact服务运行goods_list.jsp文件然后在网页find路由
http://localhost:8080/mygoods/GoodsServlet?mfind查询商品全部信息。 10.完善GoodServlet的商品按ID查询findById方法
private void findById(HttpServletRequest request, HttpServletResponse response) {
int idInteger.parseInt(request.getParameter(id));
try {
Goods g goodsDao.findById(id);
request.setAttribute(g, g);
request.getRequestDispatcher(/goods_edit.jsp).forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}11.创建商品列表页面goods_edit.jsp
% page languagejava contentTypetext/html; charsetUTF-8
pageEncodingUTF-8%
!DOCTYPE html
html
head
meta charsetUTF-8
titleInsert title here/title
link relstylesheet hrefcss/bootstrap.css /
/head
body
div classcontainer-fluid
h3修改商品页面/h3
brbr
form classform-horizontal action${pageContext.request.contextPath}/GoodsServlet?mupdate methodpost
input typehidden nameid value${g.id }/
div classform-group
label forinput_name classcol-sm-1 control-label名称/label
div classcol-sm-6
input typetext classform-control idinput_name namename value${g.name } requiredrequired
/div
/div
div classform-group
label forinput_name classcol-sm-1 control-label价格/label
div classcol-sm-6
input typetext classform-control idinput_name value${g.price } nameprice
/div
/div
div classform-group
label forinput_name classcol-sm-1 control-label介绍/label
div classcol-sm-6
input typetext classform-control idinput_name value${g.intro } nameintro
/div
/div
div classform-group
label forinput_name classcol-sm-1 control-label库存/label
div classcol-sm-6
input typetext classform-control idinput_name namestock value${g.stock }
/div
/div
div classform-group
label forinput_file classcol-sm-1 control-label封面图片/label
div classcol-sm-6
input typetext namecover idinput_file value${g.cover } requiredrequired推荐尺寸: 500 * 500
/div
/div
div classform-group
label forinput_file classcol-sm-1 control-label详情图片1/label
div classcol-sm-6
input typetext nameimage1 idinput_file value${g.image1 } requiredrequired推荐尺寸: 500 * 500
/div
/div
div classform-group
label forinput_file classcol-sm-1 control-label详情图片2/label
div classcol-sm-6
input typetext nameimage2 idinput_file value${g.image2 } requiredrequired推荐尺寸: 500 * 500
/div
/div
div classform-group
label forselect_topic classcol-sm-1 control-label类目/label
div classcol-sm-6
select classform-control idselect_topic value${g.type_id } nametype_id
option value1 ${g.type_id1?selectedselected:}食品/option
option value2 ${g.type_id2?selectedselected:}生活用品/option
option value3 ${g.type_id3?selectedselected:}学习用品/option
/select
/div
/div
div classform-group
div classcol-sm-offset-1 col-sm-10
button typesubmit classbtn btn-success提交保存/button
/div
/div
/form
/div
/body
/html12.测试商品更新 启动tomact服务器
http://localhost:8080/mygoods/GoodsServlet?mfindByIdid2对id为2的商品进行修改。 修改之前的数据 进行修改 修改之后的数据 13.完善GoodServlet的商品删除delete方法
private void delete(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
int idInteger.parseInt(request.getParameter(id));
try {
goodsDao.delete(id);
response.sendRedirect(GoodsServlet?mfind);
} catch (Exception e) {
e.printStackTrace();
}
}14.测试商品删除 我们在所有商品页面把id为168和169的商品删除 点击删除成功调用delete方法删除两条记录 15.创建编码过滤器解决表单中文乱码 为防止项目中请求和响应出现乱码情况在src下创建一个名称为filter的包在该包下新建一个过滤器EncodeFilter类来统一全站的编码防止出现乱码的情况。
package com.javaweb.filter;import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;/*** Servlet Filter implementation class EncodeFilter*/
WebFilter(/*)
public class EncodeFilter extends HttpFilter implements Filter {/*** see Filter#destroy()*/public void destroy() {// TODO Auto-generated method stub}/*** see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)*/public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {request.setCharacterEncoding(utf-8);chain.doFilter(request, response);}/*** see Filter#init(FilterConfig)*/public void init(FilterConfig fConfig) throws ServletException {// TODO Auto-generated method stub}}Servlet代码重构BaseServlet 1.编写BaseServlet实现Java动态方法调用
package com.javaweb.servlet;import java.io.IOException;
import java.lang.reflect.Method;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class BaseServlet extends HttpServlet {Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String m req.getParameter(m);Class clazz this.getClass();try {Method method clazz.getDeclaredMethod(m, HttpServletRequest.class, HttpServletResponse.class);method.setAccessible(true);method.invoke(this,req,resp);} catch (Exception e) {e.printStackTrace();} }}2.修改GoodServlet继承BaseServlet 将之前的HttpServlet修改为BaseServlet
public class GoodsServlet extends BaseServlet {
private static final long serialVersionUID 1L;
GoodsDao goodsDaonew GoodsDao();3.测试功能是否正常 服务器启动正常测试正常可以正常增删改查 增加一条“西瓜波波”商品信息 我们修改西瓜波波价格从12改成15 修改成功 删除西瓜波波这条商品信息删除成功在所有商品信息页查找不到此商品 通过测试所有功能均正常 文件上传 1.创建上传表单页 新建upload.jsp上传表单页 2.编写上传upload方法
% page languagejava contentTypetext/html; charsetUTF-8
pageEncodingUTF-8%
!DOCTYPE html
html
head
meta charsetUTF-8
titleInsert title here/title
/head
body
form action${pageContext.request.contextPath}/GoodsServlet?mupload methodpost enctypemultipart/form-data
商品名称input typetext namename
商品图片input typefile namephoto
input typesubmit value上传
/form/body
/html3.测试 启动tomact服务器运行upload.jsp文件开始进行文件上传 上传商品名称为1 上传图片名称为“图片.jpg” 点击上传控制台信息显示 1 | ec996c8a-33cc-4dd4-a344-8fec1d008b4a.jpg 文件上传成功 然后打开本地目录 C:\myx\java后端\MVC商品管理程序.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\mygoods\upload
成功发现我们在upload,jsp页面上传的文件 希望各位能通过MVC商品管理程序认识MVC框架的重要性它可以有效地分离业务逻辑和视图层使得代码更加清晰易懂。