Error passing parameters into a servlet - http

I want to implement a servlet to get the parameters from the browser and insert into db using http post not http get.
the servlet will recieve params from a url such as this http://localhost:8080/NewServlet?firstname=me&middlename=you&lastName=secret&location=here , and insert into the db, but Its like I cant do it properly.
here is the piece of code am trying to run
public class NewServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String firstName = request.getParameter("firstname");
String middleName = request.getParameter("middlename");
String lastName = request.getParameter("lastname");
String location = request.getParameter("location");
String result;
java.sql.Connection connDB = null;
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
}
try {
connDB = DriverManager.getConnection("jdbc:postgresql://" + "localhost" + ":" + 5432 + "/" + "mydb", "username", "secret");
connDB.setAutoCommit(false);
System.out.println("Connection established : [" + connDB.toString() + "]");
java.sql.Statement bankStmt = connDB.createStatement();
java.sql.Statement stt = connDB.createStatement();
bankStmt.execute("INSERT INTO full_names(firstname, secondname, lastname) VALUES('"+firstName+"', '"+middleName+"', '"+lastName+"' )");
java.sql.Statement bnk =connDB.createStatement();
bnk.execute("INSERT INTO employee_details(location) VALUES('"+location+"')");
}
connDB.commit();
} catch (SQLException ex) {
ex.printStackTrace();
try {
connDB.rollback();
} catch (SQLException ex1) {
ex1.printStackTrace();
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex1);
}
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
}
out.println("<b><font color='blue'>Your FirstName is :</font></b>"
+ "<b>"+ firstName +"</b>" + "<br>");
out.println("<b><font color='blue'>Your Middle Name is :</font></b>"
+ "<b>"+ middleName +"</b>" + "<br>");
out.println("<b><font color='blue'>Your Last Name is :</font></b>"
+ "<b>"+ lastName +"</b>");
}
}
When I try to run the code using the url http://localhost:8080/NewServlet?firstname=me&middlename=you&lastName=secret&location=here
I get the following error:
HTTP Status 405 - HTTP method GET is not supported by this URL
type Status report
message HTTP method GET is not supported by this URL
description The specified HTTP method is not allowed for the requested resource (HTTP method GET is not supported by this URL).

You have only defined the do Post() method in your servlet. But when you are accessing using http://localhost:8080/NewServlet?firstname=me&middlename=you&lastName=secret&location=here , the doGet() is called which you have not defined. Just copy and paste the code in the doPost() method inside a doGet() in the same servlet.
Like this :
public void doGet{
//your code
}

HTTP Status 405 - HTTP method GET is not supported by this URL
Well, this is already the whole answer at its own. You're sending a GET request, but your servlet implementation doesn't support it. According to the code you wrote, it only supports POST requests. You don't have a doGet() implementation anywhere, but only doPost().
I'm not sure what's the functional requirement is and why this error is unclear to you, but to get your code to run, you should either send a POST request instead, or to rename doPost method to doGet in your servlet.
Unrelated to the concrete problem, your code has other problems as well, among others SQL injection holes, DB resource leaking and mingling the view in the controller. To learn servlets properly, you may want to start at our servlets wiki page.

Related

How to send success and error messages to jQuery AJAX call from a webmethod

I am calling an asp.net webform's webmethod using jQuery AJAX, from an aspx page. When the webmethod experiences an exception I am throwing an HttpResponseException exception. I am not sure what's the best way to return a success message. In a Web API, I would have returned a ApiController.Created(HttpStatusCode) or Ok(200). But I don't see such an option available on a webmethod. In the AJAX call I have to handle success and error accordingly. The following is my code:
[WebMethod()]
public async Task<IHttpActionResult> ProcessData(CustomerData customerData)
{
try
{
HttpClient client = new HttpClient();
HttpResponseMessage resp = await client.PostAsync(<data>);
if (resp.IsSuccessStatusCode)
{
string result = await resp.Content.ReadAsStringAsync();
return ???;//how to send success message?
}
else
{
string reasonAndStatusCode = resp.StatusCode + "; " + resp.ReasonPhrase;
string errorMessage = "Method Name: ProcessData." +
"Did not process customer data." +
"Status Code and Reason: " +
reasonAndStatusCode;
HttpResponseMessage error = GenerateError(resp.StatusCode, errorMessage.ToString());
throw new HttpResponseException(error);
}
}
catch (Exception ex)
{
HttpResponseMessage error = GenerateError(HttpStatusCode.InternalServerError,
errorMessage.ToString());
throw new HttpResponseException(error);
}
}
You can change the response status code using HttpContext Current static object.
For example, if you want to send a 404 status code, see the code below.
HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.NotFound;

Creating error page in servlet filter causes error "Writer already obtained"

I'm creating a custom framework (something like portal) for numerous JSF 1.x and 2.x applications. For that purpose I created a servlet filter that "enrich" application HTML with framework menu, breadcrumb, logout, etc. In that filter I read app's HTML, modify it and write it to an output stream. So far everything worked great but now I'm having problem with creating a custom error page.
I tried to read a response status code and based on that code, I'm creating output HTML:
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest) req;
HttpServletResponse res = (HttpServletResponse) resp;
StringServletResponseWrapper responseWrapper = new StringServletResponseWrapper(res);
// Invoke resource, accumulating output in the wrapper.
chain.doFilter(req, responseWrapper);
String contentType = res.getContentType();
byte[] data;
if (contentType.contains("text/html")) {
String html = null;
int statusCode = res.getStatus();
LOG.debug("status: {}, committed: {}", statusCode, res.isCommitted());
if (statusCode != 200) {
html = "<!DOCTYPE html>\r\n" +
"<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n" +
"<head>\r\n" +
"<script type=\"text/javascript\" src=\"/path/to/jquery/jquery-1.11.1.min.js\"></script>\r\n" +
"<title>Error</title>\r\n" +
"</head>\r\n" +
"<body>\r\n" +
"<h1>Error</h1>\r\n" +
"</body>\r\n" +
"</html>";
Collection<String> headerNames = res.getHeaderNames();
Map<String, String> headerMap = new HashMap<String, String>();
for (String header : headerNames) {
headerMap.put(header, res.getHeader(header));
}
res.reset();
for (Map.Entry<String,String> entry : headerMap.entrySet()) {
res.setHeader(entry.getKey(), entry.getValue());
}
res.setStatus(statusCode);
response.setContentType("text/html");
} else {
html = responseWrapper.getCaptureAsString();
}
if (ObjectUtils.isNotEmpty(html)) {
// do some modification
String modifiedResponse = doModification(html);
data = modifiedResponse.getBytes("UTF-8");
response.setContentLength(data.length);
response.getOutputStream().write(data); // this line causes error
}
} else {
data = responseWrapper.getCaptureAsBytes();
response.setContentLength(data.length);
response.getOutputStream().write(data);
}
}
This code works without any problem if status code equals 200 (else clause), but when it's not equal to 200 (I triggered 404 error), the following error occures:
com.ibm.ws.webcontainer.webapp.WebApp logServletError SRVE0293E: [Servlet Error]-[Faces Servlet]: java.lang.IllegalStateException: SRVE0209E: Writer already obtained
I don't really understand why does this error appear. The only difference between two cases is HTML content which is valid in both cases. Any help?
Using Websphere Application Server 8.5.5.18.
EDIT: I've tried to call reset() and then set headers and status code again, but that reset() call causes an IllegalStateException - as stated in javadoc, apparently response has already been committed. As far as I understand, flush() method of ServletOutputStream could cause response to be committed, but I'm not calling it anywhere. I've also added some log to see if response really is committed. In both cases (status 200 and 404) response.isCommitted() returns true. Does that mean that response is committed before doFilter is called?
Option 1 - downgrade JAX-RS to 1.1
Once JAX-RS version is changed back to 1.1 the errors in SystemOut.log will not be shown.
Do the following steps:
Change the JAX-RS version to 1.1 using WAS 9 Admin console. See the detailed instructions at
https://www.ibm.com/support/knowledgecenter/SSEQTP_9.0.0/com.ibm.websphere.base.doc/ae/twbs_jaxrs_coexist_adminconsole.html
Option 2 - move chain.doFilter to the end of your doFilter method
chain.doFilter(req, resp);
}
Option 3 - Remove other usages of PrintWriter or OuputStream
Review application to determine if both PrintWriter and OuputStream were obtained. Modify the failing servlet/JSP to only obtain one or the other.

class variable set to null outside of a servlet

I wrote a simple servlet, in the doPost I got the user name and the password from a jspand authenticated the user by sending the password entered by the user to the data base(mysql). I got the data correctly and I am redirecting the user to another jsp page called welcome.jsp.
my question is , I wrote this method public String getUser(){return userNmae;}; I put it outside of the dopost method, however it is returning null. I have declared the variable userNmae as a class variable and when I debug , the variable contains a value in the dopost method , but it is null outside of the dopost method.why it is null outside of the dopost method?
I am calling getUser() method in the welcome.jsp page.
here is my code
public class UIclass extends HttpServlet {
public UIclass() { };
private String passWord = null;
private String userNmae = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("userName");
String password = request.getParameter("password");
Connection connection = null;
try {
connection = Connections.getConnection();
java.sql.PreparedStatement statement = connection.prepareStatement("SELECT PASSWORD,USERNAME FROM LOGIN where username =?");
statement.setString(1, name);
ResultSet resultset = statement.executeQuery();
while (resultset.next()) {
passWord = resultset.getString("PASSWORD");
userNmae = resultset.getString("USERNAME");
}
} catch (Exception e) {
// TODO: handle exception
} finally {
if (connection != null)
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
};
}
if (passWord.equalsIgnoreCase(password)) {
RequestDispatcher rd = request.getRequestDispatcher("welcome.jsp");
rd.forward(request, response);
}
}
public String getUser() {
return userNmae;
}
}
I'll answer by giving you a simpler example of what your code is actually doing:
Bottle bottle1 = new Bottle();
bottle1.setMessage("Hi there");
Bottle bottle2 = new Bottle();
System.out.println(bottle2.getMessage());
What would you expect this program to display? I would expect null, because you set a message on bottle1, and read the message from bottle2. These are two different bottles. When you put a message in a bottle, the message is in that bottle, not in the other bottles.
Your code does the same thing.
The servlet container creates an instance (unique) of UIclass. This is equivalent to creating the first bottle in my example.
The servlet is invoked when you send an HTTP request. It sets the user attribute in the servlet. This is equivalent to bottle1.setMessage("Hi there") in my example.
The container executes your JSP, which contains the code
<jsp:useBean id="uiclass" class="com.servlet.UIclass" scope="request">
This creates a new UIClass instance. It is equivalent to creating the second bottle in my example.
The JSP calls uiclass.getUser(). This is equivalent to getting the message from the second bottle in my example.
There are many, many things wrong in your code:
You shouldn't use scriptlets, and jsp:useBean tags
You should never create instances of servlets by yourself. A servlet is meant to be instanciated and called by the container.
You should realize that a unique servlet instance is called to serve, concurrently, all the requests of all the users to this servlet URL. Storing user-specific data in servlet attributes is thus really wrong
You probably want the user name to be available for all the subsequent requests of this user. That's what the HTTP session is for. You should store the user as an attribute of the HTTP session: request.getSession().setAttribute("userName", userName)
The JSP should use the JSP EL and the JSTL to access beans stored in the request or the session by the servlet:
<c:out value="${userName}"/>

Service Stack:Type definitions should start with a '{', expecting serialized type 'AuthResponse', got string starting with

i am using the following code to athenticate the user using ServiceStack basic auth provider in my asp.net application and receiving serilization exception.Please answer if anyone has solve this problem.Thank you.
I am using the following code in my asp.net application:
<asp:Button ID="btnAuth" runat="server" OnClick="btnAuth_Click" Text="Authenticate"/>
I am recieving exception on clien.Post method in code behind file.
protected void btnAuth_Click(object sender, EventArgs e)
{
try
{
var baseUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/api";
var client = new JsonServiceClient(baseUrl);
var authResponse = client.Post<AuthResponse>(new Auth { UserName = "admin", Password = "12345" });
if (authResponse.ResponseStatus.ErrorCode == null)
{
//Do Something here
}
}
catch (WebServiceException ex)
{
throw ex;
}
}
Followin is Exeception Detail which i am recieving on clien.Post method:
[SerializationException: Type definitions should start with a '{', expecting serialized type 'AuthResponse', got string starting with:
Serialization exception that reads "expecting serialized type 'X', got string starting with:" means that the serializer tries to create an object from an empty string instead of a proper json-formatted string ("{Class:{Property:{Sub:value}}}").
In this case, most likely cause is server at baseUrl returning no response (interpreted as empty string) to a POST request. Misconfigured URL or exception on server side, maybe?

Handling MaxUploadSizeExceededException with Spring MVC

How can I intercept and send custom error messages with file upload when file size is exceeded. I have an annotated exception handler in the controller class, but the request does not come to the controller. The answer I came across on this link How to handle MaxUploadSizeExceededException suggests implementing HandlerExceptionResolver.
Have things changed in Spring 3.5 or is that still the only solution?
I ended up implementing HandlerExceptionResolver:
#Component public class ExceptionResolverImpl implements HandlerExceptionResolver {
private static final Logger LOG = LoggerFactory.getLogger(ExceptionResolverImpl.class);
#Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object obj, Exception exc) {
if(exc instanceof MaxUploadSizeExceededException) {
response.setContentType("text/html");
response.setStatus(HttpStatus.REQUEST_ENTITY_TOO_LARGE.value());
try {
PrintWriter out = response.getWriter();
Long maxSizeInBytes = ((MaxUploadSizeExceededException) exc).getMaxUploadSize();
String message = "Maximum upload size of " + maxSizeInBytes + " Bytes per attachment exceeded";
//send json response
JSONObject json = new JSONObject();
json.put(REConstants.JSON_KEY_MESSAGE, message);
json.put(REConstants.JSON_KEY_SUCCESS, false);
String body = json.toString();
out.println("<html><body><textarea>" + body + "</textarea></body></html>");
return new ModelAndView();
}
catch (IOException e) {
LOG.error("Error writing to output stream", e);
}
}
//for default behaviour
return null;
}
}

Resources