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>
Related
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();
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);
}
}
}
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.
SO first off let me begin by saying that my servlet loads the option lists in a form i have just fine. The problem is when i start from the index.jsp like i want, the lists dont load. So basically, i want to click a link on the index.jsp to take me to the servlet to then redirect me to the correct page based on the link clicked. Maybe I have been looking at this too long and just need fresh eyes but I cant get why it wont work.
I have included my Index.jsp and servlet
Index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.ArrayList" %>
<!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>Insert title here</title>
</head>
<body>
<form method="get" action="customerServlet">
Add Customer
<br/>
Add Pet
</form>
</body>
</html>
Servlet
package edu.witc.Assignment03.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//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 edu.witc.Assignment03.model.Customer;
import edu.witc.Assignment03.model.Phone;
import edu.witc.Assignment03.model.States;
#WebServlet(description = "servlet to get act as controller between form and models", urlPatterns = { "/customerServlet","/addCustomer","/addPet" })
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public CustomerServlet() {
super();
}
private void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
Phone phone = new Phone();
States state = new States();
Collection<Phone> phones = phone.getPhoneCollection();
Collection<States> states = state.getStateCollection();
session.setAttribute("phones", phones);
session.setAttribute("states", states);
request.getRequestDispatcher("/customerManagement.jsp").forward(request, response);
//}
}
private List<edu.witc.Assignment03.model.Customer> customers = new ArrayList<Customer>();
private void addCustomer(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/customerManagement.jsp";
processRequest(request, response);
request.getRequestDispatcher(url).forward(request,response);
}
private void addPet(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/pets.jsp";
request.getRequestDispatcher(url).forward(request,response);
}
private Customer getCustomer(int customerId) {
for (Customer customer : customers) {
if (customer.getCustomerId() == customerId) {
return customer;
}
}
return null;
}
private void sendEditCustomerForm(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String url = "/customerManagement.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String uri = request.getRequestURI();
if (uri.endsWith("/addCustomer")) {
addCustomer(response, request);
} else if (uri.endsWith("/addPet")) {
addPet(response, request);
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
// update customer
int customerId = 0;
try {
customerId =
Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
}
Customer customer = getCustomer(customerId);
if (customer != null) {
customer.setFirstName(request.getParameter("firstName"));
customer.setLastName(request.getParameter("lastName"));
customer.setEmail(request.getParameter("email"));
customer.setPhone(request.getParameter("phone"));
customer.setAddress(request.getParameter("address"));
customer.setCity(request.getParameter("city"));
customer.setZip(request.getParameter("zip"));
}
}
}
It would be easier to use one parameter and check the value than to manually parse the URL:
Add Customer
<br/>Add Pet
In your servlet:
String action = request.getParameter("action");
if("addCustomer".equals(action)) { ... }
else if("addPet".equals(action)) { ... }
if you are using "forms", this could be the solution to send params to servlet.
<form action="ServletName" method="POST">
<input type="text" name="paramName">
<input type="submit" value="Add">
</form>
In Servlet:
String costumerName = request.getParameter("paramName");
If you just use a link like href, you should send the param like:
<a href="ServletName?ID=12345">
In servlet, same.
String costumerName = request.getParameter("ID");
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 ?