|
| 1 | +package com.baeldung.javaeeannotations; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.PrintWriter; |
| 5 | + |
| 6 | +import javax.servlet.ServletConfig; |
| 7 | +import javax.servlet.ServletException; |
| 8 | +import javax.servlet.annotation.HttpConstraint; |
| 9 | +import javax.servlet.annotation.HttpMethodConstraint; |
| 10 | +import javax.servlet.annotation.ServletSecurity; |
| 11 | +import javax.servlet.annotation.WebInitParam; |
| 12 | +import javax.servlet.annotation.WebServlet; |
| 13 | +import javax.servlet.http.HttpServletRequest; |
| 14 | +import javax.servlet.http.HttpServletResponse; |
| 15 | + |
| 16 | +@WebServlet( |
| 17 | + name = "BankAccountServlet", |
| 18 | + description = "Represents a Bank Account and it's transactions", |
| 19 | + urlPatterns = {"/account", "/bankAccount" }, |
| 20 | + initParams = { @WebInitParam(name = "type", value = "savings") } |
| 21 | + ) |
| 22 | +@ServletSecurity( |
| 23 | + value = @HttpConstraint(rolesAllowed = {"admin"}), |
| 24 | + httpMethodConstraints = {@HttpMethodConstraint(value = "POST", rolesAllowed = {"admin"})} |
| 25 | + ) |
| 26 | +public class AccountServlet extends javax.servlet.http.HttpServlet { |
| 27 | + |
| 28 | + String accountType = null; |
| 29 | + |
| 30 | + @Override |
| 31 | + public void init(ServletConfig config) throws ServletException { |
| 32 | + accountType = config.getInitParameter("type"); |
| 33 | + } |
| 34 | + |
| 35 | + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { |
| 36 | + PrintWriter writer = response.getWriter(); |
| 37 | + writer.println("<html>Hello, I am an AccountServlet!</html>"); |
| 38 | + writer.flush(); |
| 39 | + } |
| 40 | + |
| 41 | + public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { |
| 42 | + double accountBalance = 1000d; |
| 43 | + double interestRate = Double.parseDouble(request.getAttribute("interest").toString()); |
| 44 | + |
| 45 | + String paramDepositAmt = request.getParameter("dep"); |
| 46 | + double depositAmt = Double.parseDouble(paramDepositAmt); |
| 47 | + |
| 48 | + accountBalance = accountBalance + depositAmt; |
| 49 | + |
| 50 | + PrintWriter writer = response.getWriter(); |
| 51 | + writer.println("<html> Balance of " + accountType + " account is: " + |
| 52 | + accountBalance + "<br> This account bares an interest rate of " + interestRate + |
| 53 | + " % </html>"); |
| 54 | + writer.flush(); |
| 55 | + |
| 56 | + } |
| 57 | +} |
0 commit comments