Servlet是比较基础的的客户端与服务器数据交互程序,通过HttpServletRequest请求和HttpServletResponse响应,可以基本实现web程序开发。
1、Servlet基础代码
public class choServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name="hello"; response.setContentType("text/html;charset=utf-8"); //传值 request.getSession().setAttribute("name", name); /*request.setAttribute("name", name);*/ //返回页面 转发 RequestDispatcher d = request.getRequestDispatcher("/WEB-INF/jsp/chomod.jsp"); d.forward(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }
2.web.xml配置
<servlet> <servlet-name>choServlet</servlet-name> <servlet-class>valid.servlet.choServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>choServlet</servlet-name> <url-pattern>/servlet/choServlet</url-pattern> </servlet-mapping>
3.jsp获取显示
<div>${name}</div>
<%-- <div><%=session.getAttribute("name") %></div> --%>
以上就可以简单实现后台与前端的数据交互