如何用Jsp开发一个web项目

我最近用jsp代码来实现web项目,jsp虽然在应用中不是特别流行,但是用起来还是比较方便的,我总结了两种jsp通过网页上修改数据实现在数据库中的数据的增删改。
首先简单的介绍一下jsp:JSP(全称JavaServer Pages)是由Sun Microsystems公司主导创建的一种动态网页技术标准。JSP部署于网络服务器上,可以响应客户端发送的请求,并根据请求内容动态地生成HTML、XML或其他格式文档的Web网页,然后返回给请求者。JSP技术以Java语言作为脚本语言,为用户的HTTP请求提供服务,并能与服务器上的其它Java程序共同处理复杂的业务需求。Jsp的特点之处就是它可以将Java代码和特定变动内容嵌入到静态的页面中,实现以静态页面为模板,动态生成其中的部分内容,也就是可以在写网页的地方同时写Java代码,也就可以和数据库相连。我介绍的第一种开发方式就是利用的这一特点。
一、项目开发全用jsp文件来写
我是用idea开发的项目,其整体结构大致如下:

整个项目完全不需要java文件,因为Java代码也放到了jsp文件中,用这种方法开发项目,可以省去很多代码,不需要在建立实体类接收数据库中的数据,前端后端一体化,什么时候用到数据库的数据即可建立连接,jsp中链接数据库的主要步骤:
1.为了和mysql数据库相连首先添加mysql-connector-java-8.0.16.jar的依赖,然后为项目添加jstl.jar和standard.jar的外包以便更方便的使用数据库数据。
2.为用到数据库数据的jsp文件添加头部

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

连接数据库的方式:

<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
                   url="jdbc:mysql://localhost:3306/dw?useUnicode=true&characterEncoding=utf-8"
                   user="root"  password="root"/>
Sql语句的书写:
<sql:query dataSource="${snapshot}" var="result">
    SELECT * from student;
</sql:query>

显示数据库数据:

<c:forEach var="row" items="${result.rows}">
    <tr>
        <td><c:out value="${row.stu_id}"/></td>
        <td><c:out value="${row.stu_pwd}"/></td>
        <td><c:out value="${row.stu_name}"/></td>
        <td><c:out value="${row.stu_email }"/></td>
        <td><c:out value="${row.stu_major }"/></td>
        <td><c:out value="${row.stu_gra}"/></td>
        <td><a href = "student/student_update.jsp?id=${row.stu_id }">修改</a></td>
        <td><a href ="student/student_delete.jsp?id=${row.stu_id }"onclick="return(confirm('确定删除该学生?'))">删除</a></td>
    </tr>
</c:forEach>

而且在jsp间传递参数的方式也很简单,
form action=“http://localhost:8080/Summertrain_war_exploded/student/student_add_rela.jsp” method=“post” onSubmit=“return isValid(this)”; >

   <table>
        <caption>学生添加</caption>
        <tr><td>学生ID:</td><td><textarea name="stu_id" cols="50" rows="2"></textarea></td></tr>

在action所对用的页面即可用request.getParameter()函数的到数据

String id = new String(request.getParameter(“stu_id”).getBytes(“ISO-8859-1”),“UTF-8”);
3.为了将jsp页面显示出来,要配置tomcat的环境

在实现实现修改、添加和删除数据库数据时可用Java代码,我贴上部分代码供参考:


<%@ page language=“java” import=“java.util.,java.sql.” pageEncoding=“utf-8”%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"😕/"+request.getServerName()+":"+request.getServerPort()+path+"/";


%>

<title>修改个人密码</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<%
String pwd = new String(request.getParameter("password").getBytes("ISO-8859-1"),"UTF-8");
String newpwd = new String(request.getParameter("pwd").getBytes("ISO-8859-1"),"UTF-8");
Object stu_id = session.getAttribute("stu_id");//接收参数
String user = String.valueOf(stu_id);
String driverClass = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/dw";
String username = "root";
String password = "root";
Class.forName(driverClass);//加载驱动
Connection conn = DriverManager.getConnection(url,username,password);//得到连接
PreparedStatement pStmt = conn.prepareStatement("select * from student where stu_id = ?");
pStmt.setString(1,user);
ResultSet re = pStmt.executeQuery();

if(re.next()) {
    PreparedStatement pStmt1 = conn.prepareStatement("select * from student where stu_id = ?and stu_pwd = ?");
    pStmt1.setString(1, user);
    pStmt1.setString(2, pwd);
    ResultSet re1 = pStmt1.executeQuery();
    if (re1.next()) {
        PreparedStatement tmt = conn.prepareStatement("update   student set  stu_pwd= '"+ newpwd +"'where stu_id = ?");
        tmt.setString(1, user);
        int rst = tmt.executeUpdate();
        if (rst != 0) {
            out.println("<script language='javascript'>alert('密码更新成功!');window.location.href='student/student_login.jsp';</script>");
        } else {
            out.println("<script language='javascript'>alert('密码更新失败!');window.location.href='student/student_pwd_update.jsp';</script>");
        }
    } else {
        out.println("<script language='javascript'>alert('密码错误!请输入正确的密码!');window.location.href='student/student_pwd_update.jsp';</script>");
    }
}
else {
    out.println("<script language='javascript'>alert('有错误!请输入正确的密码!');window.location.href='student/student_pwd_update.jsp';</script>");
}

%>

```

此种方式虽然确实简单,但是安全性、可移植性、可修改性都较差。
二、用JavaBean+servlet+jsp方式开发项目
这种方法有效的将Java代码和网页的代码分离,通过servlet层来成为前后端连接的中间层。
其大致结构如下:

Bean层主要为实体类,Dao层中是和数据库直接相连的类,包括数据库连接和数据库增删改查的函数,Dom层是我放xml文件的地方,Servlet层根据相关操作写相对的代码,如显示写一个jdbcfindservlet代码来,添加操作写jdbcaddservlet,修改信息写一个jdbcupdateservlet等等,同时为有操作的界面写jsp代码并用 request.getRequestDispatcher("").forward(request, response); 进行连接。我的Unil是解析xml文件以及进行数据集成的地方,这也是此种方式的一大优点,可以通过集成简化操作,在新增数据库,修改数据库字段名的时候可修改一小部分代码即可。解析xml表、连接数据库部分和实体类部分我就不展示了,主要展示servlet与jsp页面的交互:

package Servlet;
import java.io.IOException;
import Util.*;
import bean.*;

import javax.servlet.annotation.WebServlet;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.xml.sax.SAXException;
public class CourseFindServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private String xmlpath="E:\\daima\\shiyan\\src\\Dom\\course2.xml";
    /**
     * 构造函数
     */
    public CourseFindServlet()
    {
        super();
    }

    /**
     * 初始化
     */
    public void init() throws ServletException
    {}

    /**
     * doGet()方法
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        doPost(request, response);
    }

    /**
     * doPost()方法
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {

        try {
            CourseDaoUtil courseDaoUtil=new CourseDaoUtil();
            CourseDaoUtil courseDaoUtil2=new CourseDaoUtil();
            courseDaoUtil2.setXmlPath(xmlpath);
            List<CourseUtil> list2 = courseDaoUtil2.getAllCourseUtilUtil();
            List<CourseUtil> list = courseDaoUtil.getAllCourseUtilUtil();
            request.setAttribute("list", list);
            request.setAttribute("list2", list2);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        request.getRequestDispatcher("course/course_manage.jsp").forward(request, response);
    }
    /**
     * 销毁
     */
    public void destroy()
    {
        super.destroy();
    }
}

Request.setAttribute()函数来传参, String cid = req.getParameter("cid");接收参数。
个人见解:这两种方式都可以实现我们想要的结果,但从长远来看还是第二种方式更加适合项目的开发,在新增数据库或是新增属性时稳定性更佳,当然还是根据自己的需要选择更优的开发方式。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值