tomcat gives 404 error while my mapping in xml is fine - java

public class Guestbook extends CacheHttpServlet {
/**
*
*/
private static final long serialVersionUID = 1 L;
private Vector < GuestbookEntry > entries = new Vector < GuestbookEntry > ();
private long lastModified = 0; // Time last entry was added
// Display the current entries, then ask for a new entry
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
printHeader(out);
printForm(out);
printMessages(out);
printFooter(out);
}
// Add a new entry, then dispatch back to doGet()
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
handleForm(req, res);
doGet(req, res);
}
private void printHeader(PrintWriter out) throws ServletException {
out.println("<HTML><HEAD><TITLE>Guestbook</TITLE></HEAD>");
out.println("<BODY>");
}
private void printForm(PrintWriter out) throws ServletException {
out.println("<FORM METHOD=POST action='/hello.html'>"); // posts to itself
out.println("<B>Please submit your feedback:</B><BR>");
out.println("Your name: <INPUT TYPE=TEXT NAME=name><BR>");
out.println("Your email: <INPUT TYPE=TEXT NAME=email><BR>");
out.println("Comment: <INPUT TYPE=TEXT SIZE=50 NAME=comment><BR>");
out.println("<INPUT TYPE=SUBMIT VALUE=\"Send Feedback\"><BR>");
out.println("</FORM>");
out.println("<HR>");
}
private void printMessages(PrintWriter out) throws ServletException {
String name, email, comment;
Enumeration < GuestbookEntry > e = entries.elements();
while (e.hasMoreElements()) {
GuestbookEntry entry = (GuestbookEntry) e.nextElement();
name = entry.name;
if (name == null) {
name = "Unknown user";
email = "Unknown email";
}
email = entry.email;
comment = entry.comment;
if (comment == null) comment = "No comment";
out.println("<DL>");
out.println("<DT><B>" + name + "</B> (" + email + ") says");
out.println("<DD><PRE>" + comment + "</PRE>");
out.println("</DL>");
// Sleep for half a second to simulate a slow data source
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {}
}
}
private void printFooter(PrintWriter out) throws ServletException {
out.println("</BODY>");
out.println("</HTML>");
}
private void handleForm(HttpServletRequest req,
HttpServletResponse res) {
GuestbookEntry entry = new GuestbookEntry();
entry.name = req.getParameter("name");
entry.email = req.getParameter("email");
entry.comment = req.getParameter("comment");
entries.addElement(entry);
// Make note we have a new last modified time
lastModified = System.currentTimeMillis();
}
public long getLastModified(HttpServletRequest req) {
return lastModified;
}
}
class GuestbookEntry {
public String name;
public String email;
public String comment;
}
And in the XML file i used
<web-app>
<servlet>
<servlet-name>
GuestBook
</servlet-name>
<servlet-class>
Guestbook
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
GuestBook
</servlet-name>
<url-pattern>
/hello.html
</url-pattern>
</servlet-mapping>
</web-app>
everything i used are fine but tomcat still gives me a 404 error. although i tried by different methods but still it gives me an error.
if someone will provide a solution then it would be really appreciated.
thanks in advance

we would need to create a separate html page and will write the same content as "PrintForm" method in the code. if we do so then this servlet will work perfectly. Although this servlet used for server cache, i hope it will help you in future.
thank you

Related

How to show another html page with servlet?

this is my first time with Java's servlet (and JSP) programming and right now I have a doubt. Imagine that I'm building an online shop with a login page (let's suppose is the starting page) and maybe a shopping page (the "second" one). My servlet contains the code for autenticate the users and if the user is correct the servlet should shows the shopping catalog. My answer is, what's the best method for doing this? This is my servlet code (doGet) now:
nb: userName and password come from the login page...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userName = request.getParameter("userName");
String password = request.getParameter("password");
out.println("<html>");
out.println("<body bgcolor = 'green'>");
out.println("<br>" + "Hello " + " " + userName + "<br> LOGGED IN!" + "<br>");
out.println("Your password is : " + " " + password + "<br>");
if(userName.equals("some_correct_user")) {
out.println("<p>Login correct </p>");
response.sendRedirect("/FirstServletExercise/shoppingPage.html");
}
else {
out.println("<p>Access denied</p>");
}
I know it's very simple but is just the concept: it's correct to use "sendRedirect" to display another different page, or I have to upgrade the content of the first page? And how I can do this? Hope I have explained myself well.
Thanks!
I am using Jetty-11 Server standalone/embedded mode. And here is how the Login Servlet looks like.
import java.io.IOException;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
private Logger log = LoggerFactory.getLogger(LoginServlet.class);
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
log.debug("LoginServlet {} userPrincipal: {}", req.getServletPath(), req.getUserPrincipal());
Map<String, String[]> p = req.getParameterMap();
p.forEach((k, v) -> {
log.debug("{} {}", k, v);
});
String un = (p.get("j_username") != null) ? p.get("j_username")[0] : null;
String up = (p.get("j_password") != null) ? p.get("j_password")[0] : null;
try {
if (un != null && up != null) {
req.logout();
req.login(un, up);
}
} catch (Exception e) {
log.error("AuthenticationException: ", e);
}
log.debug("{} userPrincipal: {}", req.getServletPath(), req.getUserPrincipal());
boolean isAuth = (req.getUserPrincipal() == null) ? false : true;
log.debug("isAuth: {}", isAuth);
resp.setContentType("text/html");
if (isAuth) {
/** Session Management */
HttpSession session = req.getSession();
session.setAttribute("user", req.getUserPrincipal().getName());
// setting session to expiry in 30 mins
session.setMaxInactiveInterval(30 * 60);
log.debug("sessionId: {} ", req.getSession().getId());
/** Cookie Management */
Cookie loginCookie = new Cookie("user", req.getUserPrincipal().getName());
loginCookie.setMaxAge(30 * 60);
resp.addCookie(loginCookie);
/** Login Success - so display the Home Page */
resp.sendRedirect("./index.html");
} else {
Cookie loginCookie = new Cookie("user", "unknownUser");
loginCookie.setMaxAge(0);
loginCookie.setPath("/");
resp.addCookie(loginCookie);
req.getRequestDispatcher("./login.html").forward(req, resp);
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

SEVERE: Servlet.service() for servlet [ProfileServlet] in context with path [/Homework] threw exception java.lang.NumberFormatException: null

I'm getting this exception and i have no idea why. It says its a number format exception is null. I have looked at other posts about this but none of them fixes my problem. My profile class is a simple class that has id username lastname age and favTeam with setters and getters and a constructor. Anyone know why this is happening?
My Servlet
public ProfileServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
HashMap<Integer, Profile> team = new HashMap<Integer, Profile>();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("application/json; charset=UTF-8");
//String requestUrl = request.getRequestURI();
PrintWriter out = response.getWriter();
Profile test = new Profile();
int id;
test = team.get(id = Integer.parseInt(request.getParameter("ID")));
if(test != null)
{
out.println("ID: " + test.getId());
out.println("name: " + test.getUsername());
out.println("lastname: " + test.getLastname());
out.println("age: " + test.getAge());
out.println("favTeam: " + test.getFavTeam());
}
else
{
//ERROR
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String id = request.getParameter("id");
String age = request.getParameter("id");
int x = 0;
if(id!=null){
try{
x = Integer.parseInt(id);
}catch(Exception e){
}
}
String username = request.getParameter("username");
String lastname = request.getParameter("lastname");
String favTeam = request.getParameter("favTeam");
int numage = 0;
if(id!=null){
try{
numage = Integer.parseInt(age);
}catch(Exception e){
}
}
Profile profile = new Profile(x,username,lastname,favTeam,numage);
team.put(profile.getId(),profile);
}
}
My .xml
<display-name>Homework</display-name>
<servlet>
<servlet-name>ProfileServlet</servlet-name>
<servlet-class>ntrut.ProfileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ProfileServlet</servlet-name>
<url-pattern>/profile</url-pattern>
</servlet-mapping>
</web-app>
Error seems in your below line.
Integer.parseInt(request.getParameter("ID"))
Make sure value returned from request.getParameter("ID") is a Number,
Can you try to print value of request.getParameter("ID") before this line ? you will see it is not a number value.
What i did to fix my issue is what i did in my doPost. I had to do the same thing in my doGet with the request.getParameter
String id = request.getParameter("id");
int x = 0;
if(id!=null){
try{
x = Integer.parseInt(id);
}catch(Exception e){
}
}
test = team.get(x);

Resolving multipart/form-data request in spring filter

I'm trying to develop my own CSRF filter in Spring MVC 3 (There are some extra trainings that made me do that, thats why Im not considering spring security.)
My filter works fine with all forms except those that have enctype="multipart/form-data". So I can not get request parameters from normal HttpServletRequest.
I've tried casting HttpServletRequest to MultipartHttpServletRequest but I found out I can not do that either.
My objective is not getting files from the request, but to only get simple form input named csrf. (Ive already uploaded files with my forms)
Here is my code till now:
CSRFilter
public class CSRFilter extends GenericFilterBean {
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
CSRF csrf = new CSRF(req);
if(csrf.isOk()){
chain.doFilter(req, res);
}else {
//todo : Show Error Page
String redirect = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/access-forbidden";
response.sendRedirect(redirect);
}
}
}
CSRF
public class CSRF {
HttpServletRequest request;
ServletRequest req;
String token;
boolean ok;
private static final Logger logger = Logger.getLogger(CSRF.class);
public CSRF(ServletRequest request) {
this.request = (HttpServletRequest) request;
this.req = request;
init();
}
public CSRF() {
}
public void setRequest(HttpServletRequest request) {
this.request = (HttpServletRequest) request;
this.req = request;
init();
}
private void init() {
if (request.getMethod().equals("GET")) {
generateToken();
addCSRFTokenToSession();
addCSRFTokenToModelAttribute();
ok = true;
} else if (request.getMethod().equals("POST")) {
if (checkPostedCsrfToken()) {
ok = true;
}
}
}
private void generateToken() {
String token;
java.util.Date date = new java.util.Date();
UUID uuid = UUID.randomUUID();
token = uuid.toString() + String.valueOf(new Timestamp(date.getTime()));
try {
this.token = sha1(token);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
this.token = token;
}
}
private void addCSRFTokenToSession() {
request.getSession().setAttribute("csrf", token);
}
private void addCSRFTokenToModelAttribute() {
request.setAttribute("csrf", token);
}
private boolean checkPostedCsrfToken() {
System.out.println("____ CSRF CHECK POST _____");
if (request.getParameterMap().containsKey("csrf")) {
String csrf = request.getParameter("csrf");
if (csrf.equals(request.getSession().getAttribute("csrf"))) {
return true;
}
}else {
//Check for multipart requests
MultipartHttpServletRequest multiPartRequest = new DefaultMultipartHttpServletRequest((HttpServletRequest) req);
if (multiPartRequest.getParameterMap().containsKey("csrf")) {
String csrf = multiPartRequest.getParameter("csrf");
if (csrf.equals(request.getSession().getAttribute("csrf"))) {
return true;
}
}
}
log();
return false;
}
private void log() {
HttpSession session = request.getSession();
String username = (String) session.getAttribute("username");
if(username==null){
username = "unknown (not logged in)";
}
String ipAddress = request.getHeader("X-FORWARDED-FOR");
if (ipAddress == null) {
ipAddress = request.getRemoteAddr();
}
String userAgent = request.getHeader("User-Agent");
String address = request.getRequestURI();
System.out.println("a CSRF attack detected from IP: " + ipAddress + " in address \"" + address + "\" - Client User Agent : " + userAgent + " Username: " + username);
logger.error("a CSRF attack detected from IP: " + ipAddress + " in address \"" + address + "\" - Client User Agent : " + userAgent + " Username: " + username);
}
public boolean isOk() {
return ok;
}
static String sha1(String input) throws NoSuchAlgorithmException {
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(input.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < result.length; i++) {
sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
}
I have this line in my dispatcher too :
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="40000000"/>
</bean>
and also I use springMultipartResolver filter ...
<filter>
<display-name>springMultipartFilter</display-name>
<filter-name>springMultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>springMultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</filter>
I get java.lang.IllegalStateException: Multipart request not initialized Exception when I try it on multipart/form-data forms.
I looked at many Examples in internet. Most of them was for file uploading purpose and could not help me, I also tried different ways to cast HttpServletRequest to any other object that gives me resolved multipart request, But I could not succeed.
How can I do it ?
Thanks.
You can not cast HttpServletRequest to MultipartHttpServletRequest, because you first have to resolve your request.
I used CommonsMultipartResolver Class and got MultipartHttpServletRequest using commonsMultipartResolver.resolveMultipart(request) method (where request is type of HttpServletRequest)
So, here is my CSRF class, checkPostedCsrfToken() method:
private boolean checkPostedCsrfToken() {
if (request.getParameterMap().containsKey("csrf")) {
String csrf = request.getParameter("csrf");
if (csrf.equals(request.getSession().getAttribute("csrf"))) {
return true;
}
} else if (request.getContentType() != null && request.getContentType().toLowerCase().contains("multipart/form-data")) {
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
MultipartHttpServletRequest multipartRequest = commonsMultipartResolver.resolveMultipart(request);
if (multipartRequest.getParameterMap().containsKey("csrf")) {
String csrf = multipartRequest.getParameter("csrf");
if (csrf.equals(request.getSession().getAttribute("csrf"))) {
return true;
}
}
}
log();
return false;
}
But, Note that you will end up loosing all request parameters and data with this approach. So you have to extend HttpServletRequestWrapper class to read request bytes and use them to get parameters if it matters to you that parameters don't get lost throw filter chain. In other words, you need a clone of your request.
Here is a good helper class I found in StackOverflow, (I cant find the question again, I will edit this if I find it).
MultiReadHttpServletRequest
public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
private ByteArrayOutputStream cachedBytes;
public MultiReadHttpServletRequest(HttpServletRequest request) {
super(request);
}
#Override
public ServletInputStream getInputStream() throws IOException {
if (cachedBytes == null)
cacheInputStream();
return new CachedServletInputStream();
}
#Override
public BufferedReader getReader() throws IOException{
return new BufferedReader(new InputStreamReader(getInputStream()));
}
private void cacheInputStream() throws IOException {
/* Cache the inputstream in order to read it multiple times. For
* convenience, I use apache.commons IOUtils
*/
cachedBytes = new ByteArrayOutputStream();
IOUtils.copy(super.getInputStream(), cachedBytes);
}
/* An inputstream which reads the cached request body */
public class CachedServletInputStream extends ServletInputStream {
private ByteArrayInputStream input;
public CachedServletInputStream() {
/* create a new input stream from the cached request body */
input = new ByteArrayInputStream(cachedBytes.toByteArray());
}
#Override
public int read() throws IOException {
return input.read();
}
}
}
now all you need to do is to use MultiReadHttpServletRequest instead of normal HttpServletRequest in filter :
public class CSRFilter extends GenericFilterBean {
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// The important part!! wrap the request:
MultiReadHttpServletRequest multiReadHttpServletRequest = new MultiReadHttpServletRequest(request);
CSRF csrf = new CSRF(multiReadHttpServletRequest);
if(csrf.isOk()){
chain.doFilter(multiReadHttpServletRequest, res);
}else {
//todo : Show Error Page
String redirect = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/access-forbidden";
response.sendRedirect(redirect);
}
}
}
I wish this helps someone :)
I needed to be able to inspect the Request's body without damaging it for the Servlet or subsequent Filters, so I created a mini-project that does just that.
The jar is < 10kb, and if you're using Tomcat then you don't need anything beyond that. Also, it's MIT licensed so you can use it in whatever project you may need.
You can find the project at https://github.com/isapir/servlet-filter-utils
All you have to do is wrap the incoming Request with RereadableServletRequest, e.g.
HttpServletRequest requestWrapper = new RereadableServletRequest(servletRequest);

How to receive info to put in HTML/JSP from post servlet

Basically my goal for this page I'm working on is for users to type in a stock symbol and this information goes to a post method and send back the data to put on the same html/jsp page. I have been able to get this to work where the form leads to another JSP page, but that has to be a separate page, I'd like to be able to stay on the same page and have the info come up. If you have a resource that could teach me how to deal with this problem, I would appreciate that just as much as a solution. I have been using the Gradle Build Tool.
Here is the form(in index.jsp):
<h1>Search Stock</h1>
<form method="POST" action="DataPage.jsp">
<input type = "text" name = "Symbol">
<input type = "submit" name = "getData">
</form>
Here is the functioning JSP code(DataPage.jsp):
<%
String Ticker = request.getParameter("Symbol");
PrintWriter write = response.getWriter();
if((Ticker == null)){
String message = "Please enter a stock symbol";
write.println(message);
}else{
try{
Company object = Serializing.getCompany(Ticker);
object.updateData();
write.println("data last added" + object.getLastUpdate());
write.println(object.getSentiment());
}catch(NullPointerException x){
Company object = Serializing.getCompany(Ticker);
}
}%>
Here is the servlet I tried writing(DataServlet.java), I have very little experience with servlets, I scavenged this from different sources and questions on stackoverflow:
package Default;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created by Ceyer on 9/3/2015.
*/
#javax.servlet.annotation.WebServlet(name = "DataServlet", urlPatterns = ("/"))
public class DataServlet extends javax.servlet.http.HttpServlet {
private static final long serialVersionUID = 1L;
public DataServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
String Ticker = request.getParameter("Symbol");
if ((Ticker == null)||Ticker.trim().isEmpty()) {
String message = "Please enter a stock symbol";
request.setAttribute("data", message);
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} else {
PrintWriter write = response.getWriter();
try {
Company object = Serializing.getCompany(Ticker);
object.updateData();
request.setAttribute("data", object.getSentiment() + "updated last" + object.getLastUpdate());
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} catch (NullPointerException x) {
Company object = Serializing.getCompany(Ticker);
request.setAttribute("data", "We do not have info on this stock");
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
If you want to use only one page and with a servlet, I think you can use session and response.sendRedirect() to do it.
This is index.jsp page
<h1>Search Stock</h1>
<form method="POST" action="DataServlet" onsubmit="dataCheck()">
<input type="text" name="Symbol">
<input type="submit" value="getData">
</form>
<%
if(session.getAttribute("data") != null) {
out.print("<p>" + session.getAttribute("data"));
session.removeAttribute("data");
}
%>
<script>
function dataCheck() {
if(document.getElementsByName[0].value == ""){
alert("Symbol is null!");
return false;
}
return true;
}
</script>
This is DataServlet class
public class DataServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String Ticker = request.getParameter("Symbol");
Company object = Serializing.getCompany(Ticker);
if (object != null) {
object.updateData();
request.getSession().setAttribute("data", object.getSentiment() +
"updated last" + object.getLastUpdate());
} else {
request.getSession().setAttribute("data", "We do not have info on this stock");
}
response.sendRedirect("index.jsp");
}
}

Servlet For Loop Causing Http 500 Error

I'm in the process of creating a login servlet essentially. I'm not sure why, but my for loop is causing it to display a 500 level error. Any help would would be appreciated.
The created class is just a basic class with getters and setters.
public Login() {
super();
}
boolean isNameValid;
boolean isPassValid;
public void init(ServletConfig config) throws ServletException {
super.init(config);
ServletContext context = this.getServletContext();
if (context.getAttribute("HomeworkUsers") == null) {
ArrayList<CS320User> HomeworkUsers = new ArrayList<CS320User>();
getServletContext().setAttribute("HomeworkUsers", HomeworkUsers);
CS320User user1 = new CS320User("John", "Doe", "john#doe.com", "1!");
CS320User user2 = new CS320User("Joe", "Boxer", "joe#boxer.com",
"2#");
HomeworkUsers.add(user1);
HomeworkUsers.add(user2);
context.setAttribute("HomeworkUsers", HomeworkUsers);
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ServletContext context = this.getServletContext();
ArrayList<CS320User> HomeworkUsers = (ArrayList<CS320User>) context
.getAttribute("HomeworkUsers");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!doctype html>");
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body>");
out.println("<h3>Login Servlet</h3>");
out.println("<form action=\"Login\" method=\"post\">");
out.println("Username: <input type='text' name='Username'/>");
out.println("<br/>");
out.println("Create Password: <input type='password' name= 'password' /> ");
out.println("<br/>");
out.println("<br/>");
out.println("<label for =\"Remember Me\"> Remember Me");
out.println("<input type=\"checkbox\" id= \"Remember Me\">");
out.println("</label>");
out.println("<br/>");
out.println("<input type='submit' name='login' value='Login' /> ");
out.println("<br>");
for (CS320User users : HomeworkUsers) {
if (users.getEmail().contains(request.getParameter("Username"))
&& users.getPassword().contains(
request.getParameter("password"))) {
out.println(users.getEmail());
out.println(users.getFirst());
isNameValid = true;
isPassValid = true;
}
}
String Username = request.getParameter("Username");
String password = request.getParameter("password");
out.println(Username);
out.println(password);
out.println(isNameValid);
out.println(isPassValid);
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (isNameValid == true && isPassValid == true) {
response.sendRedirect("Welcome");
}
doGet(request, response);
}
If you don't log your exceptions, i mean if you don't handle them you can get 500 errors in runtime as expected.
To prevent this situtation just use try catch blocks and handle your exceptions in catch block. (At least log them)
In your code there's only one thing can cause an exception in for loop line and that's the null possibility of your HomeworkUsers..
ArrayList<CS320User> HomeworkUsers = (ArrayList<CS320User>) context
.getAttribute("HomeworkUsers");
In the code part that i wrote at the top you are getting a context attribute and it can be null. And possibly your solution is checking if it's null or not.

Categories

Resources