实例演示:
业务java类MainService
控制层MainServlet
两种方法
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
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 com.service.MainService;
/**
* Servlet implementation class MainServlet
*/
public class MainServlet extends HttpServlet {
private MainService service = new MainService();
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MainServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String uri = request.getRequestURI();
//方法一
// String[] op= uri.split("/");
// if(op != null && op[op.length-1].equals("add.do")){
// String content = service.add();
// out.write(content);
// }else if(op != null && op[op.length-1].equals("delete.do")){
// String content = service.delete();
// out.write(content);
// }
//
//方法二
int index = uri.lastIndexOf("/");
if(index !=-1) {
String operate = uri.substring(index+1, uri.length());
if("add.do".equals(operate)) {
String content =service.add();
out.write(content);
}else if("delete.do".equals(operate)) {
String content =service.delete();
out.write(content);
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
<%@ 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>测试链接切割</title>
</head>
<body>
<a href="add.do?name=123">add</a>
<a href="delete.do">delete</a>
</body>
</html>