I have a DynamicWebApp in Eclipse with Tomcat Apache.
My task: The bean consists of 2 operands of type Integer and as text the arithmetic operations Addition with '+', Subtraction with '-' and Multiplication with 'MUL'. The bean returns the calculation result of type Integer. Then implement the following two scenarios:
Scenario 1: Implement a suitable Java Servlet that calls the Java Bean. You call the servlet using your own HTML page.
Scenario 2: Implement a suitable Java server page that reuses the Java bean using JSP standard actions. Then call your bean from the JSP page.
html opens and i can calculate. after submit nothing opens but i can see in the browser url what i wrote.
and if i start the jsp than i get: cannot find any information on property (firstNum) in a bean of type (bean.CalculatorBean)
my html code called: index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Hallo Welt</title>
</head>
<body>
<form action="HalloServlet" method="get" style="text-align: center">
<table border="1" width="25%">
<tr style="text-align: center">
<td colspan="2">Rechner</td>
<td></td>
</tr>
<tr>
<td>Zahl 1</td>
<td><input type="text" name="firstNum"></td>
</tr>
<tr>
<td>Operator</td>
<td><select name="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">MUL</option>
</select></td>
</tr>
<tr>
<td>Zahl 2</td>
<td><input type="text" name="secondNum"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="="></td>
</tr>
</table>
</form>
</body>
</html>
servlet called: HalloServlet.java
package calculator;
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 bean.CalculatorBean;
#WebServlet("/HalloServlet")
public class HalloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
// Get Parameter from index.html
int operand1 = Integer.parseInt(request.getParameter("firstNum"));
int operand2 = Integer.parseInt(request.getParameter("secondNum"));
char operator1 = request.getParameter("operator").charAt(0);
// Parameter from HalloServlet.java to CalculatorBean
CalculatorBean.setFirstNum(operand1);
CalculatorBean.setSecondNum(operand2);
CalculatorBean.setOperator(operator1);
// Parameter from CalculatorBean to HalloServlet.java
CalculatorBean.getFirstNum();
CalculatorBean.getSecondNum();
CalculatorBean.getOperator();
int i = Integer.parseInt(request.getParameter("result"));
PrintWriter out = response.getWriter();
out.println(i);
out.flush();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
}
bean called: CalculatorBean.java
package bean;
public class CalculatorBean {
private int firstNum;
private int secondNum;
private char operator = '+';
private int result;
public static void getFirstNum() {
}
public static void setFirstNum(int firstNum) {
}
public static void getSecondNum() {
}
public static void setSecondNum(int secondNum) {
}
public static void getOperator() {
}
public static void setOperator(char operator) {
}
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public void calculate() {
switch (this.operator) {
case '+': {
this.result = this.firstNum + this.secondNum;
break;
}
case '-': {
this.result = this.firstNum - this.secondNum;
break;
}
case '*': {
this.result = this.firstNum * this.secondNum;
break;
}
}
}
}
jsp called: HalloJSP.jsp
<%# page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<jsp:useBean id="CalculatorBean" class="bean.CalculatorBean">
</jsp:useBean>
<jsp:setProperty name="CalculatorBean" property="*" />
<%
CalculatorBean.calculate();
%>
<br />
<hr>
<br /> Ergebnis:
<jsp:getProperty name="CalculatorBean" property="firstNum" />
<jsp:getProperty name="CalculatorBean" property="operator" />
<jsp:getProperty name="CalculatorBean" property="secondNum" />
=
<jsp:getProperty name="CalculatorBean" property="result" />
<br />
<hr>
<br />
<form action="HalloJSP.jsp" method="post" style="text-align: center">
<table border="1" width="25%">
<tr style="text-align: center">
<td colspan="2">Rechner</td>
<td></td>
</tr>
<tr>
<td>Zahl 1</td>
<td><input type="text" name="firstNum"></td>
</tr>
<tr>
<td>Operator</td>
<td><select name="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">MUL</option>
</select></td>
</tr>
<tr>
<td>Zahl 2</td>
<td><input type="text" name="secondNum"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="="></td>
</tr>
</table>
</form>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>hallowelt</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
You should have noticed that your implementation contains empty methods?
public static void setFirstNum (int firstNum) {
}
Best to create new bean! Right click on "src" or beanpackage.
Then click New -> Class. Give the bean a name and click on "add" at interface. In the following window enter "Serializable" and add purple serializable interface ...
Create attributes. mark this, right click -> source -> generate getter and setter!
Implement an empty constructor such as CalcBean () {}
implement in the setResult calculator. everything else is superfluous
servlet
do right click on your source folder or httpservlet package -> new -> servlet. name it -> click on doGet and make doPost -> Finito ... copy your stuff from open script "2 java servlets.pdf" necessarily via pdf-Reader! Go to page 23.
Mark the whole flow within the doGet method COMPLETE. Put that in your servlet. Replace the getter methods of your bean with:
o.println ("<p> number 1:" + beans.getFirstNummero () ...
open script in pdf reader, because then the formatting is inserted correctly formatted when "inserting" the script copy (therefore do not open pdf via browser, otherwise haste a single line when inserting)
What surprised me is that many have answered many, even though you have more code and almost everything completely specified and the error regarding the bean everyone should have noticed here ...
In the future, be a bit more curious while working in Eclipse ... everywhere, make a right-click and see what eclipse can do. Via plugins goes even more, but meanwhile Eclipse in contrast to android studio is better. that android studio is more intended for android code
Related
I have LoginServlet like this:
package servlets;
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("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username.equals("gogikole") && password.equals("1234")) {
response.sendRedirect("mainMenu.jsp");
return;
}
}
}
And login.jsp like this:
<%# 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login page</title>
</head>
<body>
<form method="post" action="LoginServlet"></form>
<table>
<tr>
<td>User name</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</body>
</html>
For some reason when I input correct username: (gogikole) and password: (1234) and click on submit button it won't to redirect me to mainMenu.jsp
When I click on button, nothing happen it just stay on login page like I didn't even click or type anything.
How to fix that problem and redirect when I click on submit button (Login)?
I created mainMenu.jsp and, for now that is one allmost blank page only with message "Welcome".
Your submit button is not submitting the form.
i.e., you have closed the form immediately:
<form method="post" action="LoginServlet"></form>
The problem is that your form inputs and submit button are outside the form You have to enclose as below.
<form method="post" action="LoginServlet">
<table>
<tr>
<td>User name</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
I am trying to call a java method('method1') that runs some r code(using RCaller) when a specific button is clicked on a JSP page('button1'), but when i click on the button it doesn't do anything and I am getting no errors in the output. I'm trying to use a servlet to run the java method from a JSP file. I'd appreciate any help.
Analysis.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Analysis Page</title>
</head>
<body>
<center><h2>
Final year Prototype
</h2></center>
<center> <table border="0">
<thead>
<tr>
<th>Disabilities Analysis</th>
</tr>
</thead>
<tbody>
<tr>
<center><td></td></center>
</tr>
<tr>
<td>
<center>
Current HSE Support Centre Locations
</center>
</td>
</tr>
<tr>
<td>
<center>
New HSE Support Centre Locations
</center>
</td>
</tr>
<tr>
<td>
<center>
<form action="${pageContext.request.contextPath}/myservlet" method="POST">
<button type="submit" name="button" value="button1">Button 1</button>
<button type="submit" name="button" value="button2">Button 2</button>
<button type="submit" name="button" value="button3">Button 3</button>
</form>
</center>
</td>
</tr>
<tr>
<td>
<center>
Return
</center>
</td>
</tr>
</tbody>
</table></center>
</body>
</html>
myServlet.java:
package webJava;
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("/myservlet")
public class MyServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
TestMethods t = new TestMethods();
String button = request.getParameter("button");
if ("button1".equals(button)) {
t.method1();
} else if ("button2".equals(button)) {
t.method2();
} else if ("button3".equals(button)) {
t.method3();
} else {
}
request.getRequestDispatcher("/Analysis.jsp").forward(request, response);
}
}
TestMethods.java:
package webJava;
import java.io.File;
import javax.swing.ImageIcon;
import rcaller.RCaller;
import rcaller.RCode;
public class TestMethods {
public void method1() {
try {
RCaller caller = new RCaller();
RCode code = new RCode();
caller.setRscriptExecutable("/Library/Frameworks/R.framework/Versions/3.3/Resources/Rscript");
caller.cleanRCode();
caller.setRCode(code);
// load the ggplot2 library into R
code.R_require("ggplot2");
// create a data frame in R using x and y variables
code.addRCode("df <- data.frame(x,y)");
// plot the relationship between x and y
File file = code.startPlot();
code.addRCode("ggplot(df, aes(x, y)) + geom_point() + geom_smooth(method='lm') + ggtitle('y = f(x)')");
caller.runOnly();
ImageIcon ii = code.getPlot(file);
code.showPlot(file);
} catch (Exception e) {
System.out.println(e.toString());
}
}
public void method2() {
//some code
}
public void method3() {
//some code
}
}
My project directory:
Screenshot
Situation: In the code below I'm attempting to learn how to use form parameters specifically redirecting Java servlets by propagating string query parameters.
Problem: I can't seem to figure out why I'm facing a problem with re-directing the user from the form i.e. index.html using the desired string query paramters to the correct page.
Below are the steps I took before posting this up:
I made sure the URL pattern for the #WebServlet annotation is correct
i.e. in my case /CityManagerWebStarter/mainmenuresponder.do
I made sure my content-root when looking at the URL is correct i.e.
/CityManagerWebStarter and I can confirm this as when I launch the
following URL http://localhost:8080/CityManagerWebStarter/ it
displays the index.html page as expected.
Below is my servlet code and following that is my index.html code and ListCities.html is an example of a page I'm attempting to re-direct the user to:
servlet code:
package company.citymanagerweb.servlets;
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;
/**
* Servlet implementation class MainMenuResponder
*/
#WebServlet("/CityManagerWebStarter/mainmenuresponder.do")
public class MainMenuResponder extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public MainMenuResponder() {
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
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userChoiceSelect = request.getParameter("menuChoice");
String[] userOptionsCBox = request.getParameterValues("adminoptions");
StringBuilder params = new StringBuilder();
String queryStringParams = params.toString();
if(userOptionsCBox != null) {
boolean isFirst = true;
for(int i = 0; i < userOptionsCBox.length; i++) {
// Build URL with string query parameters i.e. URL + ? + PARAM1 + AMAPERSAND + PARAM2
// Arguments is value of the value attribute
if(!isFirst) {
params.append("&");
} else {
params.append("?");
}
if(userOptionsCBox[i].equalsIgnoreCase("useDB")) {
// append() argument is value of the value attribute belonging to the input attribute
params.append("useDB=1");
} else if(userOptionsCBox[i].equalsIgnoreCase("sendEmail")) {
params.append("sendEmail=1");
}
isFirst = false;
}
queryStringParams = params.toString();
}
if(userChoiceSelect.equals("1")) {
response.sendRedirect("ListCities.html" + queryStringParams);
} else if(userChoiceSelect.equals("2")) {
response.sendRedirect("AddCity.html" + queryStringParams);
} else if(userChoiceSelect.equals("3")) {
response.sendRedirect("DeleteCity.html" + queryStringParams);
} else {
response.sendRedirect("index.html");
}
}
}
index.html:
<html>
<head>
<title>Welcome to the City Manager</title>
</head>
</html>
<body>
<form id="form1" method="post"
action="/CityManagerWeb/mainmenuresponder.do">
<table style="width:100%">
<tr>
<td style="width:100%" align="center">
<h1>Welcome to the World City Manager</h1>
</td>
</tr>
<tr>
<td>
<h3>What would you like to do today?</h3>
</td>
</tr>
<tr>
<td>
<select id="menuChoice" name="menuChoice">
<option id="1" value="1">
List Cities
</option>
<option id="2" value="2">
Add a new city
</option>
<option id="3" value="3">
Delete a city
</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="adminoptions" id="optionDatabase" value="useDB" />Use Database<br>
<input type="checkbox" name="adminoptions" id="optionEmail" value="sendEmail" />Send Confirmation<br>
</td>
</tr>
<tr>
<td>
<input name="chooser" type="submit" value="Choose" />
</td>
</tr>
</table>
</form>
</body>
ListCities.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Listing Cities</title>
</head>
<body>
<table style="width:450px;">
<tr>
<td style="width:150px;"><b>COUNTRY</b></td>
<td style="width:300px;"><b>CITY</b></td>
</tr>
<tr>
<td>Russia</td>
<td>Moscow</td>
</tr>
<tr>
<td>England</td>
<td>London</td>
</tr>
<tr>
<td>United States</td>
<td>Washington, D.C.</td>
</tr>
</table>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>CityManagerWebStarter</display-name>
<servlet>
<servlet-name>citymanagerwebstarter</servlet-name>
<servlet-class>company.citymanagerweb.servlets</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>citymanagerwebstarter</servlet-name>
<url-pattern>/citymanagerwebstarter/mainmenuresponder.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
Thanks for any suggestions/help.
A fairly common problem I'm seeing these days is that people are using the latest IDE tooling that generates their web projects using the Servlet 3.0 specification i.e. the files generated use the new #WebServlet, #WebFilter etc. annotations way of doing things against the traditional deployment descriptor web.xml. But, they follow these old Servlet 2.x tutorials online and end up configuring the same servlet twice; once with the annotations and once again in the web.xml. This would lead to your server responding in undefined ways and must be avoided.
So, you can safely get rid of the following from your web.xml:
<servlet>
<servlet-name>citymanagerwebstarter</servlet-name>
<servlet-class>company.citymanagerweb.servlets</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>citymanagerwebstarter</servlet-name>
<url-pattern>/citymanagerwebstarter/mainmenuresponder.do</url-pattern>
</servlet-mapping>
The next issue is that your web application's context root is never a part of your servlet or filter's url-pattern. So, your annotation should be like
#WebServlet("/mainmenuresponder.do")
public class MainMenuResponder extends HttpServlet {
Lastly, though it works as is, your form's action attribute shouldn't hard code the context root like that. I suggest you use a relative URL there as well.
<form id="form1" method="post" action="mainmenuresponder.do">
Notice, that unlike the servlets, you can't put a leading / in the action here.
If citymanagerwebstarter is the content root. It should not be part of the url parttern in web.xml and #WebServlet annotation.
hi all I have a LoginServlet that has the functionality to log in a user however I have a jsp page with the styling I'd to use. I am unsure how I can use the functionality from my LoginServlet in my login.jsp
here is the entirety of my code for the LoginServlet, I am aware I have coded to display a page but I need to use this jsp page to display. This is a uni assignment I have been given and it's part of the requirement that we use JSP for display.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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.RequestDispatcher;
/**
* 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
}
private void sendLoginForm(HttpServletResponse response,
boolean withErrorMessage)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Login</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<CENTER>");
if (withErrorMessage)
out.println("Login failed. Please try again.<BR>");
out.println("<BR>");
out.println("<BR><H2>Login Page</H2>");
out.println("<BR>");
out.println("<BR>Please enter your user name and password.");
out.println("<BR>");
out.println("<BR><FORM METHOD=POST>");
out.println("<TABLE>");
out.println("<TR>");
out.println("<TD>User Name:</TD>");
out.println("<TD><INPUT TYPE=TEXT NAME=uniid></TD>");
out.println("</TR>");
out.println("<TR>");
out.println("<TD>Password:</TD>");
out.println("<TD><INPUT TYPE=PASSWORD NAME=password></TD>");
out.println("</TR>");
out.println("<TR>");
out.println("<TD ALIGN=RIGHT COLSPAN=2>");
out.println("<INPUT TYPE=SUBMIT VALUE=Login></TD>");
out.println("</TR>");
out.println("</TABLE>");
out.println("</FORM>");
out.println("</CENTER>");
out.println("</BODY>");
out.println("</HTML>");
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
sendLoginForm(response, false);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String uniid = request.getParameter("uniid");
String password = request.getParameter("password");
if (login(uniid, password)) {
/*RequestDispatcher rd =
request.getRequestDispatcher("AnotherServlet");
rd.forward(request, response); */
response.sendRedirect("home_student.jsp");
}
else {
sendLoginForm(response, true);
}
}
boolean login(String uniid, String password) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got connection");
Statement s = con.createStatement();
String sql = "SELECT uniid FROM user" +
" WHERE uniid='" + uniid + "'" +
" AND password='" + password + "'";
ResultSet rs = s.executeQuery(sql);
if (rs.next()) {
return true;
}
rs.close();
s.close();
con.close();
}
catch (ClassNotFoundException e) {
System.out.println(e.toString());
}
catch (SQLException e) {
System.out.println(e.toString());
}
catch (Exception e) {
System.out.println(e.toString());
}
return false;
}
}
here is my jsp page
<%# 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Mars University Lab System</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen">
</head>
<body>
<jsp:include page="header.jsp"/>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<div id = "centrecontent">
<table border="0" cellpadding="2">
<tr>
<td width="500px" align="center">
<br>
<font size="5">Welcome to <i>The Department of <br>Rocket Science</i> Lab System<br></font>
<br>
For <b>Students</b> you can enrol in labs<br> and manage the labs you're enrolled in.<br><br>
For <b>Tutors</b> you can view the labs<br> you're teaching and record attendence.<br><br>
For <b>Lecturers</b> you can create and<br> manage lab classes, register Tutors and<br> assign those Tutors to labs.<br><br>
</td>
<td width="500px">
<table border="0" align="center">
<tr>
<td align="center">
<table border="0" align="center">
<tr> <br><br><b>Existing Member? <br>Sign In Here!</b><br>
<td align="right">
<form name ="login" METHOD=POST ACTION="SaveSession.jsp">
Username: <input type="text" name="username"/><br />
Password: <input type="password" name="pword"/><br />
<input type=SUBMIT value="Login" name="Submit" />
</td>
</tr>
</table>
<br><br><br><br>
<form name="search_cat_bar" method="get" action="">
<input type="hidden" name="dff_view" value="grid">
Search:<input type="text" name="dff_keyword" size="30" maxlength="50"> <br>in
<select name="dff_cat1num" size="1">
<option value="-1">All Subjects
<option value="-2">--------------
<option value="101">CSE2ICE
<option value="193">CSE3PRA
<option value="193">CSE3PRB
<option value="193">CSE3WAE
</select>
<input type="submit" value="Find">
</form>
</td>
</tr>
</table>
</td>
</tr>
</table>
<table>
<tr>
</tr>
</table>
</div>
<jsp:include page="footer.jsp"/>
</body>
</html>
I'd like the login.jsp page to call my LoginServlet for the login functions.
You can call servlet by this way:
web.xml
<servlet>
<servlet-name>UserLogin</servlet-name>
<servlet-class>com.servlet.LoginServlet</servlet-class>//full class path
</servlet>
<servlet-mapping>
<servlet-name>UserLogin</servlet-name>
<url-pattern>/servlet/login</url-pattern>
</servlet-mapping>
login.jsp
<form name="login" action="<%=request.getContextPath()%>/servlet/login" method="post">
</form>
Servlet:
Login check and also you can send just error message to login page and display message like,
res.sendRedirect(req.getContextPath()+"/webpages/login.jsp?login=failed");
And in login.jsp you can retrieve parameter request.getParameter("login") and display proper message
add action in the html form tag.
action is LoginServlet URL.
It's easier to have the standard way of doing this:
Have jsp page with a form, to receive inputs from the user.
Have a servlet to process the data.
If there is a problem, set an error message and redirect the user to the login page. Otherwise redirect him to the destination.
Do not forget to set your form's action the address of your servlet.
Ok I'm stumped. I am writing a Spring based app that queries a web service for information to load a SELECT object based on the user's id. I've set up the web.xml and servlet xml files, design the initial page and have a redirect from an index.jsp file (the final system will reside under a Tomcat / IIS config) with a hard coded value for the username for the time being.
Every time I try to run it I get a 404 error and nothing in the Tomcat logs. I am relatively new to JSP / Spring so this is driving me nuts as I can't seem to find the problem.
I have tried removing the reference to the web service calls and still the pages to not load.
What am I missing?
Below is the code minus stylesheets and images:
UserDatabaseProject.java
/**
*
*/
package enterprisesearch.domain;
/**
* #author bob
*
*/
public class UserDatabaseProject
{
private String _msUserName = "";
private String _msDatabaseName = "";
private String _msDatabaseDescription = "";
private String _msProjectName = "";
private String _msProjectDescription = "";
public UserDatabaseProject()
{
}
public UserDatabaseProject(String psUserName, String psDatabaseName, String psDatabaseDescription, String psProjectName, String psProjectDescription)
{
this._msUserName = psUserName;
this._msDatabaseName = psDatabaseName;
this._msDatabaseDescription = psDatabaseDescription;
this.setProjectName(psProjectName);
this.setProjectDescription(psProjectDescription);
}
/**
* #return the _msProjectName
*/
public final String getProjectName()
{
return this._msProjectName;
}
/**
* #param _msProjectName the _msProjectName to set
*/
public final void setProjectName(String psProjectName)
{
this._msProjectName = psProjectName;
}
/**
* #return the _msProjectDescription
*/
public final String getProjectDescription()
{
return this._msProjectDescription;
}
/**
* #param _msProjectDescription the _msProjectDescription to set
*/
public final void setProjectDescription(String psProjectDescription)
{
this._msProjectDescription = psProjectDescription;
}
/**
* #return the _msUserName
*/
public final String getUserName()
{
return this._msUserName;
}
/**
* #param _msUserName the _msUserName to set
*/
public final void setUserName(String psUserName)
{
this._msUserName = psUserName;
}
/**
* #return the _msDatabaseName
*/
public final String getDatabaseName()
{
return this._msDatabaseName;
}
/**
* #param _msDatabaseName the _msDatabaseName to set
*/
public final void setDatabaseName(String psDatabaseName)
{
this._msDatabaseName = psDatabaseName;
}
/**
* #return the _msDatabaseDescription
*/
public final String getDatabaseDescription()
{
return this._msDatabaseDescription;
}
/**
* #param _msDatabaseDescription the _msDatabaseDescription to set
*/
public final void setDatabaseDescription(String psDatabaseDescription)
{
this._msDatabaseDescription = psDatabaseDescription;
}
}
DouglasService.java
/**
*
*/
package enterprisesearch.domain.service;
import java.io.StringReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import gov.sec.com.IDouglas;
import enterprisesearch.domain.UserDatabaseProject;
/**
* #author bob
*
*/
public class DouglasService
{
private IDouglas _mtDouglas;
private static Map<Integer, UserDatabaseProject> _muspUserDatabaseProjects = new HashMap<Integer, UserDatabaseProject>();
public DouglasService(String psDouglasUrl)
{
//String endPointAddress = "http://localhost:8080/Douglas/services/Douglas?wsdl";
//ApplicationContext acContext = new ClassPathXmlApplicationContext("context.xml");
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(IDouglas.class);
factory.setAddress(psDouglasUrl);
this._mtDouglas = (IDouglas) factory.create();
}
public String getSecurityToken(String psUserId)
{
String sReturn = "";
this._mtDouglas.getSecurityToken(psUserId);
return sReturn;
}
public String getProjectOptions(String psProjectName)
{
String sReturn = "";
this._mtDouglas.getProjectOptions(psProjectName);
return sReturn;
}
public String getDatabaseFilters(String psDatabaseName)
{
String sReturn = "";
this._mtDouglas.getDatabaseFilters(psDatabaseName);
return sReturn;
}
public Collection<UserDatabaseProject> getUserDatabaseProjects(String psUserName)
{
String sReturn = "";
String sResult = this._mtDouglas.getUserDatabaseProjects(psUserName);
XPathFactory xfactory = XPathFactory.newInstance();
XPath xPath = xfactory.newXPath();
StringReader sr = new StringReader(sResult);
NodeList databases = null;
try
{
databases = (NodeList) xPath.evaluate("/douglasresponse/responsedata/databases", new InputSource(new StringReader(sResult)), XPathConstants.NODESET);
for (int i = 0; i < databases.getLength(); i++)
{
Element elDatabase = (Element) databases.item(i);
String sUserName = xPath.evaluate("database/username", elDatabase);
String sDatabaseName = xPath.evaluate("database/databasename", elDatabase);
String sDatabaseDescription = xPath.evaluate("database/databasedescription", elDatabase);
String sProjectName = xPath.evaluate("database/projectname", elDatabase);
String sProjectDescription = xPath.evaluate("database/projectdescription", elDatabase);
this._muspUserDatabaseProjects.put(new Integer(i), new UserDatabaseProject(sUserName, sDatabaseName, sDatabaseDescription, sProjectName, sProjectDescription));
}
}
catch(XPathExpressionException ex)
{
System.out.print(ex.getMessage());
}
return _muspUserDatabaseProjects.values();
}
public String executeTextQuery(String psSecurityToken, String psProjectName, String psDatabase, String psQueryText, String psOptions, String psFilters)
{
String sReturn = "";
this._mtDouglas.executeTextQuery(psSecurityToken, psProjectName, psDatabase, psQueryText, psOptions, psFilters);
return sReturn;
}
public String executeGetContent(String psSecurityToken, String psProjects, String psDatabases, String psOptions)
{
String sReturn = "";
this._mtDouglas.executeGetContent(psSecurityToken, psProjects, psDatabases, psOptions);
return sReturn;
}
public String executeGetSimilar(String psSecurityToken, String psProjects, String psDatabases, String psOptions)
{
String sReturn = "";
this._mtDouglas.executeGetSimilar(psSecurityToken, psProjects, psDatabases, psOptions);
return sReturn;
}
}
SearchController.java
package enterprisesearch.web;
import enterprisesearch.domain.UserDatabaseProject;
import enterprisesearch.domain.service.DouglasService;
import java.util.Collection;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
#Controller
public class SearchController
{
//protected final Log logger = LogFactory.getLog(getClass());
private DouglasService dgWebService = new DouglasService("http://localhost:8080/Douglas/services/Douglas");
#RequestMapping("/search.html")
#ModelAttribute("userprojects")
public Collection<UserDatabaseProject> getUserProjects(#RequestParam(value="username", required=true) String psUsername)
{
return this.dgWebService.getUserDatabaseProjects(psUsername);
}
//#RequestMapping("/search.html")
//#ModelAttribute("testmessage")
//public String setMessage()
//{
// return "This is a test!";
//}
}
/WEB-INF/jsp/index.jsp
<jsp:forward page="search.html">
<jsp:param value="lymana" name="username"/>
</jsp:forward>
/WEB-INF/jsp/search.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Enterprise Search</title>
<link href="assets/style_sheets/main.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" language="javascript" src="assets/scripts/controls.js"></script>
</head>
<body>
<form:form method="post" action="" modelAttribute="search">
<table width="100%" border="0" style="border-collapse:collapse; border-spacing: 0px;" cellspacing="0">
<tr id="pageHeader">
<td id="pageHeaderLeft"><img src="assets/images/OCIE_left-1.jpg" style="float:left;" /></td>
<td id="pageHeaderRight"><img src="assets/images/OCIE_right.jpg" /></td>
</tr>
<tr>
<td valign="top" width="50%">
<div id="leftContainer">
<div class="blockHeader">
Text Search
</div>
<div id="TextBlock" class="blockControl">
<label for="taSearchText">Search Text:</label><br />
<textarea id="taSearchText" cols="60" rows="7" style="margin-bottom: .5em;"></textarea>
<br />
<table border="0" style="border-collapse:collapse; border-spacing: 0px;" cellspacing="0">
<tr>
<td width="30%" style="padding: 0em 0em .5em .5em; text-align:right; vertical-align:middle;">
<label for="sltResultsPerPage">Results per page:</label>
</td>
<td width="30%" style="padding: 0em .5em .5em 0em; text-align:left; vertical-align:middle;">
<select id="sltResultsPerPage">
<option value="10">10 per page</option>
<option value="20">20 per page</option>
<option value="50">50 per page</option>
<option value="100">100 per page</option>
</select>
</td>
<td width="40%" rowspan="3" valign="middle" align="center">
<input id="btnSearch" type="button" value="Search" />
</td>
</tr>
<tr>
<td style="padding: 0em 0em .5em .5em; text-align:right; vertical-align:middle;">
<label for="sltSort">Sort results by:</label>
</td>
<td style="padding: 0em .5em .5em 0em; text-align:left; vertical-align:middle;">
<select id="sltSort">
<option value="relevance">Relevance</option>
<option value="dateAsc">Date (Ascending)</option>
<option value="dateDesc">Date (Descending)</option>
</select>
</td>
</tr>
<tr>
<td style="padding: 0em 0em .5em .5em; text-align:right; vertical-align:middle;">
<label for="sltRelevance">Relevance:</label>
</td>
<td style="padding: 0em .5em .5em 0em; text-align:left; vertical-align:middle;">
<select id="sltRelevance">
<option value="90">90% relevant</option>
<option value="80">80% relevant</option>
<option value="70">70% relevant</option>
<option value="60">60% relevant</option>
<option value="50">50% relevant</option>
</select>
</td>
</tr>
</table>
</div><!-- end of textblock -->
<div class="blockHeader"><img src="assets/images/RightArrowClosed16x16.jpg" onclick="setAdvancedVisible('BooleanBlock');" />
Boolean
</div>
<div id="BooleanBlock" class="blockControl" style="visibility:hidden; display:none;">Boolean Search controls here<br /><br /><br /><br />
</div>
<div class="blockHeader">
<img src="assets/images/RightArrowClosed16x16.jpg" onclick="setAdvancedVisible('ParametricBlock');" />
Parametric
</div>
<div id="ParametricBlock" class="blockControl" style="visibility:hidden; display:none;">Parametric Search controls here<br /><br /><br /><br />
</div>
<div class="blockHeader"><img src="assets/images/RightArrowClosed16x16.jpg" onclick="setAdvancedVisible('ClusterBlock');" />
Cluster
</div>
<div id="ClusterBlock" class="blockControl" style="visibility:hidden; display:none;">Cluster results here<br /><br /><br /><br />
</div>
</div>
</td>
<td valign="top" width="50%">
<div id="rightContainer">
<div class="blockHeader"><img src="assets/images/RightArrowClosed16x16.jpg" onclick="setAdvancedVisible('ProjectsBlock');"/>
Projects
</div>
<div id="ProjectsBlock" class="blockControl">
<label for="sltProjects">Projects:</label><br />
<select id="sltProjects" size="10" onclick="">
<option value="all">All available projects</option>
<c:forEach items="${userprojects}" var="UserDatabaseProject">
<form:option value="${UserDatabaseProject._msProjectName}">${UserDatabaseProject._msProjectDescription}</form:option>
</c:forEach>
</select>
</div>
<div class="blockHeader"><img src="assets/images/RightArrowClosed16x16.jpg" onclick="setAdvancedVisible('DatabasesBlock');"/>
Databases
</div>
<div id="DatabasesBlock" class="blockControl">
<label for="sltDatabases">Databases:</label><br />
<select id="sltDatabases" size="10" onclick="">
<option value="all">All available databases</option>
<option value="dbTCR20">TCR20 Database Primary</option>
<option value="dbTCR20-1">TCR20 Database Secondary</option>
<option value="dbECC">ECC Emails</option>
</select>
</div>
<div class="blockHeader"><img src="assets/images/RightArrowClosed16x16.jpg" onclick="setAdvancedVisible('FiltersBlock');"/>
Filters
</div>
<div id="FiltersBlock" class="blockControl">
<label for="sltFilters">Filters:</label><br />
<select id="sltFilters" size="10" onclick="createInput();" multiple="multiple" >
<option value="Comment">TCR20 - Comment</option>
<option value="TCR Subject">TCR20 - Subject</option>
<option value="From Address">ECC - From Address</option>
<option value="ECC Subject">ECC - Subject</option>
<option value="Message Text">ECC - Message Text</option>
</select>
</div>
<div class="blockHeader"><img src="assets/images/RightArrowClosed16x16.jpg" onclick="setAdvancedVisible('SelectedBlock');"/>
<span>Selected Filters</span>
</div>
<div id="SelectedBlock" class="blockControl">
</div>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<hr />
<div>
<div class="resultsHeader">
Search Results
</div>
<div class="resultsControl" style="margin-bottom: 15px;">
</div>
</div>
</td>
</tr>
<tr>
<td id="footer" colspan="2"><hr />Some footer stuff goes here!</td>
</tr>
</table>
</form:form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- Register a servlet that despatches requests to registered controllers -->
<servlet>
<servlet-name>es</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Send all .html files to the Spring dispatcher servlet -->
<servlet-mapping>
<servlet-name>es</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<!-- Define the web application entry point -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
es.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- Auto-detect controllers in this package -->
<context:component-scan base-package="enterprisesearch.web"/>
<!-- Prepend /WEB-INF/jsp/ and append .jsp to the view name -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
Your controller is bound to <contextname>/search.html, not index.html - <contextname> referring to the context that Tomcat maps your application to, which usually is the name of the WAR file but can be anything if you have configured Tomcat specially.
Turn up Spring's logging and you will see it logging warnings when you request a URL that it has no mapping for.
your controller was worng, you must return a ModalAndView or NameOfView not Collection<UserDatabaseProject>
please try this :
#RequestMapping("/search.html")
#ModelAttribute("userprojects")
public ModelAndMap getUserProjects(#RequestParam(value="username", required=true) String psUsername){
ModelMap modelMap = new ModelMap();
modelMap.put("userprojects", this.dgWebService.getUserDatabaseProjects(psUsername));
return new ModelAndView("index", modelMap);
}
Follow any good tutorial on spring mvc.
your return type should be either ModelAndView or its related type (since you are using InternalResourceViewResolved) or the String name of view.
In case of Rest Based approach or ajax you can return the data as collection (which get converted into json). For this approach you need to mark your controller as #RestController on class level or #ResponseBody on method level. This approach is mostly used in Ajax calls in which you need to iterate through the json response received and set the data on that page.
In Spring mvc based approach you need to add all the objects in the ModelAndView and set the view name as below. Then you can access the objects on that view using el.
#RequestMapping("/search.html")
#ModelAttribute("userprojects")
public ModelAndView getUserProjects(#RequestParam(value="username", required=true) String psUsername){
ModelAndView modelAndView = new ModelAndView();
// add all the required data which you need on next view page
modelAndView.addObject("userprojects", this.dgWebService.getUserDatabaseProjects(psUsername));
// set the view name which needs to be displayed
modelAndView.setViewName("search");
return modelAndView
}
In Jsp access the userprojects as:
${userprojects._msProjectName}