jsp MVC学习笔记

时间:2023-11-29 09:38:32

Model层:

四个包:

com.maker.bean存放数据库里面的字段信息。

package com.maker.bean;

public class User
{ private String username;
private String password;
private int id;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
} }

在编写get set方法可以编写完数据库字段之后生成。

com.maker.util包:

package com.maker.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException; public class DBUtil
{
public Connection getConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException
{
String Url="jdbc:mysql://localhost/jsptest";
String Driver="com.mysql.jdbc.Driver";
String username="root";
String password="w111206";
Class.forName(Driver).newInstance();
Connection conn = DriverManager.getConnection(Url,username,password);
return conn; }
public void closeConnection(Connection conn)
{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }

里面包含数据库连接打开,关闭代码

com.maker.dao包:

package com.maker.dao;
import java.sql.*;
import java.util.ArrayList; import com.maker.bean.User;
import com.maker.util.DBUtil;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement; public class UserData
{
public void Del(int Id)
{
String sql="delete from user where id="+Id;
DBUtil util=new DBUtil();
Connection conn=null;
try {
conn=util.getConnection();
PreparedStatement pstmt=(PreparedStatement) conn.prepareStatement(sql); pstmt.executeUpdate(); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
util.closeConnection(conn);
} }
public void save(User us)
{
String sql="insert into User (username,password) values(?,?)";
DBUtil util=new DBUtil();
Connection conn = null;
try {
conn = util.getConnection();
PreparedStatement pstmt=(PreparedStatement) conn.prepareStatement(sql);
pstmt.setString(1, us.getUsername());
pstmt.setString(2,us.getPassword());
pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace();
}
finally{
util.closeConnection(conn);
}
}
public ArrayList List()
{
ArrayList list=new ArrayList();
String sql="select * from user";
DBUtil util=new DBUtil();
Connection conn = null;
try {
conn = util.getConnection();
java.sql.Statement stmt=conn.createStatement();
java.sql.ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
int id=rs.getInt(1);
String username=rs.getString(2);
String password=rs.getString(3);
User us=new User();
us.setId(id);
us.setPassword(password);
us.setUsername(username);
list.add(us);
} } catch (Exception e) { e.printStackTrace();
}
finally{
util.closeConnection(conn);
}
return list;
} }

里面是数据库操作代码

Control控制层:

com.maker.Servlet包

package com.maker.Sevlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.maker.bean.User;
import com.maker.dao.UserData; public class UpdateServlet extends HttpServlet { /**
* Constructor of the object.
*/
public UpdateServlet() {
super();
} /**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { String action=request.getParameter("action");
int Id=Integer.parseInt(action); UserData da=new UserData();
da.Del(Id);
ArrayList<User> list=da.List();
request.setAttribute("UserList",list); request.getRequestDispatcher("/index.jsp").forward(request, response);
} /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { String action=request.getParameter("action");
int Id=Integer.parseInt(action); UserData da=new UserData();
da.Del(Id);
ArrayList<User> list=da.List();
request.setAttribute("UserList",list);
request.setAttribute("Id",Id); request.getRequestDispatcher("/index.jsp").forward(request, response);
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }

里面是Servlet,如果测试里面数据传值等是否正确,想输出一个数值,可采用

PrintWriter out=response.getWriter();
out.println("<script>alert('"+name+")<script>");
也可以向jsp页面传值,然后在jsp页面显示。
View显示层:
<%@page import="com.maker.bean.User"%>
<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</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">
-->
</head> <body>
<table>
<%
@SuppressWarnings("unchecked")
ArrayList<User> arr=(ArrayList<User>)request.getAttribute("UserList");
for(User us:arr)
{
out.println("<tr>");
out.println("<td>"+us.getUsername()+"</td>");
out.println("<td>"+us.getPassword()+"</td>");
out.println("<td><a href='servlet/UpdateServlet?action="+us.getId()+"'>编辑</a></td>");
out.println("</tr>");
}
%>
<br/>
<br/>
</table>
<table>
<c:forEach var="fuwa" items="${UserList}" >
<tr>
<td>
 <c:out value="${fuwa.id}" />
</td>
<td><td><a href="servlet/UpdateServlet?action=${fuwa.id}">编辑</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>