标签:etc void action lin pre web app extends amp code
form.html
<html>
<body>
<h1 align=‘center‘>Beer Selection Page</h1>
<form method="post"
action="SelectBeer.do">
Select
<p>
Color:
<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>
<option value="red"> red</option>
</select>
<br/><br/>
<center>
<input type="submit">
</center>
</form>
</body>
</html>
BeerSelect.java
package com.example.web;
import com.example.model.BeerExpert;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* Created by LTN on 2016/10/30.
*/
public class BeerSelect extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws IOException ,ServletException{
response.setContentType("text/html");
String c = request.getParameter("color");
BeerExpert expert = new BeerExpert();
List result = expert.getBrands(c);
request.setAttribute("styles", result);
RequestDispatcher view = request.getRequestDispatcher("result.jsp");
view.forward(request, response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)throws IOException,ServletException {
doGet(request,response);
}
}
BeerExpert.java
package com.example.model;
import java.util.ArrayList;
import java.util.List;
public class BeerExpert
{
public List getBrands(String color)
{
List<String> brands = new ArrayList<String>();
if ( color.equals("amber") )
{
brands.add("Jack Amber");
brands.add("Red Moose");
}
else
{
brands.add("Jail Pale Ale");
brands.add("Gout Stout");
}
return (brands);
}
}
result.jsp
<%@ page import="java.util.*" %>
<html>
<body>
<h1 align="center">Beer Recommendations JSP</h1>
<p>
<%
ArrayList styles = (ArrayList)request.getAttribute("styles");
Iterator it = styles.iterator();
while(it.hasNext()) {
out.print("<br>try " + it.next());
}
%>
</body>
</html>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>Ch3 Beer</servlet-name>
<servlet-class>com.example.web.BeerSelect</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Ch3 Beer</servlet-name>
<url-pattern>/SelectBeer.do</url-pattern>
</servlet-mapping>
</web-app>
《Head First Servlets & JSP》-3-1st servlet MVC demo
标签:etc void action lin pre web app extends amp code
原文地址:http://www.cnblogs.com/myitroad/p/6192518.html