Hello I know That this question has been asked before But unfortuanetly I didn t find among the answers proposed the one suitable for me
I m still new with J2ee lookin' forward for ur help
This is my code
login.jsp
<!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>Login page</title>
</head>
<body>
<form action="" method="post"/>
<br> UserId: <input type="text" name="userId"/>
<br> password<input type="password" name="password"/>
<br><input type="submit"/>
</form>
</body>
</html>
LoginServlet.java
package org.islem.login;
import java.io.IOException;
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 org.islem.login.service.LoginService;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String userId,password;
userId= request.getParameter("userId");
System.out.println(userId);
password= request.getParameter("password");
LoginService loginService= new LoginService();
boolean result= loginService.authenticate(userId, password);
if (result)
{
response.sendRedirect("home.jsp");
return;
}
else
{
response.sendRedirect("login.jsp");
return;
}
}
}
LoginService.java
package org.islem.login.service;
public class LoginService {
public boolean authenticate (String userId,String password)
{
if (password ==null || password.trim() =="") {
return false;
}
else return true;
}
}
Your form action is empty, you should fill it your servlet name in your case it should be like:
<form action="LoginServlet" method="post"/>
I assume you already define your servlet name at your web.xml
You need to specify some controller name within the action:
<form action="LoginServlet " method="post"/>
<br> UserId: <input type="text" name="userId"/>
<br> password<input type="password" name="password"/>
<br> <input type="submit"/>
</form>
Remember: This action specifies where the data submitted by the form will be received.
Related
What I am trying to do is a blog page with jsp. For this purpose, I save the content of blogs in an html file. I am using a jsp file to update the content in the existing html file via the browser. I used the textarea tag in a jsp file to edit this html file through the browser. There is no encoding problem in the html content transferred to the textarea. But when I make changes to the html file and save it, the utf-8 characters turn out to be incorrect. For Example:
The html file is read and placed comfortably in the textarea without any encoding problems
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Evrim Üzerine Notlar</h1>
</body>
</html>
When i submit for save it:
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Evrim Ãzerine Notlar</h1>
</body>
</html>
There is the classes and jsp files:
setBlog.jsp (Html file is setting in this file)
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<jsp:include page="navbar.jsp"/>
<form action="adminBlogProcess?meth=update" method="post">
id:<input type="text" readonly="readonly" value="${setMe.textId}" name="tid">
<label>Text Title</label>
<input type="text" name="name" class="form-control" value="${setMe.name}"/>
<label>File Path</label>
<input type="text" name="textPath" class="form-control" value="${setMe.textPath}"/>
<label>Kategori</label>
<select class="form-control" name="selectedCategory">
<c:forEach items="${loc}" var="val">
<option value="${val.categoryId}">${val.categoryName}</option>
</c:forEach>
</select>
<label>İçerik:</label>
<textarea class="form-control" name="content" rows="100">${contentOfDoc}</textarea>
<input type="submit" class="btn btn-primary" value="Save Changes">
</form>
</body>
</html>
AdminBlogProcess.java
package Controller;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
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 DataAccess.CategoryDao;
import DataAccess.TextDao;
import Model.Category;
import Model.Text;
#WebServlet("/adminBlogProcess")
public class AdminBlogProcess extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -7693704779591981580L;
private CategoryDao cd;
private TextDao td;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String meth = req.getParameter("meth");
String msg="";
if (meth.equalsIgnoreCase("update")) {
update(req);
msg="Yazı Güncellendi!";
} else if (meth.equalsIgnoreCase("add")) {
} else if (meth.equalsIgnoreCase("delete")) {
}
req.setAttribute("message", msg);
req.getRequestDispatcher("/admin/admin.jsp").forward(req, resp);
}
//This update method is write new content into the html file
private void update(HttpServletRequest req) {
String name=req.getParameter("name");
String textPath=req.getParameter("textPath");
int id=Integer.valueOf(req.getParameter("tid"));
Category ct=getCd().getCategoryById(Integer.valueOf(req.getParameter("selectedCategory")));
Text txt=new Text(name, textPath, ct, id);
getTd().update(txt);
String content=req.getParameter("content");
String path="C:\\Users\\90551\\Desktop\\Eclipse Projeler\\2022 Yaz-Haziran Arsiv\\JAVA SERVER PAGES\\004BlogSitesi\\src\\main\\webapp\\texts\\"+textPath;
try (FileWriter fw = new FileWriter(new File(path), StandardCharsets.UTF_8);
BufferedWriter bw = new BufferedWriter(fw)){
bw.write("");
bw.append(content);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public CategoryDao getCd() {
if (cd == null) {
cd = new CategoryDao();
}
return cd;
}
public void setCd(CategoryDao cd) {
this.cd = cd;
}
public TextDao getTd() {
if (td == null) {
td = new TextDao();
}
return td;
}
public void setTd(TextDao td) {
this.td = td;
}
}
What should i do for fix that encodin problem?
I am trying to make a login form. and want the username parameter to accessed by the changepass.java file.
The flow of the application is:
login.jsp -> LoginServlet -> AfterLogin.jsp -> ChangePass.jsp -> ChangePassword Servlet
I tried using the session and request dispatcher for this it is not working.
I am able to get the parameter from login.jsp to ChangePass.jsp but after that the changePassword servlet is not able to access it.
My code for the flow is:
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<body>
<div align="center">
<form name="login" onsubmit="return onSubmit()" action="LoginServlet">
<h2 style="color:blue">Account Login</h2>
<table style="background-color:powderblue;border: 2px solid green;border-color:green;">
<tr><td>Enter User Name:</td><td><input type="text" name="username" minlength="6" required></td></tr>
<tr><td>Enter Pass Word:</td><td><input type="password" name="password" id="password" required></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="login"></td></tr>
</table>
<br>
<u>Home</u>
</form>
</div>
<%
String msg=(String) request.getAttribute("msg");
if(msg!=null){
%>
<p style="color:red"><%=msg%></p>
<%
}
%>
<script type="text/javascript">
function onSubmit(){
var y=document.login.password.value;
var passR=/^(?=.*\d)(?=.*[A-Z]).{6,20}$/;
if(!y.match(passR)){
alert("Password must contain at least one number and one UpperCase letter");
document.getElementById("password").focus();
}
}
</script>
</body>
</html>
LoginServlet.java
package com.wipro.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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 javax.servlet.http.HttpSession;
import com.wipro.util.DButil;
/**
* Servlet implementation class LoginServlet
*/
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try{
Connection con=DButil.getConnection();
PrintWriter out=response.getWriter();
String username=request.getParameter("username");
String password=request.getParameter("password");
String sql="select * from user_table where username=? and password=?";
PreparedStatement st=con.prepareStatement(sql);
st.setString(1, username);
st.setString(2, password);
ResultSet rs=st.executeQuery();
if(rs.next()) {
HttpSession se=request.getSession();
se.setAttribute("username", username );
request.getRequestDispatcher("AfterLogin.jsp").include(request, response);
}
else {
request.setAttribute("msg", "Invalid Credentials");
request.getRequestDispatcher("login.jsp").include(request, response);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
AfterLogin.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1><font color=green> Welcome <%=session.getAttribute("username")%></font></h1>
Change Password
</body>
</html>
ChangePass.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div align="center">
<form name="changePS" onsubmit="return onSubmit()" action="ChangePassword">
<%
String username=(String)session.getAttribute("username");
request.setAttribute("username", username);
%>
<h1><font color=green> Welcome <%=username%></font></h1>
<h2 style="color:blue">Change Password</h2>
<table style="background-color:powderblue;border: 2px solid green;border-color:green;">
<tr><td>Old Password:</td><td><input type="password" name="oldpwd" id="oldpwd" required></td></tr>
<tr><td>New Password:</td><td><input type="password" name="newpwd" id="newpwd" required></td></tr>
<tr><td>Confirm Password:</td><td><input type="password" name="confpwd" id="confpwd" required></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="login"></td></tr>
</table>
<br>
<u>Home</u>
</form>
</div>
<script type="text/javascript">
function onSubmit(){
y=document.changePS.oldpwd.value;
z=document.changePS.newpwd.value;
a=document.changePS.confpwd.value;
passR=/^(?=.*\d)(?=.*[A-Z]).{6,20}$/;
if(z != a){
alert("New Password and Confirm Password do not match");
document.getElementById("confpwd").focus();
return false;
}
if(!y.match(passR)){
alert("Old Password must contain at least one number,one UpperCase letters");
document.getElementById("oldpwd").focus();
return false;
}
if(!z.match(passR)){
alert("New Password must contain at least one number,one UpperCase letters");
document.getElementById("newpwd").focus();
return false;
}
return true;
}
</body>
</html>
ChangePassword.java
package com.wipro.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
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 javax.servlet.http.HttpSession;
import com.wipro.util.DButil;
/**
* Servlet implementation class ChangePassword
*/
#WebServlet("/ChangePassword")
public class ChangePassword extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ChangePassword() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try{
Connection con=DButil.getConnection();
PrintWriter out=response.getWriter();
String username = (String)request.getAttribute("username");
String password=request.getParameter("newPwd");
String sql="update user_table set password=? where username=?";
PreparedStatement st=con.prepareStatement(sql);
st.setString(1, username);
st.setString(2, password);
int rs=st.executeUpdate();
if(rs!=0) {
out.println("<h1><font color=green> Updated the password </font></h1>");
}
else {
out.println("<h1><font color=red> Sorry no username with this name </font></h1>"+username);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
I made my first Java Servlet application with JSPs to create a record about books and display them. The index.html page loads well but the other pages in the project don't work when deployed on GoogleAppEngine. The same project works well when run locally on App Engine through eclipse. I have also enabled sessions in the "appengine-web.xml" but the problem persists. The application works perfectly fine when run locally.
Running through the app engine I get the error -
Error: Not Found
The requested URL /BookApp was not found on this server.
Directory Structure
Servlet code :
package com.nh;
import com.books.Book;
import java.util.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;
/**
* Servlet implementation class BookApp
*/
#WebServlet("/BookApp")
public class BookApp extends HttpServlet {
private static final long serialVersionUID = 1L;
ArrayList<Book>Books = new ArrayList<Book>();
static int id = 0;
/*List<String> BookNames = new ArrayList<String>();
List<String> Authors = new ArrayList<String>();
List<String> Costs = new ArrayList<String>();*/
/**
* #see HttpServlet#HttpServlet()
*/
public BookApp() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
String bookName = request.getParameter("bookname");
String author = request.getParameter("authorname");
String bookCost = request.getParameter("cost");
String url = ("");
HttpSession session=request.getSession(true);
Book newBook = new Book();
if(bookName.length()!=0&&author.length()!=0&&bookCost.length()!=0)
{
newBook.setAuthorName(author);
newBook.setName(bookName);
newBook.setCost(Float.parseFloat(bookCost));
newBook.setId(id++);
Books.add(newBook);
}
session.setAttribute("Books", Books);
request.setAttribute("Books", Books);
System.out.println(Books.get(0).getName());
url = ("/listBooks.jsp");
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Create a book entry</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Create A Book</h2>
<form action="BookApp" method="post">
<div class="form-group">
<label for="Title">Title:</label>
<input type="text" class="form-control" id="tbBook" placeholder="Enter Title" name="bookname" required>
</div>
<div class="form-group">
<label for="author">Author:</label>
<input type="text" class="form-control" id="authorname" placeholder="Enter Author" name="authorname" required>
</div>
<div class="form-group">
<label for="cost">Cost:</label>
<input type="text" class="form-control" id="tbCost" placeholder="Enter Cost" name="cost" required>
</div>
<button type="submit" class="btn btn-default">Create</button>
</form>
</div>
</body>
</html>
listBook.jsp :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="com.books.Book" %>
<%# page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>List of books</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Book List</h2>
<table class="table table-hover">
<thead>
<tr>
<th>Sr No.</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<%
ArrayList<Book> posts=(ArrayList<Book>) request.getAttribute("Books");
for (Book book: posts) {
%>
<%session.setAttribute("Books", posts); %>
<tr>
<td><%=book.getId()+1 %></td>
<td><%=book.getName()%></td>
</tr>
<%}%>
</tbody>
</table>
</div>
</body>
</html>
appengine-web.xml
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<threadsafe>true</threadsafe>
<sessions-enabled>true</sessions-enabled>
<runtime>java8</runtime>
<system-properties>
<property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/>
</system-properties>
</appengine-web-app>
As you're using Java8 (<runtime>java8</runtime>) and as per Google App engine specification try implementing this way :
// With #WebServlet annotation the webapp/WEB-INF/web.xml is no longer required.
#WebServlet(name = "requests", description = "Requests: Trivial request", urlPatterns = "/requests")
public class RequestsServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
}
}
Reference : how-requests-are-handled-app-engine
One more advice : do not use camelCase while naming your url pattern.
Hey I am trying to create a voting app.
I have several counters in my servlets and I want to be able to display the value of those counters in my jsp file. How do I do it?
Please help me.
I want to display the total number of votes in each section and the winner after the election.
......................................................................................................................................................
servlet file
......................................................................................................................................................
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/CastVote")
public class CastVote extends HttpServlet {
int javaCount, phpCount, pythonCount, othersCount;
public CastVote() {
super();
javaCount = 0;
phpCount = 0;
pythonCount = 0;
othersCount = 0;
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String choice = request.getParameter("language");
if("java".equals(choice))
{
javaCount++;
}
else if("php".equals(choice))
{
phpCount++;
}
else if("python".equals(choice))
{
pythonCount++;
}
else if("others".equals(choice))
{
othersCount++;
}
}
}
......................................................................................................................................................
Jsp File
......................................................................................................................................................
<%# 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>Vote now.</title>
</head>
<body>
<center>
<h2>Welcome to voting portal. Cast your vote.</h2>
</center>
<form action="CastVote" method="post">
Which of the following is the best language for backend programming? <br>
<input type="radio" name="language" value="java">1) Java <br>
<input type="radio" name="language" value="php">2) PHP <br>
<input type="radio" name="language" value="python">3) Python <br>
<input type="radio" name="language" value="others">4) Others <br>
<input type = "submit" value ="Vote">
</form>
</body>
</html>
I've created a small mortg. calc. and it's working correctly, however i would like to have let's say three last calculations shown on the right side and the ability to remove (clear) them (like a small history log or similar). Whatever I try previous results get deleted. Quite new to servlets and sessions.
.jsp
<%# 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>Insert title here</title>
</head>
<body>
<body>
<div style="width:100%;">
<div style="float:left; width:20%;">
<form id="mortgage" action="mocalc" " method="post">
<p>
Principal:
<input name="principal">
Interest rate (%):
<input name="interest_rate">
Monthly payment:
<input name="monthly_payment">
<input name="calculate" type="submit" value="Calculate" />
</form>
<form id="clear" action="index.jsp" method="get"/>
<input name="clear" type="submit" value="CE"/></form>
</p>
</div>
<div style="float:right; width:80%; ">
<p>
<table>
<tr><td>Principal:</td>
<td align="right">${pr}</td>
<tr><td>Interest Rate:</td>
<td align="right">${ir}</td>
<tr><td>Monthly Payment:</td>
<td align="right">${mp}</td>
</tr></table>
<p>
It will take ${y} years and ${m} months to payoff the loan
<p>
Total interest to be paid: $${i}
</div>
</div>
</body>
</html>
.java
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;
/**
* Servlet implementation class MoCalc
*/
#WebServlet("/mocalc")
public class MoCalc extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public MoCalc() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Float pr=Float.valueOf(request.getParameter("principal"));
Float ir = Float.valueOf(request.getParameter("interest_rate"));
Float mp = Float.valueOf(request.getParameter("monthly_payment"));
String inter=null, pri=null, ira,mpa;
DecimalFormat format = new DecimalFormat("#,##0.##");
//Payoff time in months calculation
double months=(Math.log10(mp)-Math.log10(mp-pr*(ir/100)/12))/(Math.log10(1+(ir/100)/12));
int a = (int) (months + 0.5);
Integer years=a/12;
Integer month=a%12;
//Total interest calculation
double interest=mp*months-pr;
//Format values
inter=format.format(interest);
pri="$"+format.format(pr);
ira = format.format(ir)+"%";
mpa="$"+format.format(mp);
HttpSession session=request.getSession();
session.setAttribute("y",years);
session.setAttribute("m",month);
session.setAttribute("i", inter);
session.setAttribute("pr", pri);
session.setAttribute("mp", mpa);
session.setAttribute("ir", ira);
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response); }
}