how to send data from the form view to the backend? I want to use the collected data to create a JSON request.
#Controller
public class ControllerClass {
Connect connect = new Connect();
#RequestMapping(value = "/Search", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("Forms", "FlightDTO", new FlightDTO());
}
#RequestMapping(value = "/connect", method = RequestMethod.POST)
public String submit(#Valid #ModelAttribute("FlightDTO") FlightDTO flightDTO,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error.jsp";
}
return connect.connect();
}
}
View class collecting data.
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handling Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="#{/connect}" th:object="${FlightDTO}" method="post">
<p>Orgin: <input type="text" th:field="*{Origin}" /></p>
<p>Departure: <input type="text" th:field="*{Departure}" /></p>
<p>DateFrom: <input type="text" th:field="*{DateFrom}" /></p>
<p>DateTo: <input type="text" th:field="*{DateTo}" /></p>
<p>Currency: <input type="text" th:field="*{Currency}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
Class responsible for consume data JSON.
public class Connect {
public String connect() {
String output = null;
try {
UrlBuilder urlBuilder = new UrlBuilder();
urlBuilder.ulr();
System.out.println("URL String : " + urlBuilder.ulr());
URL url = new URL(urlBuilder.ulr());
HttpURLConnection conn = (HttpURLConnection) url.openConnection() ;
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : " + conn.getResponseCode());
}
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
output = response.toString();
} catch (Exception e) {
System.out.println("Exception Flight:- " + e);
}
return output;
}
}
Class that is responsible for collecting data from the view
public class FlightDTO {
private String dateFrom;
private String dateTo;
#Size(min = 2, max = 10)
private String origin;
#Size(min = 2, max = 10)
private String departure;
#Size(min = 2, max = 4)
private String currency;
My URL builder Class responsible for build request.
public class UrlBuilder extends FlightDTO {
private String key = "47c5ebee552ce27c902e7521b6ef3858";
public String ulr( ) {
String connectUrlString =
"http://api.travelpayouts.com/v1/prices/cheap?origin="
+ getOrigin() + "&destination=" + getDeparture() +
"&depart_date=" + getDateFrom() +
"¤cy=" + getCurrency() +
"&return_date=" + getDateTo() +
"&token=" + key;
return connectUrlString ;
}
}
I tried to solve my problem in many ways. Unfortunately to no avail, that's why I decided to create a thread. I could not find a similar problem. I was probably looking for a bad one. However, I do not know how to google
I get null response :
http://api.travelpayouts.com/v1/prices/cheap?origin=null&destination=null&depart_date=null¤cy=null&return_date=null&token=47c5ebee552ce27c902e7521b6ef3858
Above code will not work as you are creating new UrlBuilder object which will not have any values instead of passing flightDTO object from the controller.
Controller
#RequestMapping(value = "/connect", method = RequestMethod.POST)
public String submit(#Valid #ModelAttribute("FlightDTO") FlightDTO flightDTO,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error.jsp";
}
return connect.connect(flightDTO); //passing flightDTO object received from form
}
Connect
public String connect(FlightDTO flightDTO) { //Added new parameter to recevice flightDTO
String output = null;
try {
UrlBuilder urlBuilder = new UrlBuilder();
urlBuilder.setOrigin(flightDTO.getOrigin());
urlBuilder.setDestination(flightDTO.getDestination());
urlBuilder.setDateFrom(flightDTO.getDateFrom());
urlBuilder.setDateTo(flightDTO.getDateTo());
......//Set other required values
urlBuilder.ulr();
System.out.println("URL String : " + urlBuilder.ulr());
......//other code
}
}
Related
#PostMapping("/post")
public String write(#RequestParam("file") MultipartFile files, BoardDto boardDto) {
try {
String origFilename = files.getOriginalFilename();
String filename = new MD5Generator(origFilename).toString();
String savePath = System.getProperty("user.dir") + "\\files";
if (!new File(savePath).exists()) {
try {
new File(savePath).mkdir();
} catch(Exception e){
e.getStackTrace();
}
}
String filePath = savePath + "\\" + filename;
files.transferTo(new File(filePath));
FileDto fileDto = new FileDto();
fileDto.setOrigFilename(origFilename);
fileDto.setFilename(filename);
fileDto.setFilePath(filePath);
Long fileId = fileService.saveFile(fileDto);
boardDto.setFileId(fileId);
boardService.savePost(boardDto);
} catch(Exception e) {
e.printStackTrace();
}
return "redirect:/";
}
if (!new File(savePath).exists()) {
^
constructor File.File(Long,String,String,String) is not applicable
Description: I am working on a file upload project. but it's not working. File is just entity class and It's someone else's code. the guy worked fine but I'm not
You can try to rewrite this code using Files API.
For example: ...if (Files.notExists(Paths.get(savePath))) {...
It looks like you create too many File objects.
You can upload a file to a Spring controller using logic as follows:
Basic HTML that sends a file to a /upload controller:
<p>Upload an image</p>
<form method="POST" onsubmit="myFunction()" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="submit" value="Submit" />
</form>
<div>
Here is the controller:
// Upload a file.
#RequestMapping(value = "/upload", method = RequestMethod.POST)
#ResponseBody
public ModelAndView singleFileUpload(#RequestParam("file") MultipartFile file) {
try {
byte[] bytes = file.getBytes();
String name = file.getOriginalFilename() ;
// DO something with the file.
} catch (IOException e) {
e.printStackTrace();
}
return new ModelAndView(new RedirectView("photo"));
}
I want to make a UserUtil to auto make User and get the User's mobile and cookie in the txt file.
I finished auto insert the User's information into the mysql,but I can't auto write it into the txt file.
The main code about this:
public class UserUtil {
private static void createUser(int count) throws Exception {
// the code about insert into database not show here
// login,get the cookie
String urlString = "http://localhost:8080/login/toLogin";
File file = new File("my file location");
if (file.exists()) {
file.delete();
}
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(0);
for (int i = 0; i < users.size(); i++) {
User user = users.get(i);
URL url = new URL(urlString);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream out = httpURLConnection.getOutputStream();
String params = "mobile=" + user.getId() + "&password=" + MD5Util.inputPassToFormPass("123456");
// the params I test show the first line in database,such as mobile=1300000000&password=d3b1294a61a07da9b49b6e22b2cbd7f9
System.out.println(params);
out.write(params.getBytes());
out.flush();
InputStream inputStream = httpURLConnection.getInputStream();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while ((len = inputStream.read(buff)) >= 0) {
bout.write(buff, 0, len);
}
inputStream.close();
bout.close();
String response = new String(bout.toByteArray
// I test the response print my login.html content
System.out.println(response);
ObjectMapper mapper = new ObjectMapper();
RespBean respBean = mapper.readValue(response,RespBean.class);
String userCookie = ((String) respBean.getObj());
System.out.println("create userCookie : " + user.getId());
String row = user.getId() + "," + userCookie;
raf.seek(raf.length());
raf.write(row.getBytes());
raf.write("\r\n".getBytes());
System.out.println("write to file :" + user.getId());
}
raf.close();
System.out.println("over");
}
}
I run it , the error is:
Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
at [Source: (String)"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
<!-- jquery -->
<script type="text/javascript" src="/js/jquery.min.js"></script>
<!-- bootstrap -->
<link rel="stylesheet" type="text/css"
href="/bootstrap/css/bootstrap.min.css"/>
<script type="text/javascript" src="/bootstrap/js/bootstrap.min.js">
</script>
<!-- jquery-validator -->
<script type="text/javascript" src="/jquery-validation/jquery.validate"[truncated 2917 chars]; line: 1, column: 2]
at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1851)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:707)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:632)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._handleOddValue(ReaderBasedJsonParser.java:1947)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:776)
at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4664)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4513)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3468)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3436)
at com.example.demo.utils.UserUtil.createUser(UserUtil.java:85)
at com.example.demo.utils.UserUtil.main(UserUtil.java:108)
the UserUtil.java:85 is this line:
RespBean respBean = mapper.readValue(response,RespBean.class);
my RespBean :
package com.example.demo.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#NoArgsConstructor
#AllArgsConstructor
public class RespBean {
private long code;
private String message;
private Object obj;
/**
* Success
* #return
*/
private static RespBean success(){
return new RespBean(RespBeanEnum.SUCCESS.getCode(),RespBeanEnum.SUCCESS.getMessage(),null);
}
public static RespBean success(Object obj){
return new RespBean(RespBeanEnum.SUCCESS.getCode(),RespBeanEnum.SUCCESS.getMessage(),obj);
}
/**
* Fail
* #param respBeanEnum
* #return
*/
public static RespBean error(RespBeanEnum respBeanEnum){
return new RespBean(respBeanEnum.getCode(),respBeanEnum.getMessage(),null);
}
public static RespBean error(RespBeanEnum respBeanEnum,Object obj){
return new RespBean(respBeanEnum.getCode(),respBeanEnum.getMessage(),obj);
}
}
the RespBeanEnum:
#Getter
#ToString
#AllArgsConstructor
public enum RespBeanEnum {
// All
SUCCESS(200,"SUCCESS"),
ERROR(500,"Server error"),
// Login part
LOGIN_ERROR(500210,"username or password error"),
MOBILE_ERROR(500211,"mobile layout error"),
BIND_ERROR(500212,"parameter error"),
;
private final Integer code;
private final String message;
}
and my UserServiceImpl return is no problem
public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
// the login logic code don't show here
// the UUIDUtil is the util to make the cookie
String uuid = UUIDUtil.uuid();
CookieUtil.setCookie(request,response,"userCookie",uuid);
return RespBean.success(uuid);
}
Sorry for the long post and janky question.
I'm trying to figure out how to use an input textbox inside a form as a way to get the name of a city. With the city name, I'll then use it inside a method (getCitybyId) inside the MainController.
I'll then use it as the city name inside my api URL
Example:"http://api.openweathermap.org/data/2.5/weather?q=citynamevariable&appid=APIKey&units=imperial"
Is there any way I could do this? I'm pretty new to using spring boot and API's, and I have been trying to figure this out for a while.
Here's my code
MainController:
#RestController
public class MainController extends HttpServlet {
DataRepo dataRepo;
#RequestMapping(value = "/get", method = RequestMethod.GET)
public ModelAndView get(#RequestParam("name") String id) {
ModelAndView mv = new ModelAndView ("redirect:/");
String city = getCitybyId(id);
try{
JSONObject json = new JSONObject(city);
mv.addObject("Name", json.getString("name"));
mv.addObject("Temperature", json.getJSONObject("main").get("temp").toString());
mv.addObject("feels_like", json.getJSONObject("main").get("feels_like").toString());
mv.addObject("humidity", json.getJSONObject("main").get("humidity").toString());
mv.addObject("Wind", json.getJSONObject("wind").get("speed").toString());
}
catch (Exception e){
System.out.println(e.toString());
}
return mv;
}
private String getCitybyId(String name) {
try {
String apiKey = "key";
URL urlForGetRequest = new URL("http://api.openweathermap.org/data/2.5/weather?q=PUTCITYNAMEHERE&appid=key&units=imperial");
// These two are test to see if the method is actually getting data.
//String apiKey = "key";
// URL urlForGetRequest = new URL("https://superheroapi.com/api/" + apiKey + "/" + id);
HttpURLConnection connection = (HttpURLConnection) urlForGetRequest.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
int status = connection.getResponseCode();
System.out.println(status);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
return response.toString();
}
else {
return "Unexpected HTTP response";
}
} catch (Exception e) {
return "Exception: " + e.getMessage();
}
}
}
class City
{
private String name;
public String getName()
{
return name;
}
public City()
{
name = "DEFAULT";
}
public City(String n)
{
name = n;
}
}
HTML code
<!DOCTYPE html>
<html>
<head>
<title> Homework 4 application</title>
<style><%#include file ="../css/style.css"%></style>
</head>
<body>
<h1>Please Select A City</h1>
<form method="get" action="/get/">
<input type="text" id = "name" name="name" />
<input type="submit" value="Submit">
</form>
<div>
<h2>City</h2> <h3><%=request.getParameter("Name")%></h3>
<h2>Temperature</h2> <h3><%=request.getParameter("Temperature")%> Fahrenheit</h3>
<h2>Feels Like</h2> <h3><%=request.getParameter("feels_like")%> Fahrenheit</h3>
<h2>Humidity</h2> <h3><%=request.getParameter("humidity")%>%</h3>
<h2>Wind Speed</h2> <h3><%=request.getParameter("Wind")%> Mph</h3>
</div>
<hr>
<div>
<h2>Previously Requested Cities</h2>
<table class = "lemun">
<tr>
<td>City</td>
<td>Temperature</td>
<td>Feels Like</td>
<td>Humidity</td>
<td>Wind Speed</td>
</tr>
<c:forEach var = "Data" items = "${dataList}">
<tr>
<td>${Data.getName}</td>
<td>${Data.getTemperature}</td>
<td>${Data.getFeels_Like}</td>
<td>${Data.getHumidity}</td>
<td>${Data.getWind}</td>
</tr>
</c:forEach>
</table>
</div>
</hr>
</body>
</html>
Basically, I'm trying to use the User input from the textbox as a value for the cityname inside the openweathermap URL. Is this possible? If so may you show a way to do it?
Some background information of what I'm trying to achieve is a user hits the submit button on my JSP page it needs to send the message submitted to a text file and then I need to access the file and retrieve all the messages in the file in my JSP page. Please help me out, I have spent too long and I'm not sure what I need to do to be able to iterate over the hash map to show all the messages.
This is what my code looks like right now:
Controller:
public class TwitServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String twits = "";
String path = getServletContext().getRealPath("/WEB-INF/twit.txt");
HttpSession session = request.getSession();
String tweet = request.getParameter("tweet");
System.out.print(tweet);
String usern = (String) session.getAttribute("user");
String alias = (String) session.getAttribute("uname");
twitDB.insert(tweet, usern, alias, path);
Map test = twitDB.getTwit("/Users/emilio/Desktop/twit.txt");
session.setAttribute("test",test);
getServletContext()
.getRequestDispatcher("/home.jsp").forward(request, response);
}
}
Database(using txtfile for now):
ublic class twitDB {
public static void insert (String twit, String user, String uname, String path) throws IOException {
Date date = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("yyyy/MM/dd");
String dateString = ft.format(date);
File file = new File ("/Users/emilio/Desktop/twit.txt");
try ( PrintWriter out = new PrintWriter(new FileWriter(file, true))){
out.println("[#"+uname+"]:" + " " + dateString);
out.println(user);
out.println(twit);
out.println(".");
out.close();
}
catch (IOException iox) {
//do stuff with exception
iox.printStackTrace();
}
}
public static Map<String,Tweet> getTwit(String filename) throws IOException {
Map<String,Tweet> tweets = new HashMap<String,Tweet>();
File file = new File ("/Users/emilio/Desktop/twit.txt");
Scanner in = new Scanner(file);
while (in.hasNextLine()) {
String uname = in.nextLine();
String name = in.nextLine();
String twit = in.nextLine();
String filler = in.nextLine();
Tweet tweet = new Tweet(uname, name, twit);
tweets.put(uname, tweet);
tweets.put(name, tweet);
tweets.put(twit,tweet );
}
in.close();
return tweets;
}
}
Part of my JSP:
<button type="submit" method="post" class="btn btn-twitter">
<span class="glyphicon glyphicon-pencil"/>Tweet
</button>
</div>
</form>
</div>
</div>
<div class = "row feed">
<p>
<c:forEach items="${test}" var="test">
</c:forEach>
</p>
You are missing tag to do print if you are really getting data from the server.
<c:forEach items="${test}" var="test">
<c:out value="${test}"/>
</c:forEach>
I have to send JSON object data using JQuery+Ajax which will consume by RestFulWebServices. In backend I am using hibernate(ver 4)+Maven(ver 3)+spring(ver 4), MySql data base and ApacheTopcat server(ver 7). But my JqueryAjax code index.html client is not sending data over server.Please help me I am searching But their is no error in my Jquery Ajax part. If any other apart you need for tell me I will past here.
form.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
alert("1");
$("button").click(function(){
alert("2");
var custName = $('#custName').val();
var custMobile = $('#custMobile').value;
var custEmail = $('#custEmail').value;
var custAddress = $('#custAddress').value;
var JSONObject={"custName":custName, "custMobile": custMobile, "custEmail":custEmail,"custAddress":custAddress};
/*
var jsonData=JSON.stringify({
"custName": "Navin1",
"custMobile": "876532468",
"custEmail": "abc#gmal.com",
"custAddress": "BAnaore"
});
*/
var jsonData = JSON.stringify( JSONObject );
$.ajax({
url: "http://localhost:8080/HomeServiceProvider/customer/saveCustomer",
type: "POST",
dataType: "json",
data: jsonData,
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
processData:false,
success: function(response){
alert("scucess");
alert(JSON.stringify(response));
},
error: function(err){
alert("Fail");
alert(JSON.stringify(err));
}
});
});
});
</script>
</head>
<body>
<form>
<fieldset style="text-align:right; width:300px">
<legend><b>Registration Form</b></legend>
Name <input type="text" id="custName" name="custName"/><br/>
Mobile No <input type="text" id="custMobile" name="custMobile"/><br/>
Email <input type="text" id="custEmail" name="custEmail"/><br/>
Address <input type="text" id="custAddress" name="custAddress"/><br/>
<button>Save Data</button>
</fieldset>
</form>
</body>
</html>
my server url is
http://localhost:8080/HomeServiceProvider/customer/saveCustomer
My customer rest controller is
CustomerRestController
#RestController
#RequestMapping("/customer")
public class CustomerRestController {
private static Logger log = LogManager.getLogger(CustomerRestController.class);
#Value("${msg.customeradded}")
private String message;
#Value("${msg.successcode}")
private int code;
#Autowired
private CustomerService customerService;
#RequestMapping(value = "/saveCustomer", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody Status saveCustomer(#RequestBody Customer customer){
try {
customerService.saveCustomer(customer);
return new Status(code, message);
} catch (Exception e) {
return new Status(0, e.toString());
}
}
#RequestMapping(value="/getAllCustomer",method=RequestMethod.GET, headers="Accept=application/json")
public #ResponseBody List<Customer> getAllCustomer(){
List<Customer> customers = null;
try {
customers = customerService.getAllCustomer();
log.info("Size:"+customers.size());
log.info("customers:"+customers);
} catch(Exception e) {
e.printStackTrace();
}
return customers;
}
}
MyCustomer class Customer.Java for making table through Hibernate
#Entity
#Table(name = "customer", catalog = "service4homes")
public class Customer implements java.io.Serializable {
private Integer CId;
private String custName;
private String custMobile;
private String custEmail;
private String custAddress;
public Customer() {
}
public Customer(String custName, String custMobile, String custAddress) {
this.custName = custName;
this.custMobile = custMobile;
this.custAddress = custAddress;
}
public Customer(String custName, String custMobile, String custEmail,
String custAddress) {
this.custName = custName;
this.custMobile = custMobile;
this.custEmail = custEmail;
this.custAddress = custAddress;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "c_id", unique = true, nullable = false)
public Integer getCId() {
return this.CId;
}
public void setCId(Integer CId) {
this.CId = CId;
}
#Column(name = "cust_name", nullable = false, length = 50)
public String getCustName() {
return this.custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
#Column(name = "cust_mobile", nullable = false, length = 13)
public String getCustMobile() {
return this.custMobile;
}
public void setCustMobile(String custMobile) {
this.custMobile = custMobile;
}
#Column(name = "cust_email", length = 100)
public String getCustEmail() {
return this.custEmail;
}
public void setCustEmail(String custEmail) {
this.custEmail = custEmail;
}
#Column(name = "cust_address", nullable = false, length = 300)
public String getCustAddress() {
return this.custAddress;
}
public void setCustAddress(String custAddress) {
this.custAddress = custAddress;
}
}
When I run code What I am getting
form.index data
After click Button
$.ajax({
url:urlName,
type:"POST",
contentType: "application/json; charset=utf-8",
data: jsonString, //Stringified Json Object
async: false, //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
cache: false, //This will force requested pages not to be cached by the browser
processData:false, //To avoid making query String instead of JSON
success: function(resposeJsonObject){
}});
In Controller,
#RequestMapping(value = "/saveCustomer", method = RequestMethod.POST, consumes = "application/json")
public #ResponseBody Status saveCustomer(#RequestBody String jsonString){
//check whether u r receiving some data over here
System.out.println("received :" + jsonString);
try {
customerService.saveCustomer(customer);
return new Status(code, message);
} catch (Exception e) {
return new Status(0, e.toString());
}
}