Simple jsp + servlet web development is seldom used ~~ However, the development process is quite useful for later learning frameworks ~~~
So start from a simple project ~~~ Simple addition, deletion, modification, and query ~~~~ First, understand the business process ~~~~
It uses simple repetitive programming work to re-encapsulate-> objects), so we should probably list the source code and steps ~~~
Connection class: JDBC_Connection.java
Static {try {Class. forName (drivername); System. out. println ("Driver created successfully! ");} Catch (ClassNotFoundException e) {System. out. println (" failed to create the driver! Check the driver! "); E. printStackTrace () ;}} public static Connection getConnection () {} public static void free (ResultSet rs, Connection conn, Statement stmt ){}
In the getConnection () method, the following links are obtained ):
conn = (Connection)DriverManager.getConnection(url, username, password);
User operation:
1) Add users
AddUser. jsp
This is the main sentence:
<form action="AddUserServlet" method="post" >
AddUser. java
Public void add (UserVo userVo) {Connection conn = null; PreparedStatement pstm = null; ResultSet rs = null; try {conn = JDBC_Connection.getConnection (); string SQL = "insert into user (id, name, age, tel, adress) value (?,?,?,?,?) "; Pstm = conn. prepareStatement (SQL); pstm. setInt (1, userVo. getId (); pstm. setString (2, userVo. getName (); pstm. setInt (3, userVo. getAge (); pstm. setString (4, userVo. getTel (); pstm. setString (5, userVo. getAdress (); pcmd.exe cuteUpdate (); System. out. println ("added successfully. The added content is as follows:"); System. out. println ("id:" + userVo. getId () + "\ t name:" + userVo. getName () + "\ t age:" + userVo. getAge () + "\ t tel:" + userVo. getTel () + "\ t adress:" + userVo. getAdress ();} catch (Exception e) {e. printStackTrace ();} finally {JDBC_Connection.free (rs, conn, pstm );}}
AddUserServlet. java
Note: doPost (HttpServletRequest request, HttpServletResponse response) throws ...{}
Int id = Integer. parseInt (request. getParameter ("id"); String name = request. getParameter ("name"); int age = Integer. parseInt (request. getParameter ("age"); String tel = request. getParameter ("tel"); String adress = request. getParameter ("adress"); UserVo userVo = new UserVo (); userVo. setId (id); userVo. setName (name); userVo. setAge (age); userVo. setTel (tel); userVo. setAdress (adress); AddUser addUser = new AddUser (); // declare an AddUser object addUser. add (userVo); // call the add () method of the AddUser object, request. getRequestDispatcher ("addUsers. jsp "). forward (request, response); // forward to the specified page
Configuration in web. xml:
<servlet> <servlet-name>AddUserServlet</servlet-name> <servlet-class>com.cn.add.AddUserServlet</servlet-class></servlet><servlet-mapping><servlet-name>AddUserServlet</servlet-name><url-pattern>/AddUserServlet</url-pattern></servlet-mapping>
2) query all users
Query. java
List<UserVo> list = new ArrayList<UserVo>(); try{ conn = JDBC_Connection.getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery("select * from user"); while(rs.next()){ UserVo userVo = new UserVo(); userVo.setId(rs.getInt("id")); userVo.setName(rs.getString("name")); userVo.setAge(rs.getInt("age")); userVo.setTel(rs.getString("tel")); userVo.setAdress(rs.getString("adress")); list.add(userVo); }}
ShowAllUserServlet. java
List<UserVo> list = new ArrayList<UserVo>();Query query = new Query();list = query.showUser();request.setAttribute("list", list); request.getRequestDispatcher("showAllUser.jsp").forward(request, response);
ShowAllUser. jsp
<C: forEach items = "$ {list}" var = "list"> <tr> <td >$ {list. id} </td> <td >$ {list. name} </td> <td >$ {list. age} </td> <td >$ {list. tel }</td> <td >$ {list. adress} </td> <a href = "QueryUserByIdServlet? Id =$ {list. id} "> modify </a> <a href =" DeleteUserServlet? Id =$ {list. id} "> Delete </a> </td> </tr> </c: forEach>
(3) query a user
QueryById. java
pstmt = conn.prepareStatement("select * from user where id = ?");pstmt.setInt(1, id);rs = pstmt.executeQuery();return userVo;
QueryUserById. java
UserVo userVo = new UserVo();QueryById queryById = new QueryById();userVo = queryById.queryUserById(id);request.setAttribute("userVo", userVo); request.getRequestDispatcher("updateUser.jsp").forward(request, response);
UpdateUser. java
String sql = "update user set id = ?,name = ?,age = ?,tel = ?,address = ? where id = ?";
UpdateUserServlet. java
int id = Integer.parseInt(request.getParameter("id"));String name = request.getParameter("name");int age = Integer.parseInt(request.getParameter("age"));String tel = request.getParameter("tel");String adress = request.getParameter("adress");UserVo userVo =new UserVo();userVo.setId(id);userVo.setName(name);userVo.setAge(age);userVo.setTel(tel);userVo.setAdress(adress);UpdateUser updateUser = new UpdateUser();updateUser.update(userVo);response.sendRedirect("ShowAllUserServlet");
(4) Delete a user
DeleteUser. java
String sql = "delete from user where id = ?";
DeleteUserServelt. java
int id = Integer.parseInt(request.getParameter("id"));DeleteUser deleteUser = new DeleteUser();deleteUser.deleteUser(id);response.sendRedirect("ShowAllUserServlet");
You can also use the Filter to configure Chinese characters.
Zh_Filter.java
public class Zh_Filter implements Filter { public void doFilter(ServletRequest request , ServletResponse response, FilterChain chain) throws IOException, ServletException{ request.setCharacterEncoding("gb2312"); response.setCharacterEncoding("gb2312"); chain.doFilter(request, response); }}
Configure in web. xml
<filter> <filter-name>filter</filter-name> <filter-class>com.cn.filter.Zh_Filter</filter-class> </filter><filter-mapping> <filter-name>filter</filter-name> <url-pattern>/*</url-pattern></filter-mapping>
In addition, small knowledge points:
1) The following is a prompt on the Internet about the difference between servlet forword and redirect:
Forward is a server request resource. The server directly accesses the URL of the target address, reads the response content of that URL, and then sends the content to the browser, the browser does not know where the content sent by the server comes from, so its address bar is still the original address.
Redirect means that the server sends a status code based on logic to tell the browser to request the address again. Generally, the browser will re-request the address with all the parameters just requested, so the session and request parameters can be obtained.
Forward: the data in the request will not be lost, and sendRedirect: the data in the request will be lost.
The former is only the redirection of control in the container, and the address after the redirection is not displayed in the address bar of the client browser; the latter is a complete jump, and the browser will get the jump address, and resend the request link. In this way, the link address after the jump is displayed in the address bar of the browser. Therefore, the former is more efficient. When the former can meet the needs, try to use the forward () method, and this will also help to hide the actual link. In some cases, for example, to jump to a resource on another server, you must use the sendRedirect () method.
2)
Request. getAttribute () is used to obtain data in Request. setAttribute ().
Request. getParameter () is the data obtained from the form Request.
This article from "tired also happy D" blog, please be sure to keep this source http://zhangzhang.blog.51cto.com/6250085/1302655