unknown Servlet exception throw error of HTTP Status 500 - java

I have tried adding all libraries that are needed for Servlet to run but still I am getting an exception that threw HTTP Status 500 error.
I also have tried all previously asked questions in stack overflow.
LoginServlet.java
package com.testlogin;
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;
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String username = request.getParameter("username");
String password = request.getParameter("password");
PrintWriter pw = response.getWriter();
pw.print("Hello");
if (username.equals(password)) {
pw.println("<h1>Hello </h1>" + username);
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
login.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="LoginServlet" method="post">
<div style="color: red">
User Name
<input type="text" name="username">
<br /> Password
<input type="password" name="password">
<br>
<input type="submit" value="Sign In">
</div>
</form>
</body>
</html>

well, don't complicate your code. I think your code will work fine too and problem should be on your server.
please make sure if you are using servlet version >3.0 and tomcat 7 as it will not run in the previous versions of tomcat
try this..
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;
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String username = request.getParameter("username");
String password = request.getParameter("password");
PrintWriter pw = response.getWriter();
pw.print("Hello");
if (username.equals(password)) {
pw.println("<h1>Hello </h1>" + username);
}
}
}

Related

How can i get my table values from html to servlet?

I need to get my html table values in my servlet
Hi,
Im doing a project during my acadamic courses about sudoku website.
During my project I have encounterd a problem that I can't slove - get my table html values into my servlet.
I have tried doing things like set hidden names and getParameterValues but none of them worked.
this is my html table
<table class="center">
<% int n =9;
for(int s = 0; s<n; s++){
%>
<tr>
<% for(int f=0; f<n; f++)
{
%>
<td><% int z = SF[s][f];
if(z==0) {%>
<input type="text">
<% } else { %>
<%=SF[s][f]%>
<%}%>
</td hidden name="z">
<% } %>
</tr hidden name="z">
<% } %>
</table>
and this is my empty servlet
package View;
import org.omg.CORBA.SystemException;
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 java.io.IOException;
import java.io.PrintWriter;
#WebServlet(name = "CheckSudokuServlet",urlPatterns = "/CheckSudokuServlet")
public class CheckSudokuServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
//tried - String td[]=request.getParameterValues("z");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
How about using javascript to encode the values into a url
var z=3;
window.location.href = "/CheckSudokuServlet?z="+z;
Then in your servlet you can access as so:
String refBgcId= request.getParameter("refBgcId").toString();

passing parameters between jsp pages and servlets

I am new to web services jsps and servlets and i have this very simple example just to understand how things work.
At first, i have this simple web service :
package com.sav.calculator;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
#WebService(serviceName = "CalculatorWS")
public class CalculatorWS {
#WebMethod(operationName = "add")
public int add(#WebParam(name = "i") int i, #WebParam(name = "j") int j) {
int k = i + j;
return k;
}
}
Then i use this web service in my client application. Im trying to work the right way so i send data from a jsp to servlet, do the calculations in the servlet and send the data in another jsp for the presentation.. but the question is why im not getting it right?
here is the first jsp(just an html form):
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method="POST" action="ClientServlet">
<input type="text" name="j"/>
<input type="text" name="i"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
here is the servlet where i use my add webmethod:
package com.sav.calculator.client;
import com.sav.calculator.CalculatorWS_Service;
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.xml.ws.WebServiceRef;
#WebServlet(name = "ClientServlet", urlPatterns = {"/ClientServlet"})
public class ClientServlet extends HttpServlet {
#WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/CalculatorWSApplication/CalculatorWS.wsdl")
private CalculatorWS_Service service;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
doPost(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
int i = (int) request.getAttribute("i");
int j = (int) request.getAttribute("j");
int k = add(i, j);
request.setAttribute("k",k);
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("newjsp2.jsp");
dispatcher.forward(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
private int add(int i, int j) {
com.sav.calculator.CalculatorWS port = service.getCalculatorWSPort();
return port.add(i, j);
}
}
And the newjsp2 is just a hello world page, im just trying to get there first but what i get is :
that.
After starting web-service server, in web browser type address:
http://localhost:8080/CalculatorWSApplication/CalculatorWS.wsdl
if this address contains an wsdl (xml format) then use it as your wsdlLocation.
Try also some tool, like SoapUI, or some other.
From Servlet to JSP
You could set values into the response object before forwarding request to jsp. Or you can put your values into a session bean and access it in the jsp.
From JSP to Servlet
You need to submit a form and pass parameter as an input. An example ...
<form method="Post" action="path/to/servlet">
<input type="text" name="x" />
<input type="password" name="xx" />
<input type="hidden" name="xxx" value="zzz" />
<input type='submit' />
</form>

values are getting inserted in database but they should not

LoginServlet.java
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
String name=request.getParameter("name");
String password=request.getParameter("password");
boolean status=false;
try{
Connection con=ConnectionProvider.getCon();
String sql="select * from roles where name='" + name + "' and pass='" + password + "'";
PreparedStatement stmt =con.prepareStatement(sql);
String role="admin";
ResultSet rs=stmt.executeQuery();
if(rs.next())
{
status=true;
role=rs.getString("role");
}
if(status){
out.print("Welcome, "+name);
HttpSession session=request.getSession();
session.setAttribute("name",name);
if(role!=null && role.equals("admin") ){
response.sendRedirect("create.html");
}
else {
response.sendRedirect("create1.html");
}
}
else{
out.print("Sorry, username or password error!");
request.getRequestDispatcher("login.html").include(request, response);
}
}catch( SQLException | ServletException | IOException e){}
}
}
}
create.html
Logout
Create Department
Create Users
<hr/>
department.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Create Department</h1>
<br>
<form action="DepartmentServlet">
<table border="1">
<tbody>
<tr>
<td>Company Name :</td>
<td><input type="text" name="company" value="" size="50" /></td>
</tr>
<tr>
<td>Department Name</td>
<td><input type="text" name="department" value="" size="50" /> </td>
</tr>
<tr>
<td>Head Office :</td>
<td><input type="text" name="place" value="" size="50" /></td>
</tr>
</tbody>
</table>
<input type="reset" value="Clear" name="Clear" />
<input type="submit" value="Submit" name="Submit" />
</form>
</body>
</html>
DepartmentServlet.java
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class DepartmentServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
HttpSession session=request.getSession(false);
if(session!=null){
String name=(String)session.getAttribute("name");
boolean status=false;
try{
String department=request.getParameter("department");
String company=request.getParameter("company");
String place=request.getParameter("place");
Connection con=ConnectionProvider.getCon();
String sql="insert into department(departmentname,company,place) values (?,?,?)";
PreparedStatement pstmt =con.prepareStatement(sql);
pstmt.setString(1,department);
pstmt.setString(2,company);
pstmt.setString(3,place);
int rs=pstmt.executeUpdate();
if(rs>0){status=true;}
}catch(Exception e){}
if(status){
out.print("Values have been inserted,"+name);
request.getSession();}
else
{
out.print("failed");
}
}
else{
out.print("Please login first");
request.getRequestDispatcher("login.html").include(request, response);
}
}
}
}
LogoutServlet.java
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LogoutServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
HttpSession session=request.getSession(false);
session.invalidate();
out.print("You are successfully logged out!");
}
}
}
With DepartmentServlet, I am inserting values into the database. The problem is that, I am able to open create.html and department.jsp without login and values are also getting inserted into the database even when I have not logged in. I know the problem is with the session not being properly passed(used). How can I solve it? Could someone correct it?
Change the condition if(session != null)
to if(session != null && session.getAttribute("name") != null)
you'll have to implement filter to restrict access for .jsp/.html which would check for active session .if no active session found then it'll redirect request to login page(in you case link.Use below implementation of doFilter method
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("name") == null) {
response.sendRedirect(request.getContextPath() + "/link");
} else {
chain.doFilter(req, res);
}
}

Out.Print method not working?

Here is my code
LoginController.java
package mvc.demo.control;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mvc.demo.model.Authenticate;
public class LoginController extends HttpServlet {
private static final long SerialVersionUID=1L;
public LoginController()
{
super();
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String s1=req.getParameter("username");
String s2=req.getParameter("password");
RequestDispatcher rd=null;
Authenticate au=new Authenticate();
String result=au.authorise(s1, s2);
if(result.equals("success"))
{
rd=req.getRequestDispatcher("/success.jsp");
}
else
{
//This is the point where i try to print error message on jsp.
PrintWriter out = resp.getWriter( );
out.print("Sorry UserName or Password Error!");
rd=req.getRequestDispatcher("/login.jsp");
rd.include(req, resp);
}
rd.forward(req, resp);
}
}
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form method="post" action="LoginController" >
UserName: <input type="text" name="username"><BR><BR>
PassWord: <input type="password" name="password"><BR><BR>
<input type="submit" />
</form>
</body>
</html>
Please check the else block of loginController class where i am trying to print error message on my jsp file currently the "out.print" method is unable to reflect on my login.jsp file.
Kindly help me to sort this issue Thanks in advance.
You can set the error message in request attribute and can fetch it in JSP
String errorMsg = "UserName or Password is invalid !";
req.setAttribute("errorMsg", errorMsg);
req.getRequestDispatcher("/login.jsp").forward(req, res);
Now on your JSP
<h2>${errorMsg}</h2> // Print wherever you need it
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mvc.demo.model.Authenticate;
public class LoginController extends HttpServlet {
private static final long SerialVersionUID=1L;
public LoginController()
{
super();
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String s1=req.getParameter("username");
String s2=req.getParameter("password");
RequestDispatcher rd=null;
Authenticate au=new Authenticate();
String result=au.authorise(s1, s2);
if(result.equals("success"))
{
rd=req.getRequestDispatcher("/success.jsp");
//The error was with this line
rd.forward(req, resp);
}
else
{
PrintWriter out = resp.getWriter( );
out.print("Sorry UserName or Password Error!");
rd=req.getRequestDispatcher("/login.html");
rd.include(req, resp);
}
}
}
I can't see out.close() in your code. You must close the PrintWriter object in the end.
If u want to print the error message in Jsp and first Set the Error msg in request
req.setAttribute("msg","error msg configure here");
and now you can get the same in jsp by using EL Expression.
${msg}
or You can get it by using scripting language.
<%Object obj=request.getAttribute("msg");%>
Typecast the Obj into String and print by using this
<%=str%>
Note:- Recommended to use El expression.

Jetty on a non web project

I have a plugin project where I want to implement some servlets with jetyy. I have a login.html with this structure:
<!DOCTYPE html PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>LOGIN.HTML</title>
</head>
<body>
<h1>LOGIN</h1>
<form method='POST' action=''>
User: <input type="text"> <br />
Password: <input type="password"> <br />
<input type="submit" value="login">
</form>
</body>
</html>
After I submit the form, I want to call a servlet to do some actions...
This is the servlet:
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("/receptor")
public class HelloServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
System.out.println("TEST");
}
}
But I can't call it, I always have the 404 not found error, what's the right thing to write on the action of the form ?
PS: I've tried to create the WEB-INF structure and the web.xml, but I always got bad configuration error of this web.xml .. Is it possible to call the servlet without web.xml ?

Categories