mvc
MVC全名:Model View Controller ,即把一个应用的输入、处理、输出流程按照Model、View、Controller的方式进行分离
MVC是比较经典的软件开发架构划分方式,在Web开发领域有广泛的应用
代码
实体类
/**
*
*/
package com.shegx.entity;
/**
* @author SHE
*
* 2020年6月9日下午4:26:41
* com.shegx.entity
*/
public class Blog {
private String id;
private String title;
private String content;
private String url;
private int indexFlag;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getIndexFlag() {
return indexFlag;
}
public void setIndexFlag(int indexFlag) {
this.indexFlag = indexFlag;
}
public Blog() {
}
public Blog(String id, String title, String content, String url, int indexFlag) {
this.id = id;
this.title = title;
this.content = content;
this.url = url;
this.indexFlag = indexFlag;
}
@Override
public String toString() {
return "Blog [id=" + id + ", title=" + title + ", content=" + content + ", url=" + url + ", indexFlag="
+ indexFlag + "]";
}
}
Dao方法
继承Basedao简化代码,提高通用性
/**
*
*/
package com.shegx.Dao;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
import com.shegx.entity.Blog;
import com.shegx.util.BaseDao;
import com.shegx.util.PageBean;
import com.shegx.util.StringUtils;
/**
* @author SHE
*
* 2020年6月9日下午4:29:32
* com.shegx.Dao
*/
public class BlogDao extends BaseDao<Blog>{
public List<Blog> list(Blog blog,PageBean pageBean) throws IllegalAccessException, SQLException, Exception{
//查询的sql的的语句
String sql="select * from t_lucene_crawler_blog where true";
//可能需要带条件查询,要是拼接查询sql
String title=blog.getTitle();
//分页
if(StringUtils.isNotBlank(title)) {
sql +=" and title like '%"+title+"%'";
}
// 在修改的时候,查询被修改的那条记录("单个查询")
String id=blog.getId();
if(StringUtils.isNotBlank(id)) {
sql +=" and id ="+id;
}
return super.executeQuery(sql, Blog.class, pageBean);
}
public int add(Blog blog) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
//随机生成id
blog.setId(UUID.randomUUID().toString());
//新增sql语句
String sql="insert into t_lucene_crawler_blog values(?,?,?,?,?)";
//调用
return super.executeUpdate(sql, blog, new String[] {"id","title","content","url","indexFlag"});
}
//修改
public int edit(Blog blog) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
//修改sql语句
String sql="update t_lucene_crawler_blog set title=?,content=?,url=?,indexFlag=? where id=?";
//调用
return super.executeUpdate(sql, blog, new String[] {"title","content","url","indexFlag","id"});
}
//删除
public int del(Blog blog) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
//删除sql语句
String sql="delete from t_lucene_crawler_blog where id=?";
//调用
return super.executeUpdate(sql, blog, new String[] {"id"});
}
}
分页核心Basedao,pageBean
Basedao
/**
*
*/
package com.shegx.util;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* @author SHE
*
* 2020年6月4日下午2:36:32
* com.shegx.util
*/
public class BaseDao<T> {
public List<T> executeQuery(String sql,Class clz,PageBean pageBean) throws SQLException, Exception, IllegalAccessException{
List<T> ls=new ArrayList<>();
Connection con = DBHelper.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
if(pageBean!=null && pageBean.isPagination()) {
//分页--->列表需求
//查询出符号条件的总记录数
String countSql=getCountsql(sql);
ps = con.prepareStatement(countSql);
rs = ps.executeQuery();
if(rs.next()) {
pageBean.setTotal(rs.getObject(1).toString());
}
//展示要看到的数据
String pageSql=getPageSql(sql,pageBean);
ps = con.prepareStatement(pageSql);
rs = ps.executeQuery();
}else {
//不分页---》下拉需求
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
if(rs.next()) {
pageBean.setTotal(rs.getObject(1).toString());
}
}
while(rs.next()) {
//ls.add(new Book(rs.getInt("bid"),rs.getString("bName"),rs.getFloat("price")));
/**
* Book book=new Book;
* book.setBid(rs.getInt("bid"));
* book.setBName(rs.getString("bName"));
* book.setPrice(rs.getFloat("price"));
* list.add(book);
* 实例化了一个对象
* 给这一个空对象的每一个属性赋值
* 将赋值的对象添加到list集合中返回
*/
T t = (T) clz.newInstance();
for (Field f : clz.getDeclaredFields()) {
f.setAccessible(true);
f.set(t, rs.getObject(f.getName()));
}
ls.add(t);
}
DBHelper.close(con, ps, rs);
return ls;
}
/**
* @param sql
* @param pageBean
* @return
*/
private String getPageSql(String sql, PageBean pageBean) {
// TODO Auto-generated method stub
return sql + " limit "+pageBean.getStartIndex()+","+pageBean.getRows();
}
/**
* @param sql
* @return
*/
private String getCountsql(String sql) {
return "select count(1) from("+sql+") t";
}
/**
* sql=select * from t_mvc_book where TRUE and bname like '%圣墟%'
* countsql=select count(1) from(SELECT * FROM t_mvc_book WHERE TRUE AND bname like '%圣墟%')t;
* pagesql=SELECT * FROM t_mvc_book WHERE TRUE AND bname LIKE '%圣墟%'LIMIT 1,10
*/
/**
*
* @param sql
* @param t
* @param attrs
* @return
* @throws SQLException
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public int executeUpdate(String sql, T t, String[] attrs) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Connection con=DBHelper.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
/* pst.setObject(1, book.getbId());
pst.setObject(2,book.getbName());
pst.setObject(3, book.getPrice());*/
int loop=1;
Field f=null;
for(String attr : attrs) {
f = t.getClass().getDeclaredField(attr);
f.setAccessible(true);
pst.setObject(loop++, f.get(t));
}
int code = pst.executeUpdate();
DBHelper.close(con, pst, null);
return code;
}
}
pageBean
package com.shegx.util;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
/**
* 分页工具类
*
*/
public class PageBean {
private int page = 1;// 页码
private int rows = 10;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
//上一次查询的url
private String url;
//上一次查询携带的条件
private Map<String, String[]> parameterMap=new HashMap<String, String[]>();
//对pagebean进行初始化
public void setRequest(HttpServletRequest req) {
//初始化jsp页面传递来的当前页
this.setPage(req.getParameter("page"));
//初始化jsp页面传递来的页大小
this.setRows(req.getParameter("rows"));
//初始化jsp页面传递来的是否分页
this.setPagination(req.getParameter("pagination"));
//保留上一次的查询请求
this.setUrl(req.getRequestURI().toString());
//保留上一次的查询条件
this.setParameterMap(req.getParameterMap());
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getParameterMap() {
return parameterMap;
}
public void setParameterMap(Map<String, String[]> parameterMap) {
this.parameterMap = parameterMap;
}
/**
* @param parameter
*/
private void setPagination(String pagination) {
// TODO Auto-generated method stub
//只有填写了false才不分页
this.setPagination(!"false".equals(pagination));
}
/**
* @param parameter
*/
private void setRows(String rows) {
if(StringUtils.isNotBlank(rows))
this.setRows(Integer.valueOf(rows));
}
/**
* @param parameter
*/
private void setPage(String page) {
if(StringUtils.isNotBlank(page))
this.setPage(Integer.valueOf(page));
}
public PageBean() {
super();
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void setTotal(String total) {
this.total = Integer.parseInt(total);
}
public boolean isPagination() {
return pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
/**
* 获得起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
//上一页
public int getPrevPage() {
return this.page > 1 ? this.page-1 : this.page;
}
//下一页
public int getNexPage() {
return this.page < this.getMaxpage() ? this.page+1 : this.page;
}
//最大页
public int getMaxpage() {
return this.total % this.rows==0 ? this.total / this.rows : (this.total / this.rows)+1;
}
}
mvc框架
中央控制器DispatcherServlet:
package com.shegx.framework;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
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 org.apache.commons.beanutils.BeanUtils;
@WebServlet(name="dispatcherServlet",urlPatterns="*.action")
public class DispatcherServlet extends HttpServlet {
private static final long serialVersionUID = -3108231320735758922L;
private ConfigModel configModel;
@Override
public void init() throws ServletException {
try {
configModel = ConfigModelFactory.build();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// http://localhost:8080/book.action?methodName=list
String uri = req.getRequestURI();
String path = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));// /book
ActionModel actionModel = configModel.pop(path);
if(actionModel == null) {
throw new RuntimeException(path+" action 标签没有配置");
}
try {
// 实例化处理网络请求URL的类
// action就相当于BookAction
Action action = (Action) Class.forName(actionModel.getType()).newInstance();
// 动态封装参数
if(action instanceof ModelDriven) {
ModelDriven md = (ModelDriven) action;
// 将前端jsp参数传递到后端的所有值封装到业务模型类中
BeanUtils.populate(md.getModel(), req.getParameterMap());
}
// 动态调用方法
String code = action.execute(req, resp);
ForwardModel forwardModel = actionModel.pop(code);
// /reg.jsp
String jspPath = forwardModel.getPath();
if(forwardModel.isRedirect()) {
resp.sendRedirect(req.getServletContext()+jspPath);
}else {
req.getRequestDispatcher(jspPath).forward(req, resp);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
子控制器Action
package com.shegx.framework;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface Action {
String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException;
}
ActionSupport:处理if分支问题,动态调用当前类的其它方法
package com.shegx.framework;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 处理if分支问题,动态调用当前类的其它方法add/del/edit
* @author SHE
*
*/
public class ActionSupport implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
String methodName = req.getParameter("methodName");
// this指的是BookAction
Method m = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
m.setAccessible(true);
// 相当于动态调用del(req, resp);
return (String) m.invoke(this, req,resp);
}
}
ModelDriven
package com.shegx.framework;
public interface ModelDriven<T> {
// private Book book = new Book();
T getModel();
}
WEB处理业务层
主要跳转及调用dao方法
/**
*
*/
package com.shegx.web;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.shegx.Dao.BlogDao;
import com.shegx.entity.Blog;
import com.shegx.framework.ActionSupport;
import com.shegx.framework.ModelDriven;
import com.shegx.util.PageBean;
/**
* @author SHE
*
* 2020年6月9日下午5:48:22
* com.shegx.web
*/
public class BlogAction extends ActionSupport implements ModelDriven<Blog>{
private BlogDao blogdao=new BlogDao();
private Blog blog=new Blog();
/* (non-Javadoc)
* @see com.shegx.framework.ModelDriven#getModel()
*/
@Override
public Blog getModel() {
// TODO Auto-generated method stub
return blog;
}
//查询
public String list(HttpServletRequest req,HttpServletResponse resp) {
PageBean pageBean=new PageBean();
pageBean.setRequest(req);
try {
//调用dao方法查询出要展示的内容
List<Blog> list = blogdao.list(blog, pageBean);
req.setAttribute("list", list);
//分页标签保存
req.setAttribute("pageBean", pageBean);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "list";
}
//新增
public String add(HttpServletRequest req,HttpServletResponse resp) {
try {
this.blogdao.add(blog);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "tolist";
}
//跳转新增
public String toadd(HttpServletRequest req,HttpServletResponse resp) {
//bookAdd.jsp
return "toadd";
}
//跳转修改
public String toedit(HttpServletRequest req,HttpServletResponse resp) {
//查询单个要修改的消息
try {
Blog b = this.blogdao.list(blog, null).get(0);
req.setAttribute("b", b);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//blogEdit.jsp
return "toedit";
}
//修改
public String edit(HttpServletRequest req,HttpServletResponse resp) {
try {
this.blogdao.edit(blog);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "tolist";
}
//删除
public String del(HttpServletRequest req,HttpServletResponse resp) {
try {
this.blogdao.del(blog);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "tolist";
}
}
xml配置
<?xml version="1.0" encoding="UTF-8"?>
<!-- <!DOCTYPE config[
<!ELEMENT config (action*)>
<!ELEMENT action (forward*)>
<!ELEMENT forward EMPTY>
<!ATTLIST action
path CDATA #REQUIRED
type CDATA #REQUIRED
>
<!ATTLIST forward
name CDATA #REQUIRED
path CDATA #REQUIRED
redirect (true|false) "false"
>
]> -->
<config>
<action path="/blog" type="com.shegx.web.BlogAction">
<forward name="list" path="/bloglist.jsp" redirect="false" />
<forward name="toadd" path="/blogadd.jsp" redirect=" " />
<forward name="toedit" path="/blogedit.jsp" redirect="" />
<forward name="tolist" path="/blog.action?methodName=list" redirect="" />
</action>
</config>