首页 > 基础资料 博客日记
JavaWeb学习-Servlet优化(MVC思想)
2023-07-25 17:13:33基础资料围观226次
Java资料网推荐JavaWeb学习-Servlet优化(MVC思想)这篇文章给大家,欢迎收藏Java资料网享受知识的乐趣
1. 把多个Servlet变成一个Servlet
(1)访问不同的servlet处理不同的业务
(2)整合Servlet,访问同一个servlet,重写servlet方法处理不同的业务
(3)代码实现
A.fruit.do
package com.fruits.servelet;
import com.fruits.dao.FruitDAO;
import com.fruits.dao.Impl.FruitDAOImpl;
import com.fruits.pojo.Fruit;
import com.fruits.util.StringUtil;
import com.myssm.myspringmvc.ViewBaseServlet;
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.util.List;
@WebServlet("/fruit.do")
public class FruitServlet extends ViewBaseServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String operate = request.getParameter("operate");
if(StringUtil.isEmpty(operate)){
operate = "index"; //如果operate为空,则设置为index
}
switch (operate){
case "index":
Index(request,response);
break;
case "add":
Add(request,response);
break;
case "delete":
Delete(request,response);
break;
case "edit":
Edit(request,response);
break;
case "update":
Update(request,response);
break;
default:
throw new RuntimeException("operate不合法!");
}
}
private void Index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
int pageNo = 1;
String oper = request.getParameter("oper");
//如果oper不是空的,则是通过表单的查询按钮点击过来的,
//如果oper是空的,说明不是通过表单的查询按钮点击过来的,
// 因为index文件可以通过点击分页按钮进入,增删改后也可以进入。
String keyword = null;
if(StringUtil.isNotEmpty(oper)&&"search".equals(oper)){
//是通过表单的查询按钮点击过来的,
//此时,pageNo应该还原为 1 , keyword应该从请求参数中获取
pageNo=1;
keyword = request.getParameter("keyword");
if(StringUtil.isEmpty(keyword)){
keyword = "";
}
session.setAttribute("keyword",keyword);
}else{
//说明不是通过表单的查询按钮点击过来的,(比如点击上一页下一页或者直接在地址栏中输入网址 )
//此时keyword应该从session作用域中获取
String pageNoStr = request.getParameter("pageNo");
if(StringUtil.isNotEmpty(pageNoStr)){
pageNo = Integer.parseInt(pageNoStr);
}
Object keywordobj = session.getAttribute("keyword");
if(keywordobj!=null){
keyword = (String)keywordobj;
}else{
keyword="";
}
}
session.setAttribute("pageNo",pageNo);
FruitDAO fruitDAO=new FruitDAOImpl();
//List<Fruit> fruitList = fruitDAO.getFruitList();
//List<Fruit> fruitList = fruitDAO.getFruitListbypageNo(pageNo);
List<Fruit> fruitList = fruitDAO.getListbypageNo(keyword, pageNo);
session.setAttribute("fruitList", fruitList);
//总记录条数
// int count = fruitDAO.getFruitCount();
int count = fruitDAO.getCount(keyword);
//总页数
int pageCount = count/5+1;
session.setAttribute("pageCount", pageCount);
//此处的视图名称是index,
//那么thymeleaf会将这个 逻辑视图名称 对应到 物理视图 名称上去
//逻辑视图名称:index
//物理视图名称: view-prefix+逻辑视图名称+view-suffix
//所以真是的视图名称为 / index. html
super.processTemplate("index",request,response);
}
private void Add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fidstr = request.getParameter("fid");
int fid = Integer.parseInt(fidstr);
String fname = request.getParameter("fname");
String fpricestr = request.getParameter("price");
int price =Integer.parseInt(fpricestr);
String fcountstr = request.getParameter("fcount");
int fcount =Integer.parseInt(fcountstr);
String remark = request.getParameter("remark");
System.out.println(fid+" "+fname+" "+price+" "+fcount+" "+remark);
FruitDAO fruitDAO = new FruitDAOImpl();
boolean b = fruitDAO.addFruits(new Fruit(fid,fname,price,fcount,remark));
if(b){
System.out.println("添加成功");
}
else{
System.out.println("添加失败");
}
response.sendRedirect("fruit.do");
}
private void Delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fidstr = request.getParameter("fid");
int fid = Integer.parseInt(fidstr);
FruitDAO fruitDAO = new FruitDAOImpl();
boolean b = fruitDAO.deleteFruitById(fid);
if(b){
System.out.println("删除成功!");
}
else{
System.out.println("删除失败!");
}
response.sendRedirect("fruit.do");
}
private void Edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fidstr = request.getParameter("fid");
int fid = Integer.parseInt(fidstr);
FruitDAO fruitDAO1=new FruitDAOImpl();
Fruit fruit1 = new Fruit();
fruit1= fruitDAO1.getFruitById(fid);
request.setAttribute("fruit",fruit1);
super.processTemplate("edit",request,response);
}
private void Update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String fidstr = request.getParameter("fid");
int fid = Integer.parseInt(fidstr);
String fname = request.getParameter("fname");
String fpricestr = request.getParameter("price");
int price =Integer.parseInt(fpricestr);
String fcountstr = request.getParameter("fcount");
int fcount =Integer.parseInt(fcountstr);
String remark = request.getParameter("remark");
FruitDAO fruitDAO=new FruitDAOImpl();
boolean b = fruitDAO.updateFruitById(new Fruit(fid, fname, price, fcount, remark));
if(b){
System.out.println("修改成功");
}
else{
System.out.println("修改失败");
}
/*super.processTemplate("index",request,response);
相当于
request.getRequestDispatcher("index").forward(request,response); 获得的数据还是更新之前的数据
此处需要重定向,目的是重新给IndexServlet发请求,
重新获取fruitList,然后覆盖到session中,这样index.html页面上显示的session中的数据才是最新的。
*/
response.sendRedirect("fruit.do");
}
}
B. 界面代码修改
th:href="@{/fruit.do(fid=${fruit.fid},operate='edit')}"
//js
function delFruit( fid ) {
if(confirm("是否确认删除?")){
window.location.href="fruit.do?fid="+fid+"&operate=delete";
}
}
function page(pageNo) {
window.location.href="fruit.do?pageNo="+pageNo;
}
//add
<input type="hidden" name="operate" value="update">
2. 用反射技术代替switch
fruit.do
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置编码
request.setCharacterEncoding("utf-8");
String operate = request.getParameter("operate");
if(StringUtil.isEmpty(operate)){
operate = "index";
}
//获取当前类中所有的方法
Method[] methods = this.getClass().getDeclaredMethods();
for(Method m : methods){
String name = m.getName();
if(operate.equals(name)){
try {
m.invoke(this,request,response);
return;
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
throw new RuntimeException("operate不合法!");
}
}
3. 引入DispatcherServlet
DispatcherServlet中央控制器,客户端的请求都交给DispatcherServlet,DispatcherServlet根据用户的请求不同对应不同的Servlet。
DispatcherServlet.java
package com.springmvc;
import com.fruits.util.StringUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
@WebServlet("*.do")
public class DispatcherServlet extends HttpServlet {
private Map<String,Object> beanMap = new HashMap<>();
public DispatcherServlet(){
}
public void init(){
try {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("applicationContext.xml");
//1.创建DocumentBuilderFactory
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
//2.创建DocumentBuilder对象
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder() ;
//3.创建Document对象
Document document = documentBuilder.parse(inputStream);
//4.获取所有的bean节点
NodeList beanNodeList = document.getElementsByTagName("bean");
for(int i = 0 ; i<beanNodeList.getLength() ; i++){
Node beanNode = beanNodeList.item(i);
if(beanNode.getNodeType() == Node.ELEMENT_NODE){
Element beanElement = (Element)beanNode ;
String beanId = beanElement.getAttribute("id");
String className = beanElement.getAttribute("class");
Class controllerBeanClass = Class.forName(className);
Object beanObj = controllerBeanClass.newInstance() ;
Method setServletContextMethod = controllerBeanClass.getDeclaredMethod("setServletContext",ServletContext.class);
setServletContextMethod.invoke(beanObj , this.getServletContext());
beanMap.put(beanId , beanObj) ;
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置编码
request.setCharacterEncoding("UTF-8");
//假设url是: http://localhost:8080/pro15/hello.do
//那么servletPath是: /hello.do
// 我的思路是:
// 第1步: /hello.do -> hello 或者 /fruit.do -> fruit
// 第2步: hello -> HelloController 或者 fruit -> FruitController
String servletPath = request.getServletPath();
servletPath = servletPath.substring(1);
int lastDotIndex = servletPath.lastIndexOf(".do") ;
servletPath = servletPath.substring(0,lastDotIndex);
Object controllerBeanObj = beanMap.get(servletPath);
String operate = request.getParameter("operate");
if(StringUtil.isEmpty(operate)){
operate = "index" ;
}
try {
Method method = controllerBeanObj.getClass().getDeclaredMethod(operate,HttpServletRequest.class,HttpServletResponse.class);
if(method!=null){
method.setAccessible(true);
method.invoke(controllerBeanObj,request,response);
}else{
throw new RuntimeException("operate值非法!");
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
applicationContext.xml
<?xml version="1.0" encoding="utf-8" ?>
<beans>
<!-- bean标签的作用是:servletPath中涉及的名字是fruit,那么就要FruitController这个类来处理 -->
<bean id="fruit" class="com.fruits.controller.FruitController"></bean>
</beans>
<!--
xml文档包含三个部分
1)XML声明,放在xml文件的第一行
2)DTD 文档类型定义
3)XML 正文
-->
文章来源:https://www.cnblogs.com/Joyce-mi7/p/16497130.html
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签: