标签:style blog http color io os 使用 java ar
假如,现在我做了一个给用户使用的html页面:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <h1>helloPost!</h1> <body> <form method="post" action="SelectBeer.do"> <p>Select beer</p> <select name="color" size="1"> <option value="light"> light</option> <option value="amber"> amber</option> <option value="brown"> brown</option> <option value="dark"> dark</option> </select> <center> <input type="submit"> </center> </form>> </body> </html>
<form method="post" action="SelectBeer.do"> 中的SelectBeer.do有点像资源名。最终会被http:/127.0.0.1:8080/文件名/SelectBeer.do 的形式访问到。
这是我又写了后台servlet程序,实现了get,post的方法:
package com.example.web; import java.io.IOException; import java.io.PrintWriter; import java.sql.Time; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class HelloWorld2 */ @WebServlet("/HelloWorld2") public class HelloWorld2 extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public HelloWorld2() { // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @SuppressWarnings("deprecation") protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter out = response.getWriter(); //out.print("helloWorld"); //String outPut=request.getParameter("input"); out.print(request); System.out.println(request); String c = request.getParameter("color"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Beer Selection Advice<br>"); String c = request.getParameter("color"); out.println("<br> Got beer color"+c); System.out.println(c); } }
把html放到servlet目录下,发现前后端无法通信。
这时还需要在web.xml下进行设置。
<servlet> <servlet-name>123123</servlet-name> <servlet-class>com.example.web.HelloWorld2</servlet-class> </servlet> <servlet-mapping> <servlet-name>123123</servlet-name> <url-pattern>/SelectBeer.do</url-pattern> </servlet-mapping>
servlet:可以自己设置servlet的资源名字, 然后写上对应的servlet类名
servlet-mapping:自己的servlet与资源的映射关系
发送Post请求:
返回:
发送get请求:
参考:head first,servlet & jsp
标签:style blog http color io os 使用 java ar
原文地址:http://www.cnblogs.com/huhuuu/p/3993019.html