Servlet实现添加商品
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="shangpin" method="post"> <table><tr> <td>商品名称:</td> <td><input type="text" name="name"/></td> </tr><tr> <td>编号:</td> <td><input type="text" name="number"/></td> </tr><tr> <td>价格:</td> <td><input type="text" name="price"/></td> </tr><tr> <td>产地:</td> <td><input type="text" name="address"/></td> </tr> <tr> <td><input type="submit" value="提交"/></td> <td><input type="reset" value="重置"/></td> </tr></table> </form></body> </html>
package com.hanqi.web;import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** Servlet implementation class HWshangpin*/
public class HWshangpin extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public HWshangpin() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub//response.getWriter().append("Served at: ").append(request.getContextPath());response.setContentType("text/html");response.setCharacterEncoding("UTF-8");String name=new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");String number=request.getParameter("number");String price=request.getParameter("price");String address=new String(request.getParameter("address").getBytes("ISO-8859-1"),"UTF-8");if(name==null||number==null||price==null||address==null){response.getWriter().write("请完善信息,5秒后返回添加页面!");response.setHeader("refresh", "5;shangpin.jsp");}else{response.getWriter().write("添加成功!");response.getWriter().write("商品名:"+name+",编号:"+number+",价格:"+price+",产地:"+address);}}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}
运行结果: