Send post request on click of href in JSP - html

If we write something as follow:
Link
It will call GET method of that servlet. Can I send post request on click of a tag? Is it possible?
I know how to do this with Javascript but want to know if this could be done without JavaScript.

The solution is to surround the anchor in a form, which has the post method and the action you wish to execute. On the anchor put a javascript to submit the form
<form name="submitForm" method="POST" action="/servlet/ServletName">
<input type="hidden" name="param1" value="param1Value">
Click Me
</form>
edit
I think I should mention that this isn't a good idea.
Links take you to pages, that's what users understand them to do. To break the users assumptions and cause a link to POST, to do an irrevocable thing, is generally considered a bad idea.
Use a button, label it semantically, then your user knows that clicking this does something.
second edit
I really need to emphasise that this isn't a good idea at all.
This breaks the internet.

Only with javascript: create a <form action="MyServlet"> and submit it with form.submit()
You can also send POST with ajax (with jQuery: $.post("MyServlet", {param:param}))
But think about the semantics. With POST you should post data. And links are usually simply getting resources. (It's another story if your link is actually a button in disguise)

Code for Login.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>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post" name="credential">
Please enter userName :
<input type="text" name="un"><br>
Please enter PassWord :
<input type="text" name="pw"><br>
<input type="submit" value="Submit">
</form>
<form action="registerUser" name="registerUserForm" method="post">
If no user name and password then get a new one by clicking here
</form>
</body>
</html>
code for registerUser servlet::
package examplePackage;
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("/registerUser")
public class registerUser extends HttpServlet {
private static final long serialVersionUID = 1L;
public registerUser() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("registerUser");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}

Related

Spring html button replies with 404 error

My problem is that the submit-button below the form should redirect the registrating user to the welcome page after pressing it.
So far, the button wants to redirect to "welcome.html" but I constantly get an error 404, which I don't understand.
The welcome-html doesn't do anything fancy, just a simple text saying hello.
My Controller looks as follows:
package user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
#Controller
public class UserController {
#Autowired private UserRepository users;
#Autowired private UserManagement UserManager;
#GetMapping("/")
public String register(Model model, RegistrationForm form) {
System.out.println("Homepage");
model.addAttribute("form", form);
return "register";
}
#PostMapping("/register")
public String submit(#ModelAttribute("user")User user, RegistrationForm form,
Model model) {
User newUser = UserManager.createUser(form);
model.addAttribute("name", newUser.getAccount().getUsername());
model.addAttribute("street", newUser.getStreet());
model.addAttribute("PLZ", newUser.getPLZ());
model.addAttribute("mail", newUser.getMail());
model.addAttribute("number", newUser.getPhoneNumber());
users.save(newUser);
return "redirect:/welcome";
}
}
`
the register-page functions alright and the button too:
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" th:href="#{/resources/css/style.css}" href="../static/resources/css/style.css"/>
<title>register</title>
</head>
<body>
<header id ="mainHeader">
<div class ="container">
<h1>ClownCollege</h1>
</div>
</header>
<nav id="mainNav">
<div class="container">
<ul>
<li>Startseite
<li>Angebote
<li>Login
</ul>
</div>
</nav>
<div id="register">
<h2>Registrierung</h2>
<form modelAttribute = "form" method ="post" th:object=${form}>
<input type="text" field ="*{name}" />
<input type="text" field ="*{street}"/>
<input type="text" field ="*{PLZ}"/>
<input type="text" field ="*{mail}"/>
<input type="text" field ="*{number}"/>
<input type="text" field ="*{password}"/>
</form>
<button type ="submit">registrieren</button>
</div>
</body>
</html>
[source folders for path finding]
Please add action="register" on your <form>. It is specifying where does the form go to after submitting.
<form action="register" modelAttribute = "form" method ="post" th:object=${form}>
Remove <a href ="welcome.html">. Because your controller has redirect statement return "redirect:/welcome";, a html link is unnecessary.
It should be work as you expect.

Why am I getting 415 Unsupported Media Type in Spring MVC?

I'm getting the below error; I tried everything but not getting a resolution:
HTTP Status 415 – Unsupported Media Type
I am trying to send JSON object to the controller as put it in the #Requestbody
<%#page import="org.json.JSONObject"%>
<%# page language="java" contentType="application/json charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Welcome</h1>
Register
Delete
<%
JSONObject obj = new JSONObject();
obj.put("id", "1");
obj.put("name", "ABC");
%>
<form action="./jsonreq" method="post">
<input type="hidden" name="obj" id="obj" value="<%=obj%>">
<input type="submit" value="Submit"/>
</form>
</body>
</html>
2)Controller:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.springhibernate.bean.Employee;
import com.springhibernate.service.EmployeeService;
#Controller
public class RegistrationController {
#RequestMapping(path="/jsonreq", method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody Employee json(#RequestBody Employee obj)
{
System.out.println("JSON"+obj.toString());
return obj;
}
}
You're getting a 415 status because your browser is sending a request with a content type of application/x-www-form-urlencoded to an controller method which only accepts application/json.
Ask yourself if you really need to send JSON data in this way instead of as part of the form.
If you do, one way of accomplishing it is to use Javascript to compile the data from the form (or elsewhere) as JSON and make an XMLHttpRequest posting it to your server.
Another much less ideal way would be to remove your consumes constraint on the controller method, change the argument to #RequestParam("obj") String obj and parse the response in the controller method manually using an Autowired ObjectMapper using objectMapper.readValue(obj, Employee.class).

How to get value of generated row value for another action when generated submit button is clicked

I want to know how to get dynamically generated table row value (eg. empp_id) when clicking submit button that is generated for each row dynamically.
Below is my code. I used to generate each row and submit button for each row. I don't know how to use submit button to get and pass the value of 'id' column to another action.
Struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<package name="default" namespace="/" extends="struts-default">
<action name="edit" class="com.ojt.database.EditUserAction" method="execute">
<result name="success">edituser.jsp</result>
<result name="error"></result>
</action>
</struts>
EditUserAction.java
package com.ojt.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
#SuppressWarnings("serial")
public class EditUserAction extends ActionSupport {
List<User> liUser=null;
public List<User> getLiUser() {
return liUser;
}
public void setLiUser(List<User> liUser) {
this.liUser = liUser;
}
#Override
public String execute() throws Exception {
Connection conn;
String ret = "error";
try {
String url = "jdbc:mysql://localhost:3306/test";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, "root", "root");
String sql = "SELECT * FROM user";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
liUser=new ArrayList<User>();
while (rs.next()) {
User user = new User();
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setPassword(rs.getString(3));
liUser.add(user);
}
conn.close();
ret = "success";
System.out.println(ret);
} catch (Exception e) {
e.printStackTrace();
ret = "error";
System.out.println(ret);
}
return ret;
}
}
edituser.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="display" uri="http://displaytag.sf.net/el"%>
<!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>Edit</title>
</head>
<body>
<table cellpadding="20" align="center">
<tr>
<th>Id</th>
<th>Name</th>
<th>Password</th>
</tr>
<s:iterator value="liUser">
<tr>
<td><s:property value="id" /></td>
<td><s:property value="name" /></td>
<td><s:property value="password" /></td>
<td><s:submit value="Edit" theme="simple" action="review" method="POST"/></td>
</tr>
</s:iterator>
</table>
</body>
</html>
I need your help please.
I can't go any further, i am stuck here.
When you use <s:property/>, you are not creating a form tag, but just simple text. To send something printed with <s:property/>, use an <s:hidden/> in conjunction with it.
To send a list of object from JSP, you need to use the IteratorStatus object to specify an index.
You are not even using a form. You need a form to POST something in the standard, non-AJAX way.
You need two action's methods, or two actions: one to display the data, the other to edit it. In your execute() method you are initializing your list every time: liUser=new ArrayList<User>();, so the one coming from the page will always be lost.
You are in deep water. I suggest you to stop for a moment and take a closer look at HTML, HTTP, Struts2 and its tags, otherwise you will get frustrated quite soon.

How to get multiple images for same id from database in jsp servlet

index.jsp
This is my jsp code
<%# page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<sql:setDataSource var="webappDataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/bharatwellness"user="root" password="naveen" />
<sql:query dataSource="${webappDataSource}" sql="select * from individaulpartner " var="result" />
<table width="100%" border="1">
<c:forEach var="row" items="${result.rows}">
<tr>
<td>${row.id}</td>
<td>${row.fname}</td>
<td>
<img src="${pageContext.servletContext.contextPath }/ImageServlet?id=${row.id}" />
</td>
<td>
<a href="${pageContext.servletContext.contextPath }/ImageServlet?id=${row.id}" />certificate</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
ImageGetTest.java
This my servlet code
package com.server.servlet;
import java.io.IOException;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ImageServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://localhost/mydatabase";
final String User = "root";
final String Password = "password";
try {
Class.forName(JDBC_DRIVER);
Connection conn = DriverManager.getConnection(DB_URL, User, Password);
PreparedStatement stmt = conn.prepareStatement("select * from usertable where id=?");
stmt.setLong(1, Long.valueOf(request.getParameter("id")));
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
response.getOutputStream().write(rs.getBytes("image"));
response.getOutputStream().write(rs.getBytes("certificate1"));
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is my table from where i am fetching my data
I am able to show only single image or single certificate for one id . How can I show all file on jsp page. Please help me out...
You need to call the Sevlet for each individual image. So in your JSP you need to do somthing like:
<td>
<img src="${pageContext.servletContext.contextPath }/ImageServlet?id=${row.id}&name=image" />
<img src="${pageContext.servletContext.contextPath }/ImageServlet?id=${row.id}&name=certificate" />
</td>
and in your Servlet check the additional 'name' parameter to determine which image to send back:
if (rs.next()) {
if(request.getParameter("name").equals("image")
response.getOutputStream().write(rs.getBytes("image"));
}else{
response.getOutputStream().write(rs.getBytes("certificate1"));
}
}
The problem with all of this is that it is not dynamic. To make it handle any number of images for a given entity you need to have some knowledge of the available images when the JSP is processed and have a loop which will generate an <img/> tag for each image and call the Servlet with the necessary paramaters.
This will also probably involve some database update: images go into a different table with a FK to the corresponding user.
img_id user_id image_data
1 1 bytes
2 1 bytes
3 1 bytes
4 1 bytes
Now you get a handle on the image ids for the relevant user and load them one-by-one by passing the id to the Servlet.

HTML file not posting GET parameters in a GET request

I am trying a simple program with Java Servlet wherein a HTML page with a text box and a submit button will be displayed. Once the user enters the data and submits it, the next page will display a Hello . Calling the servlet URL with the GET parameter directly shows that it works fine. But when I open the HTML file and submit data from there, the GET request isn't formed properly, i.e. the parameters are not getting passed in the address of the 'action' URL.
Here is the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<form action="/TestServlt/TestClass" name="myform" method="get">
Enter your name: <input type="text name="username">
<br />
<input type="submit" value="Go">
</form>
</body>
</html>
and the servlet code:
package in.lguruprasad;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestClass extends HttpServlet implements Servlet {
static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter output = response.getWriter();
response.setContentType("text/html");
String name = request.getParameter("username");
output.println("Hello "+name+"!");
output.flush();
output.close();
}
}
The servlet is mapped to /TestServlt/TestClass URL and the form submit redirects http://localhost:8080/TestServlt/TestClass instead of http://localhost:8080/TestServlt/TestClass?username=<user input> which would work fine. The output I get is 'Hello null!'.
In all the browsers the form submits without the get parameter. I tried writing a similar doPost method, but that didn't work as well.
What is the issue here and how to fix it?
I am using Eclipse 3.1.2, Apache Tomcat 5.5, JDK 1.6.25 if that helps.
You are missing a quote in the html input:
Enter your name: <input type="text name="username">
should be
Enter your name: <input type="text" name="username">