【JavaWeb】改进纯Servlet(注解开发+模板设计模式+JSP)
创始人
2024-06-02 21:29:02
0

文章目录

  • 1.Servlet注解,解决配置文件
  • 2.第一个注解
  • 3.@WebServlet 的属性
  • 4.反射注解
  • 5.使用模板方法设计模式改造项目
  • 6.JSP

1.Servlet注解,解决配置文件

在这里插入图片描述

2.第一个注解

package com.sdnu.javaweb.servlet;import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;import java.io.IOException;/*** hello servlet** @author Beyong* @date 2023/03/13 08:48**/
@WebServlet
public class HelloServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {}
}

3.@WebServlet 的属性

  • name属性:是用来指定Servlet的名字。
等同于
  • urlPatterns属性:用来指定Servlet的映射路径。
等同于
  • loadOnStartUp属性:用来指定在服务器启动阶段是否加载该Servlet。
等同于
  • value属性:与urlPatterns用法一样,当属性名是value的时候,使用注解时,value属性名可以省略。

注解对象的使用格式:

@注解名称(属性名=属性值,属性名=属性值…)

例子:

package com.sdnu.javaweb.servlet;import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;import java.io.IOException;
import java.io.PrintWriter;/*** hello servlet** @author Beyong* @date 2023/03/13 08:48**/
@WebServlet(name="hello", urlPatterns = {"/hello1", "/hello2", "/hello3"}, loadOnStartup = 1,
initParams = {@WebInitParam(name = "username", value = "root"), @WebInitParam(name = "password", value = "123")})
public class HelloServlet extends HttpServlet {public HelloServlet(){System.out.println("无参构造方法执行");}@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {}
}

4.反射注解

package com.sdnu.javaweb.servlet;import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;import java.lang.annotation.Annotation;/*** 反射注解** @author Beyong* @date 2023/03/13 09:58**/
public class ReflectAnnotation {public static void main(String[] args) throws ClassNotFoundException {Class welcomeServletClass = Class.forName("com.sdnu.javaweb.servlet.HelloServlet");
//        boolean annotationPresent = welcomeServletClass.isAnnotationPresent(WebServlet.class);
//        System.out.println(annotationPresent);if(welcomeServletClass.isAnnotationPresent(WebServlet.class)){WebServlet webServletAnnotation = welcomeServletClass.getAnnotation(WebServlet.class);String[] value = webServletAnnotation.value();for (int i = 0; i < value.length; i++) {System.out.println(value[i]);}}}
}

5.使用模板方法设计模式改造项目

package com.sdnu.oa.web.action;import com.sdnu.oa.utils.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;/*** 使用模板方法 解决类爆炸** @author Beyong* @date 2023/03/13 10:34**/
@WebServlet({"/dept/edit", "/dept/modify", "/dept/save", "/dept/detail", "/dept/list", "/dept/delete"})
public class DeptServlet extends HttpServlet {@Overrideprotected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String servletPath = request.getServletPath();if("/dept/edit".equals(servletPath)){doEdit(request, response);} else if("/dept/modify".equals(servletPath)){doModify(request, response);} else if("/dept/save".equals(servletPath)){doSave(request, response);} else if("/dept/detail".equals(servletPath)){doDetail(request, response);} else if("/dept/list".equals(servletPath)){doList(request, response);} else if("/dept/delete".equals(servletPath)){doDel(request, response);}}private void doEdit(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();String contextPath = request.getContextPath();out.print("          ");out.print("");out.print("	");out.print("		");out.print("		");out.print("	");out.print("	");out.print("		

修改部门

");out.print("
");out.print("
");String deptno = request.getParameter("deptno");Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {conn = DBUtil.getConnection();String sql = "select dname, loc as location from dept where deptno = ?";ps = conn.prepareStatement(sql);ps.setString(1, deptno);rs = ps.executeQuery();if (rs.next()) {String dname = rs.getString("dname");String location = rs.getString("location");out.print(" 部门编号
");out.print(" 部门名称
");out.print(" 部门位置
");}} catch (SQLException e) {e.printStackTrace();} finally {DBUtil.close(conn, ps, rs);}out.print("
");out.print("
");out.print(" ");out.print("");}private void doModify(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("UTF-8");String deptno = request.getParameter("deptno");String dname = request.getParameter("dname");String loc = request.getParameter("loc");Connection conn = null;PreparedStatement ps = null;int count = 0;try {conn = DBUtil.getConnection();String sql = "update dept set dname=?, loc=? where deptno=?";ps = conn.prepareStatement(sql);ps.setString(1, dname);ps.setString(2, loc);ps.setString(3, deptno);count = ps.executeUpdate();} catch (SQLException e) {e.printStackTrace();} finally {DBUtil.close(conn, ps, null);}if(count == 1){request.getRequestDispatcher("/dept/list").forward(request, response);} else {request.getRequestDispatcher("/error.html").forward(request, response);}}private void doSave(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("UTF-8");String deptno = request.getParameter("deptno");String dname = request.getParameter("dname");String loc = request.getParameter("loc");Connection conn = null;PreparedStatement ps = null;int count = 0;try{conn = DBUtil.getConnection();String sql = "insert into dept(deptno, dname, loc) values (?, ?, ?)";ps = conn.prepareStatement(sql);ps.setString(1, deptno);ps.setString(2, dname);ps.setString(3, loc);count = ps.executeUpdate();} catch (SQLException e){e.printStackTrace();}finally {DBUtil.close(conn, ps, null);}if(count == 1){request.getRequestDispatcher("/dept/list").forward(request, response);}else{request.getRequestDispatcher("/error.html").forward(request, response);}}private void doList(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();String contextPath = request.getContextPath();out.print("");out.print("");out.print(" ");out.print(" ");out.print(" 部门列表页面");out.print("");out.print(" ");out.print(" ");out.print("

部门列表

");out.print("
");out.print(" ");out.print(" ");out.print(" ");out.print(" ");out.print(" ");out.print(" ");out.print(" ");//连接数据库,查询所有部门Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {//获取连接conn = DBUtil.getConnection();//获取预编译的数据库操作对象String sql = "select deptno as a, dname, loc from dept";ps = conn.prepareStatement(sql);//执行sql语句rs = ps.executeQuery();//处理结果集int i = 0;while (rs.next()){String deptno = rs.getString("a");String dname = rs.getString("dname");String loc = rs.getString("loc");out.print(" ");out.print(" ");out.print(" ");out.print(" ");out.print(" ");out.print(" ");}} catch (SQLException e) {e.printStackTrace();} finally {DBUtil.close(conn, ps, rs);}out.print("
序号部门列表部门名称操作
"+(++i)+""+deptno+""+dname+"");out.print(" 删除");out.print(" 修改");out.print(" 详情");out.print("
");out.print("
");out.print(" 新增部门");out.print(" ");out.print("");}private void doDetail(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();out.print(" ");out.print("");out.print(" ");out.print(" ");out.print(" 部门详情");out.print(" ");out.print(" ");out.print("

部门详情

");out.print("
");String deptno = request.getParameter("deptno");Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {conn = DBUtil.getConnection();String sql = "select dname, loc from dept where deptno = ?";ps = conn.prepareStatement(sql);ps.setString(1, deptno);rs = ps.executeQuery();if(rs.next()){String dname = rs.getString("dname");String loc = rs.getString("loc");out.print(" 部门编号:"+deptno+"
");out.print(" 部门名称:"+dname+"
");out.print(" 部门位置:北京
");}} catch (SQLException e) {e.printStackTrace();} finally {DBUtil.close(conn, ps, rs);}out.print(" ");out.print(" ");out.print("");}private void doDel(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String deptno = request.getParameter("deptno");Connection conn = null;PreparedStatement ps = null;int count = 0;try{conn = DBUtil.getConnection();conn.setAutoCommit(false);String sql = "delete from dept where deptno = ?";ps = conn.prepareStatement(sql);ps.setString(1, deptno);count = ps.executeUpdate();conn.commit();} catch (SQLException e){if(conn != null){try {conn.rollback();} catch (SQLException ex) {ex.printStackTrace();}}e.printStackTrace();} finally {DBUtil.close(conn, ps, null);}if(count == 1){request.getRequestDispatcher("/dept/list").forward(request, response);}else{request.getRequestDispatcher("/error.html");}} }

6.JSP

JSP本质上是一个Servlet

Servlet职责:收集数据(逻辑处理,业务处理,连接数据库)
jsp职责:展示数据(数据的展示)

  • JSP中写java代码
<%System.out.println("hello jsp");
%>
  • JSP专业注释
<%-- 注释内容 --%>
  • JSP输出
    在这里插入图片描述

相关内容

热门资讯

尚德教育的老师教的怎么样? 尚德教育的老师教的怎么样?尚德教育机构有他们独有的教育方式,直播课程可以互动,没听懂的可以看回放反复...
真三赵云龙之心怎么合成 真三赵云龙之心怎么合成真三赵云龙之心怎么合成杀黄龙掉出来的。不过杀黄龙需要一些装备建议在单人模式下练...
小冰 和 小兵 的英文分别怎么... 小冰 和 小兵 的英文分别怎么写?拜托了各位 谢谢little ice little solder ...
进监狱为什么会被其他的犯人打? 进监狱为什么会被其他的犯人打?为什么呢?因为他们和大家一样相信弱肉强食的丛林法则!!!让你看看他们有...
有一本小说女主角叫林小溪男主角... 有一本小说女主角叫林小溪男主角叫李什么琛一不小心爱上总裁作者:聿天使主角:林小溪,李聿旻你问错地方了
百万新娘之爱无悔英杰是敏君亲生... 百万新娘之爱无悔英杰是敏君亲生的吗王英杰是林敏君跟王绍华的儿子,五十九集说了:王英杰是:林敏君、王绍...
女人在恋爱中通常有哪些误区?如... 女人在恋爱中通常有哪些误区?如何避免?女人在恋爱中误区有付出的多少与爱的程度为正比,如果你总觉得如果...
俩人去马尔代夫旅行结婚需要多少... 俩人去马尔代夫旅行结婚需要多少钱?从天津到马尔代夫旅行结婚需要多少钱 什么时候去合适 待上7天左右 ...
人是不是年龄越大越不敢动感情? 人是不是年龄越大越不敢动感情?人并不是年龄越大越不敢动感情,而是因为年龄越大就看透了这世间所有的感情...
说男主重生如何开加盟鞋店如何赚... 说男主重生如何开加盟鞋店如何赚钱的过程的小说。小说重生之超级商业帝国重生之最强富翁重生1978重生1...
拔萝卜儿歌改编歌曲 拔萝卜儿歌改编歌曲儿歌拔萝卜 拔萝卜. 嗨吆嗨吆,拔萝卜,嗨吆嗨吆,拔不动, 老太婆,快快来,快来帮...
为啥所有的付出再他就是一文不值... 为啥所有的付出再他就是一文不值你人与人之间"心已走远"。。。那就不在付出了,既然看透了,那就没必要付...
贝利亚奥特曼 贝利亚奥特曼贝利亚奥特曼有什么故事?他的性格很不好吗?赛罗奥特曼VS黑暗独眼巨人赛罗大怪兽大战!超银...
找一部日剧~~ 找一部日剧~~之前看到有人推荐过一部日剧,前两个字是“非常”后面几个字我忘了,请问有谁知道吗?应该是...
“一往如初”是什么意思? “一往如初”是什么意思?一往如初是什么意思还是像以前一样。一往:一直,始终。如:像。初:以前那样,一...
闲情倩意后面能连个什么句 闲情倩意后面能连个什么句连词后面也可以加有动词的句子. recoveries accrued to...
世界上最( )的( )... 世界上最( )的( )是世界上最(奇妙)的(感觉)是你爱上一个人的时候.世界上最(舒服)的(...
备胎说车:打蜡 封釉 镀膜 镀... 备胎说车:打蜡 封釉 镀膜 镀晶哪个好常规的保养漆面的方法有打蜡封釉,保持时间长久,和提升漆面的硬度...
下背痛的诊断 下背痛的诊断下背痛的诊断
金鼎猜一个数字 金鼎猜一个数字不知道啊啊啊啊金鼎猜一个数字是9