Servlet
Servlet is the foundation of JSP (Java Servlet Pages), which is essentially a Java class running on the server side, receiving requests from clients and responding.
Tomcat's containers are divided into four levels: Container, Engine, Host and Servlet. The relationship is as follows
The servlet's life cycle is as follows. When the request first arrives at the servlet, the server loads the servlet instance and calls init() to complete initialization. Then, the servlet instance is resident in memory. When the request arrives again, the servlet instance can directly call the service method to select doPost/doGet to respond to the request. Call destroy() until the server is shut down to destroy the servlet. In addition to the server loading servlet at page request, you can also configure the < load startup > tag in the web.xml file to set the servlet loading at server startup. The smaller the number, the higher the priority of loading. When the servlet is modified, it is also automatically reloaded.
To create a Servlet, we first need to inherit the HttpServlet class. The abstract class is a Servlet that implements the Http protocol. Its parent class is the abstract class GenericServlet. This is a protocol independent Servlet, which is also implemented in the Servlet interface. The interface has three methods: Init(), destroy(), and service().
In the servlet class, you need to override the doGet() and doPost() methods. In these two methods, you define the operations to be performed when the get and post methods request the servlet.
public class FirstServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("with Post Mode request Servlet"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("with Get Mode request Servlet"); //console output //Return html page content through response response.setContentType("text/html;charset=UTF-8"); PrintWriter out=response.getWriter(); out.println("<h1>Servlet Returned page</h1>"); } }
Finally, you need to register the servlet in the web.xml file. As follows, register a servlet named FirstServlet. The corresponding Java class is in servlet.FirstServlet. Its url is: website root path / servlet/FirstServlet. When the browser requests to get http://localhost:8080/FirstApp_war_exploded/servlet/FirstServlet Page output: the page returned by the Servlet
<servlet> <servlet-name>FirstServlet</servlet-name> <servlet-class>servlet.FirstServlet</servlet-class> <load-on-startup>1</load-on-startup> <!--Priority of auto mount on server startup--> </servlet> <servlet-mapping> <servlet-name>FirstServlet</servlet-name> <url-pattern>/servlet/FirstServlet</url-pattern> </servlet-mapping>
Using a page object in a servlet page is similar to using a JSP, with the following correspondence. For example, in JSP, get the parameters from the client through requests. Getparameter(), then in servlet, you can do the same operation through req.getParameter()
You can also load initialization parameters in servlet, configure it in web.xml file, and then call this.getInitParameter("username") in servlet to get initialization parameters.
<servlet> <servlet-name>FirstServlet</servlet-name> <servlet-class>servlet.FirstServlet</servlet-class> <init-param> <param-name>username</param-name> <param-value>petty thief</param-value> </init-param> </servlet>
MVC development mode
Based on Java development Model 1, Model 2, MVC development mode, is produced. The Model model refers to the object class structure involved in the development, which is implemented by JavaBean and used to interact with the database, read and store the data. View view refers to the interface that displays the data to the user and completes the interaction with the user through the JSP page. The Controller controller completes the logic control function of the web, and the Servlet can process the user's request and complete the required operation. MVC completes the further division of the website development function, which makes the code development and maintenance more efficient.
Sometimes, in order to interact with the database, a DAO(Data Access Object) interface is encapsulated to provide basic API operations such as adding, deleting, modifying and querying database objects
A shopping cart function is realized through MVC design mode. Click the item as shown below to add to the shopping cart, and view and delete the shopping cart
First, the Module class is designed: Cart, which can be used to add and delete goods
package modules; import java.util.HashMap; import java.util.Map; public class Cart { private HashMap<Item,Integer> goods; private double totalPrice; public Cart(){ goods=new HashMap<Item,Integer>(); totalPrice=0.0; } public HashMap<Item, Integer> getGoods() { return goods; } public double getTotalPrice() { return totalPrice; } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } //Calculate the total amount of shopping cart public void calculateTotal(){ double sum=0; for (Map.Entry<Item, Integer> entry : goods.entrySet()) { Item item=entry.getKey(); int num= entry.getValue(); sum+=item.getPrice()*num; } this.setTotalPrice(sum); } //Add item to cart public boolean addGoods(Item item,int num){ if (goods.containsKey(item)) //If the item is already in the cart, the quantity increases goods.put(item,goods.get(item)+num); else goods.put(item,num); //If not, add to cart this.calculateTotal(); return true; } //Remove item from cart public void removeGoods(Item item){ goods.remove(item); calculateTotal(); } }
Then implement the View, cart View cart.jsp, and take out the cart object saved in the session and display it on the JSP page
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %> <%@ page import="modules.Cart" %> <%@ page import="modules.Item" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Shopping cart page</title> <link type="text/css" rel="stylesheet" href="css/style1.css"/> <script language="javascript"> function delcfm() { if (!confirm("Are you sure you want to delete?")) { window.event.returnValue = false; } } </script> </head> <body> <h1>My shopping cart</h1> <a href="index.jsp">home page</a> >> <a href="index.jsp">List of commodities</a> <hr> <div id="shopping"> <form action="" method=""> <table> <tr> <th>Trade name</th> <th>item pricing</th> <th>commodity price</th> <th>Purchase quantity</th> <th>operation</th> </tr> <% //Take out the cart object from the session to traverse and display the contents of the shopping cart if (request.getSession().getAttribute("cart") != null) { //Determine whether there is a shopping cart object in the session Cart cart = (Cart) request.getSession().getAttribute("cart"); HashMap<Item, Integer> goods = cart.getGoods(); Set<Item> Item = goods.keySet(); Iterator<Item> it = Item.iterator(); while (it.hasNext()) { Item i = it.next(); %> <tr name="products" id="product_id_1"> <td class="thumb"><img src="images/<%=i.getPicture()%>"/><a href=""><%=i.getName()%> </a></td> <td class="number"><%=i.getPrice() %> </td> <td class="price" id="price_id_1"> <span><%=i.getPrice() * goods.get(i) %></span> <input type="hidden" value=""/> </td> <td class="number"> <%=goods.get(i)%> </td> <td class="delete"> <a href="servlet/CartServlet?action=delete&id=<%=i.getId()%>" οnclick="delcfm();">delete</a> </td> </tr> <% } %> <!--End of traversal shopping cart--> </table> <div class="total"><span id="total">Total:<%=cart.getTotalPrice() %>¥</span></div> <% } %> <div class="button"><input type="submit" value=""/></div> </form> </div> </body> </html>
Finally, the Controller is implemented to process the user's request from the page through the CartServlet. The action in the Get request is judged in the doGet() function, which includes adding, displaying and deleting the shopping cart. Three functions are defined to perform three operations
package servlets; import modules.Cart; import modules.Item; import modules.ItemList; 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 java.io.IOException; @WebServlet(name = "CartServlet", value = {"/servlet/CartServlet"}) public class CartServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get the action type in the request and judge String action = request.getParameter("action"); if (action.equals("add")) { //Add cart if (addToCart(request, response)) { request.getRequestDispatcher("/success.jsp").forward(request, response); } else { request.getRequestDispatcher("/fail.jsp").forward(request, response); } } if (action.equals("show")) //Show cart request.getRequestDispatcher("/cart.jsp").forward(request, response); if (action.equals("delete")) { //Delete cart item deleteFromCart(request, response); request.getRequestDispatcher("/cart.jsp").forward(request, response); } } //Add shopping cart action private boolean addToCart(HttpServletRequest request, HttpServletResponse response) { int itemId = Integer.parseInt(request.getParameter("id")); int num = Integer.parseInt(request.getParameter("num")); ItemList itemList = new ItemList(); Item item = itemList.getItemById(itemId); Cart cart = (Cart) request.getSession().getAttribute("cart"); //Remove the shopping cart object from the session if (cart == null) { cart = new Cart(); } if (cart.addGoods(item, num)) { request.getSession().setAttribute("cart", cart); return true; } else return false; } //Delete shopping cart operation private boolean deleteFromCart(HttpServletRequest request, HttpServletResponse response) { int itemId = Integer.parseInt(request.getParameter("id")); ItemList itemList = new ItemList(); Item item = itemList.getItemById(itemId); Cart cart = (Cart) request.getSession().getAttribute("cart"); cart.removeGoods(item); request.getSession().setAttribute("cart", cart); return true; } }